RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
Release 2.19.0: vector map on MapLibre with an optional Mapbox map, Waze-style 3D view, same-road Waze alerts, device history search, MT7921AU WiFi 6E adapters
CIS-C0dfa3e812ec71
diff --git a/README.md b/README.mdindex 43db303..d28eb62 100644--- a/README.md+++ b/README.md@@ -75,7 +75,7 @@|---|---|| **What** | A non-rooted Android app that lists every Bluetooth LE and WiFi device around you with its vendor, type and signal, and flags law-enforcement and surveillance equipment || **How** | Receive-only: reads advertisements, beacons and cell info that devices broadcast publicly. Never transmits to, connects to or jams anything |-| **Runs on** | Android 8.0+ phones, Android Auto, plus optional ESP32 boards (OUI-Spy, GhostESP, Marauder, Flipper Zero + BFFB, FREE-WiLi 2) and USB WiFi adapters |+| **Runs on** | Android 8.0+ phones (64-bit ARM), Android Auto, plus optional ESP32 boards (OUI-Spy, GhostESP, Marauder, Flipper Zero + BFFB, FREE-WiLi 2) and USB WiFi adapters || **Costs** | Nothing. GPL-3.0, no ads, no account, no subscription, no analytics |## What it detects@@ -93,7 +93,7 @@| **Camera glasses** | Ray-Ban / Oakley Meta, Snap Spectacles, Vuzix, HeyCyan-based glasses such as Nilox Smart AI Glasses | Company IDs `0x0D53`, `0x03C2`, `0x060C`, Meta UUIDs, the HeyCyan SDK UUID, name tokens || **Fake cell towers** | IMSI catchers / cell-site simulators | Test network codes, sudden 4G→2G, cloned or reserved cell identities, unexpected networks || **Police aircraft** *(online, off by default)* | Police, sheriff, state patrol, federal and RCMP / provincial police aircraft, and unlisted aircraft circling low overhead | Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries |-| **Waze reports** *(online, off by default)* | Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), each with its own level: sound and voice, notification only, or silent. Shows what Waze says it is (hiding, mobile speed camera...) | Two sources: your own OpenWeb Ninja API key, or *Waze direct* (opt-in: no key, free, sends Waze your IP address and a position rounded to a 1 km grid). You set the alert range (100 m to 10 km), the map range, and how often Waze is asked (15 s to 5 min direct, 2 to 10 min OpenWeb Ninja), slower when parked and faster on fast roads. Scored by distance, age and driver confirmations and re-scored every second as you move, so an alert fires the moment a report comes into range, not at the next check. Optional: only alert for reports ahead of you, and spoken call-outs at 1 km, 500 m and 200 m. Third-party service, at your own risk |+| **Waze reports** *(online, off by default)* | Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), each with its own level: sound and voice, notification only, or silent. Shows what Waze says it is (hiding, mobile speed camera...) | Two sources: your own OpenWeb Ninja API key, or *Waze direct* (opt-in: no key, free, sends Waze your IP address and a position rounded to a 1 km grid). You set the alert range (100 m to 10 km), the map range, and how often Waze is asked (15 s to 5 min direct, 2 to 10 min OpenWeb Ninja), slower when parked and faster on fast roads. Scored by distance, age and driver confirmations and re-scored every second as you move, so an alert fires the moment a report comes into range, not at the next check. Optional: only alert for reports on the road you're on, ahead of you (checked against the map's roads: a parallel road, a cross street, an overpass or a report behind you stays quiet), and spoken call-outs at 1 km, 500 m and 200 m. Third-party service, at your own risk || **Card skimmers** | Bluetooth modules inside gas-pump and ATM skimmers | HC-05 / HC-06 / HC-03 / RN42 / BT04-A names, serial-port service || **Hacking tools** *(off by default)* | Flipper Zero, Pwnagotchi, WiFi Pineapple, ESP deauthers, evil twin WiFi networks, Bluetooth spam floods, **WiFi deauth attacks** | Flipper UUIDs / company ID `0x0E29` / IEEE block, Pwnagotchi beacon JSON, default SSIDs, same network name from two makers with mismatched security, bursts of new pairing pop-ups; with a USB WiFi adapter, floods of unprotected deauthentication frames knocking devices off a network || **Emergency vehicles (V2X, Europe)** | Police, fire, ambulance and safety cars that broadcast European car-to-car radio (ITS-G5) | Needs an ESP32-C5 with the [V2X2MAP](https://github.com/pit711/V2X2MAP) firmware: the vehicle's own role, light bar and siren state and position (CAM), and its "emergency vehicle approaching" warnings (DENM). Ordinary cars are counted, not listed. Not in North America, which uses C-V2X |@@ -139,10 +139,11 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer- Notification, Quick Settings tile and home-screen widget**Map & history**-- OpenStreetMap map with your GPS trace and every device pinned where its signal peaked, flagged devices at their pinpointed spot with its circle (tap a spot to list everything heard there), the same filter chips as the list (including Waze, which draws reports as coloured dots by type), self-centering+- Vector map ([MapLibre](https://maplibre.org) with [OpenFreeMap](https://openfreemap.org), OpenStreetMap data; light and a readable night map with shops, landmarks, one-way arrows and highway shields; optional [Mapbox](https://www.mapbox.com) map) with your GPS trace and every device pinned where its signal peaked, flagged devices at their pinpointed spot with its circle (tap a spot to list everything heard there), the same filter chips as the list (including Waze, which draws reports as coloured dots by type), self-centering- Optional **cell tower layer** (or the map's **Cells** chip): every tower seen while scanning, at the spot where its signal was strongest- **Record traces** of your route and the devices along it, with the screen off (with the network names each device asked for, when a USB adapter or Marauder board is plugged in)- **History map & timeline:** heatmap of where flagged equipment showed up, and when (hour of day, day of week)+- **Device history (search):** every device the app remembers, in range or not, searchable by address (with or without colons), name, vendor, type or your note, filtered to favorites, flagged before or seen today; tap one for its details page. History is kept as long as you set in Settings → Data**Driving**- **Android Auto** app: threat headline, next camera ahead, recent alerts, filtered device lists, cell towers, hardware status, live map with cameras and drones, OpenStreetMap turn-by-turn navigation, alerts through the car speakers with Mute 30 min / Ignore buttons@@ -151,10 +152,10 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer**Hardware**- ESP32 boards over USB OTG (OUI-Spy, GhostESP, Marauder incl. dual-band ESP32-C5 boards, or through a Flipper Zero) or Bluetooth (OUI-SPY App-Controlled) add their detections and extend range-- **USB WiFi adapters in monitor mode** over OTG, no root: RTL8811AU / RTL8821AU (e.g. ALFA AWUS036ACS, 2.4 GHz; 5 GHz experimental, Settings → External hardware), **RTL8812BU / RTL8822BU** (2.4 + 5 GHz, e.g. TP-Link Archer T3U, Wise Tiger AC1200), **RTL8814AU** (ALFA AWUS1900, 2.4 + 5 GHz), **MT7612U** (ALFA AWUS036ACM, 2.4 + 5 GHz), **RTL8187** (ALFA AWUS036H), **RT3070** (ALFA AWUS036NH / NEH) and, experimental, **AR9271** (ALFA AWUS036NHA). No Android scan limit, longer range, and **client devices** (laptops, phones, cameras connected to a network) the phone's WiFi scan can't see. Single-antenna dongles are detected and handled automatically+- **USB WiFi adapters in monitor mode** over OTG, no root: RTL8811AU / RTL8821AU (e.g. ALFA AWUS036ACS, 2.4 GHz; 5 GHz experimental, Settings → External hardware), **RTL8812BU / RTL8822BU** (2.4 + 5 GHz, e.g. TP-Link Archer T3U, Wise Tiger AC1200), **RTL8814AU** (ALFA AWUS1900, 2.4 + 5 GHz), **MT7612U** (ALFA AWUS036ACM, 2.4 + 5 GHz), **MT7921AU** (ALFA AWUS036AXML, WiFi 6E: 2.4 + 5 + **6 GHz**, experimental), **RTL8187** (ALFA AWUS036H), **RT3070** (ALFA AWUS036NH / NEH) and, experimental, **AR9271** (ALFA AWUS036NHA). No Android scan limit, longer range, and **client devices** (laptops, phones, cameras connected to a network) the phone's WiFi scan can't see. Single-antenna dongles are detected and handled automatically- **Requested networks:** the WiFi names nearby devices ask for (probe requests), from a USB adapter or a Marauder board, in an optional list; **watch** a name to get an alert whenever any device asks for it- **Record frames to .pcap** for Wireshark (Settings → External hardware): every frame a USB WiFi adapter or V2X board hears, with its channel and signal-- The ALFA AWUS036ACS's light blinks with received traffic+- The ALFA AWUS036ACS's light blinks with received traffic (Settings → External hardware switches it off, for the adapters whose light the app can control)- **More from every frame:** WPS maker / model / device name, a **probe fingerprint** that survives MAC randomization (watchable: "every device of this type"), and the real name of **hidden networks** when a device joins them**Interface**@@ -175,7 +176,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer## Quick start-Requires **Android 8.0 or newer**.+Requires **Android 8.0 or newer** on a 64-bit ARM phone (almost every phone since 2017; the release APK is about 30 MB).1. On your phone, tap **Download the app** above, or open the [latest release](https://github.com/CIS-C0/RFSentinel/releases/latest).2. Under **Assets**, tap the file ending in **`-release.apk`** (not the "Source code" archives).@@ -259,7 +260,11 @@ the raw advertisement.- **North up / heading up / 3D:** the compass button steps through north up,heading up (turns with your direction of travel while moving), and a **3D drivingview** - tilted in perspective with your position low on the screen, like a car- navigation app. The sun / moon button switches the map between light and dark.+ navigation app. The sun / moon button switches the map between light and dark, the gear+ opens the map settings. **Settings → Map** sets the **default zoom** (17 is close to Waze;+ the 3D view pulls back from it as you speed up), the **3D view angle** (30° to 60°) and the+ **map provider**: OpenFreeMap (free, no account) or Mapbox. The floating mini map always+ uses OpenFreeMap.- **Cell towers** (Settings → *Map* → *Show cell towers*): towers seen while scanning,at the spot where your phone heard them strongest - an estimate, not thetower's real position (looking that up online would reveal where you are).@@ -421,7 +426,8 @@ Plug a supported USB WiFi adapter into the phone with an OTG cable whilescanning and allow USB access on the prompt. RF Sentinel drives it directlyover Android's USB host API (no root, no kernel driver), puts it in**receive-only monitor mode** and hops the channels (2.4 GHz on 88xxau, RTL8187,-RT3070 and AR9271; 2.4 GHz and 5 GHz on 88x2bu, 8814au and MT7612U). Access points+RT3070 and AR9271; 2.4 GHz and 5 GHz on 88x2bu, 8814au and MT7612U; 2.4, 5 and 6 GHz on the+MT7921AU, 6 GHz on its 15 preferred scanning channels, where access points beacon). Access points(beacons, probe responses) and client devices (probe requests, data frames)go through RF Sentinel's own rules like everything else, with a purple**USB WIFI** badge.@@ -432,6 +438,7 @@ go through RF Sentinel's own rules like everything else, with a purple| Realtek RTL8812BU / RTL8822BU (`0bda:b812`, `0bda:b82c` and ~35 other IDs) | TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, Wise Tiger AC1200 | Supported (2.4 + 5 GHz), tested on a Wise Tiger 8812BU || Realtek RTL8814AU (`0bda:8813` and 13 other IDs) | ALFA AWUS1900, TP-Link Archer T9UH, ASUS USB-AC68, Netgear A7000 | Supported (2.4 + 5 GHz), not yet tested on hardware || MediaTek MT7612U / MT7632U (`0e8d:7612` and 16 other IDs) | ALFA AWUS036ACM, ASUS USB-AC55, Netgear A6210 | Supported (2.4 + 5 GHz), not yet tested on hardware |+| MediaTek MT7921AU (`0e8d:7961` and 4 other IDs) | ALFA AWUS036AXML, Comfast CF-952AX, Netgear A8000 / A7500, TP-Link TXE50UH | Experimental (2.4 + 5 + 6 GHz), not yet tested on hardware || Realtek RTL8187L / RTL8187B (`0bda:8187` and 20 other IDs) | ALFA AWUS036H, Netgear WG111v2/v3 | Supported (2.4 GHz), tested on an ALFA AWUS036H || Ralink RT3070 (`148f:3070` and 4 other IDs) | ALFA AWUS036NH / AWUS036NEH | Supported (2.4 GHz), tested on an ALFA AWUS036NEH || Atheros AR9271 (`0cf3:9271` and 17 other IDs) | ALFA AWUS036NHA, TP-Link TL-WN722N v1 | Experimental (2.4 GHz) |@@ -547,15 +554,18 @@ Pick a theme in the setup wizard or under **Settings → Appearance**.- **Receive-only.** Nothing is transmitted, jammed, spoofed or connected to.- **No accounts, no cloud, no analytics.** Detections live in a local databaseexcluded from cloud backup.-- **Network use is limited to OpenStreetMap data:** map tiles while the map is- open, and the known-camera list for the area you look at, fetched once per+- **Network use is limited to map data:** the map (vector tiles, styles and fonts from+ OpenFreeMap, OpenStreetMap data; or from Mapbox if you choose it in Settings → Map,+ with Mapbox's own usage statistics switched off) while the map is open, the road tiles+ of your area and direction while *Only alert for reports ahead* is on (OpenFreeMap,+ kept on the phone), and the known-camera list for the area you look at, fetched once perarea and refreshed weekly from overpass-api.de (or the mirrorsoverpass.kumi.systems and overpass.private.coffee). Camera downloads alsofetch DeFlock's region files from cdn.deflock.me. These servers see your IPaddress and the area, never your scans. Turn off *Show known camerasautomatically* to fetch only when you tap a download. In Android Auto,navigation uses Nominatim and OSRM only when you search or start a route.- Map data © OpenStreetMap contributors (ODbL).+ Map data © OpenStreetMap contributors (ODbL), © OpenMapTiles, © Mapbox when chosen.- **Two optional online sources, off by default:** *Police / governmentaircraft* sends a position rounded to about 1 km to the community ADS-Bfeeds adsb.fi / adsb.lol every minute while scanning. *Waze reports* use@@ -673,6 +683,11 @@ Requirements: Android Studio, or JDK 17+ with the Android SDK (platform 37)../gradlew testDebugUnitTest lintDebug```+Mapbox is optional: with `MAPBOX_ACCESS_TOKEN=pk...` (your own public token) in+`local.properties` (git-ignored) the build offers the Mapbox map; without it the app+builds and runs on OpenFreeMap only. The Mapbox SDK downloads from Mapbox's public+Maven repository without an account.+The debug APK is written to `app/build/outputs/apk/debug/`. `tools/gen_assets.py`regenerates the offline IEEE and Bluetooth SIG databases. The website is builtfrom `site/` with `python tools/build_site.py` (see [site/README.md](site/README.md)).@@ -763,8 +778,11 @@ driver; every transmit path was left out. The RTL8814AU, MT7612U, RT3070 andAR9271 drivers and the FREE-WiLi 2 reader are ported from Wardrive Go too(checked against and fixed from the Linux rt2800usb, mt76x2u and ath9k_htcdrivers), and the RTL8187 driver from the Linux rtl8187 driver with Kismet's-Android PCAP Capture as the USB reference. Their firmware (Ralink rt2870.bin,-MediaTek mt7662, open ath9k_htc) is the unmodified linux-firmware images, with+Android PCAP Capture as the USB reference. The MT7921AU (WiFi 6E) driver is ported from+[mt76-usb-macos](https://github.com/Network-Weather/mt76-usb-macos) by Network Weather+(BSD-3-Clause-Clear), a transcription of the MT7921 path of the Linux mt76 driver+(openwrt/mt76, MediaTek and the mt76 authors, BSD-3-Clause-Clear); its transmit path was left out. Their firmware (Ralink rt2870.bin,+MediaTek mt7662 and MT7961, open ath9k_htc) is the unmodified linux-firmware images, withtheir licences in `assets/usbwifi/`; see `usb/NOTICE.md`. The map's anchored point layer followsWardrive Go's approach - thank you.@@ -779,7 +797,10 @@ was re-checked against its IEEE registrant; see[docs/SIGNATURES.md](docs/SIGNATURES.md#community-lists-compared-2026-10). Knownplate-reader locations come from [DeFlock](https://github.com/FoggedLens/deflock)'ssnapshot of OpenStreetMap, mapped by its volunteers (data © OpenStreetMap-contributors, ODbL) - thank you. The DedSec and fsociety theme font is Share Tech+contributors, ODbL) - thank you. The map is drawn by [MapLibre Native](https://github.com/maplibre/maplibre-native)+(BSD-2-Clause) on [OpenFreeMap](https://openfreemap.org)'s vector tiles (OpenStreetMap data and [OpenMapTiles](https://openmaptiles.org),+ODbL / CC-BY 4.0), with the optional [Mapbox Maps SDK](https://docs.mapbox.com/android/maps/) under Mapbox's terms. The+DedSec and fsociety theme font is Share TechMono (SIL Open Font License 1.1). The DedSec theme is an unofficial fan homage toWatch Dogs; its header poster uses DedSec imagery. Watch Dogs, DedSec, ctOS and Blumeare trademarks of Ubisoft. The fsociety theme is an unofficial fan homage to Mr. Robotdiff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 7ab051d..d24b98d 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -7,8 +7,8 @@ plugins {}// Bump both for every release. versionName ends up in the APK file name.-val appVersionCode = 42-val appVersionName = "2.18.0"+val appVersionCode = 43+val appVersionName = "2.19.0"// Release signing credentials live in keystore.properties (git-ignored).// Without that file, release builds are produced unsigned.@@ -17,6 +17,14 @@ val keystoreProps = Properties().apply {if (f.exists()) f.inputStream().use { load(it) }}+// Mapbox public token (Settings > Map > Map provider) from local.properties (git-ignored), never the repo.+// Without it the Mapbox choice is unavailable and the map stays on OpenFreeMap.+val mapboxToken: String = Properties().run {+ val f = rootProject.file("local.properties")+ if (f.exists()) f.inputStream().use { load(it) }+ getProperty("MAPBOX_ACCESS_TOKEN", "").trim()+}+// APKs come out as RFSentinel-v<versionName>-<buildType>.apkbase.archivesName.set("RFSentinel-v$appVersionName")@@ -32,6 +40,7 @@ android {versionName = appVersionNametestInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"+ buildConfigField("String", "MAPBOX_TOKEN", "\"$mapboxToken\"")}signingConfigs {@@ -52,6 +61,9 @@ android {}release {signingConfig = signingConfigs.findByName("release")+ // The map engines' native libraries are ~15 MB per CPU type: 64-bit ARM phones only (every+ // phone of the last several years), not 32-bit ARM or the x86 emulator builds, which debug builds keep.+ ndk { abiFilters += listOf("arm64-v8a") }isMinifyEnabled = falseproguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"),@@ -60,6 +72,9 @@ android {}}+ // Native libraries stored compressed: a much smaller APK to download (unpacked once at install).+ packaging { jniLibs { useLegacyPackaging = true } }+compileOptions {sourceCompatibility = JavaVersion.VERSION_17targetCompatibility = JavaVersion.VERSION_17@@ -104,6 +119,10 @@ dependencies {// OpenStreetMap map view (Apache-2.0, no API key). Tiles are the only network use.implementation("org.osmdroid:osmdroid-android:6.1.20")+ // Preview of the new map engine (3D driving view): vector maps with a real 3D camera.+ implementation("org.maplibre.gl:android-sdk:13.6.1")+ // Optional Mapbox map (Settings > Map > Map provider); needs MAPBOX_ACCESS_TOKEN in local.properties.+ implementation("com.mapbox.maps:android-ndk27:11.32.0")// Android Auto (Car App Library, template-based UI; "projected" = phone-driven Android Auto)implementation("androidx.car.app:app:1.7.0")diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 5a52ebf..2bb6611 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -31,7 +31,7 @@<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />- <!-- Only used by the map screen to download OpenStreetMap tiles. Scanning,+ <!-- Only used for map data (the map's tiles, the roads for the Waze "ahead" check, camera lists). Scanning,detections and history never leave the phone. --><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />@@ -74,6 +74,7 @@<activity android:name=".ouilist.OuiListActivity" android:exported="false" /><activity android:name=".probes.ProbeListActivity" android:exported="false" /><activity android:name=".ui.DetectionLogActivity" android:exported="false" />+ <activity android:name=".ui.DeviceHistoryActivity" android:exported="false" /><activity android:name=".ui.CellTowersActivity" android:exported="false" /><activity android:name=".ui.GnssActivity" android:exported="false" /><activity android:name=".ui.WazeStatusActivity" android:exported="false" />diff --git a/app/src/main/assets/usbwifi/LICENCE.mediatek b/app/src/main/assets/usbwifi/LICENCE.mediateknew file mode 100644index 0000000..6886c61--- /dev/null+++ b/app/src/main/assets/usbwifi/LICENCE.mediatek@@ -0,0 +1,9 @@+MediaTek Inc. grants permission to use and redistribute aforementioned firmware+files for the use with devices containing MediaTek chipsets, but not as part of+the Linux kernel or in any other form which would require these files themselves+to be covered by the terms of the GNU General Public License or the GNU Lesser+General Public License.++These firmware files are distributed in the hope that they will be useful, but+are provided WITHOUT ANY WARRANTY, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTY+OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.diff --git a/app/src/main/assets/usbwifi/LICENCE.mt76-usb-macos b/app/src/main/assets/usbwifi/LICENCE.mt76-usb-macosnew file mode 100644index 0000000..c452917--- /dev/null+++ b/app/src/main/assets/usbwifi/LICENCE.mt76-usb-macos@@ -0,0 +1,37 @@+The Clear BSD License++Copyright (c) 2026 Primatech Paper Co LLC d/b/a Network Weather+Portions Copyright (C) 2023 MediaTek Inc.+Portions Copyright (C) 2022 MediaTek Inc.+Portions Copyright (C) 2020 MediaTek Inc.+Portions Copyright (C) 2018 Lorenzo Bianconi <[email protected]>+Portions Copyright (C) 2016 Felix Fietkau <[email protected]>+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted (subject to the limitations in the disclaimer+below) provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.++ * Neither the name of any copyright holder nor the names of its contributors+ may be used to endorse or promote products derived from this software without+ specific prior written permission.++NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY+THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND+CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER+IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+POSSIBILITY OF SUCH DAMAGE.diff --git a/app/src/main/assets/usbwifi/WIFI_MT7961_patch_mcu_1_2_hdr.bin b/app/src/main/assets/usbwifi/WIFI_MT7961_patch_mcu_1_2_hdr.binnew file mode 100644index 0000000..b065872Binary files /dev/null and b/app/src/main/assets/usbwifi/WIFI_MT7961_patch_mcu_1_2_hdr.bin differdiff --git a/app/src/main/assets/usbwifi/WIFI_RAM_CODE_MT7961_1.bin b/app/src/main/assets/usbwifi/WIFI_RAM_CODE_MT7961_1.binnew file mode 100644index 0000000..9639b48Binary files /dev/null and b/app/src/main/assets/usbwifi/WIFI_RAM_CODE_MT7961_1.bin differdiff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex b959b7b..35cabaa 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -775,6 +775,7 @@ class MainActivity : AppCompatActivity() {return when (item.itemId) {R.id.action_waze_now -> { com.rfsentinel.app.ui.WazeUi.checkNow(this); true }R.id.action_waze_status -> { com.rfsentinel.app.ui.WazeUi.openStatus(this); true }+ R.id.action_device_history -> { startActivity(Intent(this, com.rfsentinel.app.ui.DeviceHistoryActivity::class.java)); true }R.id.action_match_log -> { startActivity(Intent(this, DetectionLogActivity::class.java)); true }R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)); true }R.id.action_probes -> { startActivity(Intent(this, com.rfsentinel.app.probes.ProbeListActivity::class.java)); true }diff --git a/app/src/main/java/com/rfsentinel/app/data/DetectionDao.kt b/app/src/main/java/com/rfsentinel/app/data/DetectionDao.ktindex 83900e8..a29a648 100644--- a/app/src/main/java/com/rfsentinel/app/data/DetectionDao.kt+++ b/app/src/main/java/com/rfsentinel/app/data/DetectionDao.kt@@ -20,6 +20,10 @@ interface DetectionDao {@Query("SELECT * FROM detections ORDER BY timestamp DESC")suspend fun allForExport(): List<DetectionEntity>+ /** Exports, in batches: the [limit] newest rows logged before row [beforeId] (stable while new ones arrive). */+ @Query("SELECT * FROM detections WHERE id < :beforeId ORDER BY id DESC LIMIT :limit")+ suspend fun pageBefore(beforeId: Long, limit: Int): List<DetectionEntity>+@Query("SELECT * FROM detections WHERE timestamp >= :since ORDER BY timestamp DESC")suspend fun since(since: Long): List<DetectionEntity>diff --git a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.ktindex 479eab8..8208fd9 100644--- a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt+++ b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt@@ -37,6 +37,10 @@ interface KnownDeviceDao {@Query("SELECT * FROM known_devices ORDER BY lastSeen DESC")suspend fun all(): List<KnownDeviceEntity>+ /** Exports, in batches: the order first, then the rows a batch at a time ([getAll]). */+ @Query("SELECT mac FROM known_devices ORDER BY lastSeen DESC")+ suspend fun macsByLastSeen(): List<String>+@Query("SELECT * FROM known_devices WHERE mac IN (:macs)")suspend fun getAll(macs: List<String>): List<KnownDeviceEntity>@@ -52,6 +56,28 @@ interface KnownDeviceDao {@Query("SELECT COUNT(*) FROM known_devices")suspend fun count(): Int+ /**+ * Device history search ([com.rfsentinel.app.ui.DeviceHistoryActivity]), newest first: [query] in the+ * MAC (with or without colons), name, vendor, type or note; only favorites, only devices that were+ * flagged (in the match log), only those seen since [since].+ */+ @Query("""SELECT * FROM known_devices+ WHERE (:query = '' OR mac LIKE :like ESCAPE '\' OR REPLACE(mac, ':', '') LIKE :likeHex ESCAPE '\'+ OR name LIKE :like ESCAPE '\' OR vendor LIKE :like ESCAPE '\'+ OR deviceType LIKE :like ESCAPE '\' OR note LIKE :like ESCAPE '\')+ AND (:favorites = 0 OR favorite = 1)+ AND (:flagged = 0 OR mac IN (SELECT mac FROM detections))+ AND lastSeen >= :since+ ORDER BY lastSeen DESC LIMIT :limit""")+ suspend fun search(query: String, like: String, likeHex: String, favorites: Boolean, flagged: Boolean, since: Long, limit: Int): List<KnownDeviceEntity>++ companion object {+ /** "%text%" for LIKE, with LIKE's own characters taken literally. */+ fun like(text: String) = "%" + text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"+ /** A MAC typed without colons (or with dashes) still finds it. */+ fun likeHex(text: String) = like(text.replace(":", "").replace("-", ""))+ }+/** Forget non-favorite devices not heard since [before]. */@Query("DELETE FROM known_devices WHERE lastSeen < :before AND favorite = 0")suspend fun prune(before: Long): Intdiff --git a/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt b/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.ktnew file mode 100644index 0000000..2df7f03--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt@@ -0,0 +1,74 @@+package com.rfsentinel.app.online++import android.content.Context+import android.location.Location++/**+ * "Only alert for reports ahead of me", on the map's roads: the road you're on, followed forward+ * from where you are ([RoadMatch]), with each report checked against it. Your road ahead is worked+ * out again when you've moved or turned, not every second; stopped (at a light), your last heading+ * still counts for a couple of minutes.+ */+internal class AheadOnRoad {++ private var path: RoadMatch.Path? = null+ private var pathLat = 0.0; private var pathLon = 0.0; private var pathHeading = 0.0; private var pathAt = 0L+ private var heading: Double? = null; private var headingAt = 0L+ private var headingLat = 0.0; private var headingLon = 0.0++ /** 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 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 p = path ?: return emptyMap()+ return reports.associate { it.id to RoadMatch.check(p, it.lat, it.lon).first }+ }++ /** Your heading while driving; stopped, the last one for 2 minutes (as long as you haven't moved off). */+ private fun headingOf(me: Location): Double? {+ val now = System.currentTimeMillis()+ if (me.hasBearing() && me.hasSpeed() && me.speed > 1.5f) {+ heading = me.bearing.toDouble(); headingAt = now; headingLat = me.latitude; headingLon = me.longitude+ return heading+ }+ val h = heading ?: return null+ val near = com.rfsentinel.app.service.DeviceRegistry.metersBetween(headingLat, headingLon, me.latitude, me.longitude) < 60+ return h.takeIf { now - headingAt < 120_000 && near }+ }++ /** 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? {+ 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 }+ // 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()+ RoadTiles.roads(context, listOf(RoadTiles.tileOf(la, lo)))+ }+ return path+ }++ companion object {+ /** 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>()+ var d = 0.0+ while (d <= maxM) {+ for (side in listOf(0.0, -300.0, 300.0)) {+ val (a, b) = com.rfsentinel.app.ui.MapGeo.offset(lat, lon, d, headingDeg)+ val (c, e) = if (side == 0.0) a to b else com.rfsentinel.app.ui.MapGeo.offset(a, b, kotlin.math.abs(side), headingDeg + if (side > 0) 90 else -90)+ out += RoadTiles.tileOf(c, e)+ }+ d += 250.0+ }+ return out+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.ktindex 5ff52d5..4a9b1e5 100644--- a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt+++ b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt@@ -181,6 +181,10 @@ object PoliceAircraft {@Volatile var latest: List<Seen> = emptyList()@Volatile var latestAt = 0L+ /** Aircraft [hex] (ICAO address) in the latest poll while it's fresh (as the map draws it), or null. */+ fun current(hex: String, now: Long = System.currentTimeMillis()): Seen? =+ if (now - latestAt > 3 * 60_000L) null else latest.firstOrNull { it.plane.hex.equals(hex, ignoreCase = true) }+fun feedUrls(lat: Double, lon: Double, radiusKm: Int): List<String> {val nm = Math.round(radiusKm / 1.852).toInt().coerceIn(1, 250)// Rounded to ~1 km: the feeds don't need your exact position.diff --git a/app/src/main/java/com/rfsentinel/app/online/RoadMatch.kt b/app/src/main/java/com/rfsentinel/app/online/RoadMatch.ktnew file mode 100644index 0000000..17e0bdb--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/RoadMatch.kt@@ -0,0 +1,227 @@+package com.rfsentinel.app.online++import kotlin.math.abs+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.hypot++/**+ * Is a report on the road you're on, ahead of you? Finds your road from your position and heading+ * (the nearest road segment that runs your way), follows it forward - through intersections, taking+ * the straightest way on when the line ends, as you would keep driving - out to [RoadMatch.Path.maxM],+ * then checks each report against that stretch. A report on a parallel road, a cross street or an+ * overpass, or behind you, isn't on it. Plain geometry on [RoadTiles.Road] lines (tested without a map).+ */+object RoadMatch {++ enum class Verdict { ON_MY_ROAD, OTHER_ROAD, BEHIND, UNKNOWN }++ /** Your road ahead, as points in metres around you, with the distance along it at each point. */+ class Path internal constructor(+ internal val xs: DoubleArray, internal val ys: DoubleArray, internal val along: DoubleArray,+ /** Road segments the path runs on (road index, segment index). */+ internal val used: Set<Long>,+ /** The road each stretch (point i to i + 1) runs on. */+ internal val roadOf: IntArray,+ /** It stopped where no map data was loaded yet (rather than at a dead end or [maxM]). */+ val stoppedForData: Boolean,+ internal val frame: Frame,+ internal val roads: Index,+ internal val headingDeg: Double+ ) {+ val lengthM get() = along.lastOrNull() ?: 0.0+ /** Where it ended, for loading the map there. */+ 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+ /** 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. */+ private const val HEADING_TOLERANCE = 40.0+ /** At the end of a line, the way on must turn less than this ("straight on"). */+ private const val CONTINUE_TOLERANCE = 50.0+ /** Lines meet (a junction, or the same road cut at a tile edge) within this. */+ private const val JOIN_M = 10.0++ /**+ * 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).+ */+ fun pathAhead(roads: List<RoadTiles.Road>, lat: Double, lon: Double, headingDeg: Double, maxM: Double,+ 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 ->+ // 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)+ val ow = roads[c.road].oneway+ val dirs = listOfNotNull(+ (1 to fwd).takeIf { fwd <= HEADING_TOLERANCE && ow != -1 },+ (-1 to back).takeIf { back <= HEADING_TOLERANCE && ow != 1 })+ dirs.minByOrNull { it.second }?.let { (sign, diff) -> Triple(c, sign, c.dist + diff * 0.4) }+ }.minByOrNull { it.third } ?: return null++ val xs = ArrayList<Double>(); val ys = ArrayList<Double>(); val along = ArrayList<Double>()+ val used = HashSet<Long>()+ val roadOf = ArrayList<Int>()+ var total = 0.0+ var road = start.first.road; var seg = start.first.seg; var sign = start.second+ fun add(x: Double, y: Double) {+ if (xs.isNotEmpty()) { total += hypot(x - xs.last(), y - ys.last()); roadOf += road }+ xs += x; ys += y; along += total+ }+ add(start.first.px, start.first.py)+ var stoppedForData = false+ var guard = 0+ walk@ while (total < maxM && guard++ < 5000) {+ // Along this line to its end (in the direction of travel).+ val pts = idx.pts(road)+ var i = if (sign > 0) seg + 1 else seg+ while (i in pts.indices) {+ used += key(road, if (sign > 0) i - 1 else i)+ add(pts[i].first, pts[i].second)+ if (total >= maxM) break@walk+ i += sign+ }+ // The line ends: carry on along the straightest way that starts here.+ val endX = xs.last(); val endY = ys.last()+ val inDir = dirOf(xs[xs.size - 2], ys[ys.size - 2], endX, endY)+ val next = idx.nearest(endX, endY, JOIN_M).filter { key(it.road, it.seg) !in used && it.road != road }.mapNotNull { c ->+ val d = idx.dirDeg(c.road, c.seg)+ val ow = roads[c.road].oneway+ val opts = listOfNotNull(+ (1 to angleDiff(d, inDir)).takeIf { ow != -1 },+ (-1 to angleDiff(d + 180, inDir)).takeIf { ow != 1 })+ opts.minByOrNull { it.second }?.takeIf { it.second <= CONTINUE_TOLERANCE }?.let { (s, diff) ->+ // The same kind of road is the likelier way on.+ Triple(c, s, diff + (if (roads[c.road].cls == roads[road].cls) 0.0 else 15.0) + c.dist)+ }+ }.minByOrNull { it.third }+ if (next == null) {+ val (la, lo) = f.toLatLon(endX, endY)+ stoppedForData = !loaded(la, lo)+ break+ }+ road = next.first.road; seg = next.first.seg; sign = next.second+ if (hypot(next.first.px - endX, next.first.py - endY) > 0.5) add(next.first.px, next.first.py)+ }+ if (xs.size < 2) return null+ return Path(xs.toDoubleArray(), ys.toDoubleArray(), along.toDoubleArray(), used, roadOf.toIntArray(), stoppedForData, f, idx, headingDeg)+ }++ /** Whether the report at ([lat], [lon]) is on [path] - your road ahead - and how far along it. */+ fun check(path: Path?, lat: Double, lon: Double): Pair<Verdict, Double?> {+ if (path == null) return Verdict.UNKNOWN to null+ val (x, y) = path.frame.toXY(lat, lon)+ // Nearest point of your road ahead.+ var best = Double.MAX_VALUE; var bestAlong = 0.0; var bestDir = 0.0; var bestRoad = -1+ for (i in 0 until path.xs.size - 1) {+ val (d, t) = pointToSegment(x, y, path.xs[i], path.ys[i], path.xs[i + 1], path.ys[i + 1])+ if (d < best) {+ best = d+ bestAlong = path.along[i] + t * (path.along[i + 1] - path.along[i])+ bestDir = dirOf(path.xs[i], path.ys[i], path.xs[i + 1], path.ys[i + 1])+ bestRoad = path.roadOf[i]+ }+ }+ val ahead = angleDiff(dirOf(0.0, 0.0, x, y), path.headingDeg) <= 90+ // Right where you are and the wrong way: just behind you.+ if (bestAlong < 20.0 && best <= REPORT_MAX_M && hypot(x, y) > 10 && !ahead) return Verdict.BEHIND to null++ // The road the report itself is on, when it isn't yours.+ val other = path.roads.nearest(x, y, REPORT_MAX_M).filter { key(it.road, it.seg) !in path.used }.minByOrNull { it.dist }+ if (other != null && bestRoad >= 0) {+ val axis = angleDiff(path.roads.dirDeg(other.road, other.seg), bestDir) // 0 = same way, 180 = the other way+ val parallel = minOf(axis, 180 - axis) <= 30+ val mine = path.roads.road(bestRoad); val theirs = path.roads.road(other.road)+ // A divided highway: the other carriageway (a one-way road beside yours, the other way) is the same road.+ if (parallel && axis > 150 && theirs.oneway != 0 && mine.oneway != 0 && theirs.cls == mine.cls &&+ other.dist <= 15 && best <= 2 * REPORT_MAX_M) return Verdict.ON_MY_ROAD to bestAlong+ // Clearly on another road: one that crosses yours (a cross street, an overpass), or runs beside it (a service road).+ if (!parallel && other.dist + 6 < best) return Verdict.OTHER_ROAD to null+ if (parallel && other.dist + 10 < best) return Verdict.OTHER_ROAD to null+ }+ if (best > REPORT_MAX_M) {+ // Off the stretch that's loaded: it may still be on your road further on.+ if (path.stoppedForData && hypot(x - path.xs.last(), y - path.ys.last()) < hypot(x, y)) return Verdict.UNKNOWN to null+ return (if (ahead) Verdict.OTHER_ROAD else Verdict.BEHIND) to null+ }+ return Verdict.ON_MY_ROAD to bestAlong+ }++ // ---- geometry ----------------------------------------------------------------------------------++ private fun key(road: Int, seg: Int) = (road.toLong() shl 20) or seg.toLong()++ /** Bearing (degrees clockwise from north) from one point to another, in the local metre frame. */+ private fun dirOf(x0: Double, y0: Double, x1: Double, y1: Double) = (Math.toDegrees(atan2(x1 - x0, y1 - y0)) + 360) % 360++ /** 0..180 between two bearings. */+ internal fun angleDiff(a: Double, b: Double): Double { val d = abs(((a - b) % 360 + 540) % 360 - 180); return d }++ /** Distance from a point to a segment, and where along it (0..1) the nearest point is. */+ private fun pointToSegment(px: Double, py: Double, x0: Double, y0: Double, x1: Double, y1: Double): Pair<Double, Double> {+ val dx = x1 - x0; val dy = y1 - y0+ val l2 = dx * dx + dy * dy+ val t = if (l2 == 0.0) 0.0 else (((px - x0) * dx + (py - y0) * dy) / l2).coerceIn(0.0, 1.0)+ return hypot(px - (x0 + t * dx), py - (y0 + t * dy)) to t+ }++ /** Metres east / north of a point (fine for the few kilometres involved). */+ internal class Frame(private val lat0: Double, private val lon0: Double) {+ private val kx = 111_320.0 * cos(Math.toRadians(lat0))+ private val ky = 110_540.0+ fun toXY(lat: Double, lon: Double) = (lon - lon0) * kx to (lat - lat0) * ky+ fun toLatLon(x: Double, y: Double) = (lat0 + y / ky) to (lon0 + x / kx)+ }++ /** A segment near a point: which, how far, and the nearest point on it. */+ internal class Near(val road: Int, val seg: Int, val dist: Double, val px: Double, val py: Double)++ /** Road segments in metres, on a 100 m grid for finding what's near a point. */+ internal class Index(private val source: List<RoadTiles.Road>, f: Frame) {+ private val points: List<List<Pair<Double, Double>>> = source.map { r -> r.lat.indices.map { f.toXY(r.lat[it], r.lon[it]) } }+ private val grid = HashMap<Long, MutableList<Long>>()+ private val cell = 100.0++ init {+ for ((ri, pts) in points.withIndex()) for (si in 0 until pts.size - 1) {+ val (x0, y0) = pts[si]; val (x1, y1) = pts[si + 1]+ for (cx in cellOf(minOf(x0, x1))..cellOf(maxOf(x0, x1)))+ for (cy in cellOf(minOf(y0, y1))..cellOf(maxOf(y0, y1)))+ grid.getOrPut(cellKey(cx, cy)) { ArrayList() } += key(ri, si)+ }+ }++ private fun cellOf(v: Double) = Math.floor(v / cell).toInt()+ private fun cellKey(cx: Int, cy: Int) = (cx.toLong() shl 32) or (cy.toLong() and 0xffffffffL)++ fun pts(road: Int) = points[road]+ fun road(i: Int) = source[i]++ fun dirDeg(road: Int, seg: Int): Double {+ val (x0, y0) = points[road][seg]; val (x1, y1) = points[road][seg + 1]+ return dirOf(x0, y0, x1, y1)+ }++ fun nearest(x: Double, y: Double, maxM: Double): List<Near> {+ val out = ArrayList<Near>()+ val seen = HashSet<Long>()+ for (cx in cellOf(x - maxM)..cellOf(x + maxM)) for (cy in cellOf(y - maxM)..cellOf(y + maxM)) {+ for (k in grid[cellKey(cx, cy)] ?: continue) {+ if (!seen.add(k)) continue+ val ri = (k ushr 20).toInt(); val si = (k and 0xfffff).toInt()+ val (x0, y0) = points[ri][si]; val (x1, y1) = points[ri][si + 1]+ val (d, t) = pointToSegment(x, y, x0, y0, x1, y1)+ if (d <= maxM) out += Near(ri, si, d, x0 + t * (x1 - x0), y0 + t * (y1 - y0))+ }+ }+ return out+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt b/app/src/main/java/com/rfsentinel/app/online/RoadTiles.ktnew file mode 100644index 0000000..c4d8fee--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt@@ -0,0 +1,229 @@+package com.rfsentinel.app.online++import android.content.Context+import java.io.File+import java.net.HttpURLConnection+import java.net.URL+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.Executors++/**+ * The roads around you, from the same OpenFreeMap vector tiles the map draws (OpenStreetMap data,+ * OpenMapTiles schema, zoom 14): each road's line, class (motorway ... service), one-way flag and+ * whether it's a bridge or tunnel. Used to tell whether a Waze report is on the road you're on+ * ([RoadMatch]). Tiles are fetched in the background as you go and kept on the phone (they don't+ * change until OpenFreeMap publishes a new map); fetching them reveals the area, like the map does.+ */+object RoadTiles {++ const val Z = 14+ private const val TILEJSON = "https://tiles.openfreemap.org/planet"+ private const val MEMORY_TILES = 24+ private const val DISK_TILES = 400++ /** One road line: points as latitude / longitude, OpenMapTiles attributes. */+ class Road(val lat: DoubleArray, val lon: DoubleArray, val cls: String, val oneway: Int, val brunnel: String?, val layer: Int)++ /** Classes a car drives on (not paths, rail, ferries...). */+ private val DRIVABLE = setOf("motorway", "trunk", "primary", "secondary", "tertiary", "minor", "service", "track", "busway", "raceway")++ data class Tile(val x: Int, val y: Int)++ fun tileOf(lat: Double, lon: Double): Tile {+ val n = 1 shl Z+ val x = ((lon + 180.0) / 360.0 * n).toInt().coerceIn(0, n - 1)+ val r = Math.toRadians(lat.coerceIn(-85.0, 85.0))+ val y = ((1.0 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2.0 * n).toInt().coerceIn(0, n - 1)+ return Tile(x, y)+ }++ /** A point of tile [t], in its own units (0..[extent] across), as latitude / longitude. */+ internal fun toLatLon(t: Tile, px: Double, py: Double, extent: Int): Pair<Double, Double> {+ val n = (1 shl Z).toDouble()+ val lon = (t.x + px / extent) / n * 360.0 - 180.0+ val lat = Math.toDegrees(Math.atan(Math.sinh(Math.PI * (1 - 2 * (t.y + py / extent) / n))))+ return lat to lon+ }++ // ---- the vector tile format (Mapbox Vector Tile 2: protocol buffers) -------------------------++ /** The drivable roads of one tile; malformed data gives what was read before it. */+ internal fun decode(bytes: ByteArray, t: Tile): List<Road> {+ val out = ArrayList<Road>()+ runCatching {+ val r = Pb(bytes, 0, bytes.size)+ while (r.more()) {+ val (f, w) = r.key()+ if (f == 3 && w == 2) { val (s, e) = r.bytes(); layer(bytes, s, e, t, out) } else r.skip(w)+ }+ }+ return out+ }++ private fun layer(b: ByteArray, start: Int, end: Int, t: Tile, out: MutableList<Road>) {+ // First pass: the name, keys, values and extent; features come back in a second pass.+ var name = ""; val keys = ArrayList<String>(); val values = ArrayList<Any?>(); var extent = 4096+ val features = ArrayList<IntArray>()+ val r = Pb(b, start, end)+ while (r.more()) {+ val (f, w) = r.key()+ when {+ f == 1 && w == 2 -> { val (s, e) = r.bytes(); name = String(b, s, e - s, Charsets.UTF_8); if (name != "transportation") return }+ f == 2 && w == 2 -> { val (s, e) = r.bytes(); features += intArrayOf(s, e) }+ f == 3 && w == 2 -> { val (s, e) = r.bytes(); keys += String(b, s, e - s, Charsets.UTF_8) }+ f == 4 && w == 2 -> { val (s, e) = r.bytes(); values += value(b, s, e) }+ f == 5 && w == 0 -> extent = r.varint().toInt()+ else -> r.skip(w)+ }+ }+ if (name != "transportation") return+ for ((s, e) in features.map { it[0] to it[1] }) feature(b, s, e, keys, values, extent, t, out)+ }++ private fun value(b: ByteArray, start: Int, end: Int): Any? {+ val r = Pb(b, start, end)+ while (r.more()) {+ val (f, w) = r.key()+ when (f) {+ 1 -> { val (s, e) = r.bytes(); return String(b, s, e - s, Charsets.UTF_8) }+ 4, 5 -> return r.varint()+ 6 -> return Pb.zigzag(r.varint())+ 7 -> return r.varint() != 0L+ else -> r.skip(w)+ }+ }+ return null+ }++ private fun feature(b: ByteArray, start: Int, end: Int, keys: List<String>, values: List<Any?>, extent: Int, t: Tile, out: MutableList<Road>) {+ var tags = IntArray(0); var type = 0; var geom = LongArray(0)+ val r = Pb(b, start, end)+ while (r.more()) {+ val (f, w) = r.key()+ when {+ f == 2 && w == 2 -> tags = r.packed().map { it.toInt() }.toIntArray()+ f == 3 && w == 0 -> type = r.varint().toInt()+ f == 4 && w == 2 -> geom = r.packed()+ else -> r.skip(w)+ }+ }+ if (type != 2) return // lines only+ val attrs = HashMap<String, Any?>()+ for (i in 0 until tags.size - 1 step 2) keys.getOrNull(tags[i])?.let { attrs[it] = values.getOrNull(tags[i + 1]) }+ val cls = attrs["class"] as? String ?: return+ if (cls !in DRIVABLE) return+ val oneway = (attrs["oneway"] as? Long)?.toInt() ?: 0 // 1 = drawn direction only, -1 = against it+ val brunnel = attrs["brunnel"] as? String+ val layer = (attrs["layer"] as? Long)?.toInt() ?: 0+ // Geometry: MoveTo / LineTo commands with zigzag-encoded relative steps; one road per MoveTo.+ var i = 0; var x = 0L; var y = 0L+ var lat = ArrayList<Double>(); var lon = ArrayList<Double>()+ fun flush() {+ if (lat.size >= 2) out += Road(lat.toDoubleArray(), lon.toDoubleArray(), cls, oneway.coerceIn(-1, 1), brunnel, layer)+ lat = ArrayList(); lon = ArrayList()+ }+ while (i < geom.size) {+ val cmd = (geom[i] and 7).toInt(); val count = (geom[i] ushr 3).toInt(); i+++ if (cmd == 1) flush()+ if (cmd == 1 || cmd == 2) repeat(count) {+ if (i + 1 >= geom.size) return@repeat+ x += Pb.zigzag(geom[i]); y += Pb.zigzag(geom[i + 1]); i += 2+ val (la, lo) = toLatLon(t, x.toDouble(), y.toDouble(), extent)+ lat += la; lon += lo+ }+ }+ flush()+ }++ /** A minimal protocol-buffer reader over a slice of [b]. */+ private class Pb(val b: ByteArray, var pos: Int, val end: Int) {+ fun more() = pos < end+ fun varint(): Long {+ var r = 0L; var s = 0+ while (pos < end) { val x = b[pos++].toInt(); r = r or ((x and 0x7f).toLong() shl s); if (x and 0x80 == 0) return r; s += 7 }+ throw IllegalStateException("truncated varint")+ }+ fun key(): Pair<Int, Int> { val k = varint(); return (k ushr 3).toInt() to (k and 7).toInt() }+ fun bytes(): Pair<Int, Int> { val n = varint().toInt(); val s = pos; pos += n; check(n >= 0 && pos <= end); return s to pos }+ fun packed(): LongArray { val (s, e) = bytes(); val r = Pb(b, s, e); val out = ArrayList<Long>(); while (r.more()) out += r.varint(); return out.toLongArray() }+ fun skip(w: Int) { when (w) { 0 -> varint(); 1 -> pos += 8; 2 -> bytes(); 5 -> pos += 4; else -> throw IllegalStateException("wire type $w") } }+ companion object { fun zigzag(n: Long) = (n ushr 1) xor -(n and 1) }+ }++ // ---- fetching and keeping them ------------------------------------------------------------------++ private val memory = object : LinkedHashMap<Tile, List<Road>>(32, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Tile, List<Road>>) = size > MEMORY_TILES+ }+ private val pending = ConcurrentHashMap.newKeySet<Tile>()+ private val failedAt = ConcurrentHashMap<Tile, Long>()+ private val worker = Executors.newSingleThreadExecutor { Thread(it, "road-tiles").apply { isDaemon = true } }+ @Volatile private var template: String? = null+ @Volatile private var templateAt = 0L++ /** The roads of [tiles] already at hand; the others are fetched in the background (null until then). */+ fun roads(context: Context, tiles: Collection<Tile>): Map<Tile, List<Road>> {+ val have = HashMap<Tile, List<Road>>()+ val missing = ArrayList<Tile>()+ synchronized(memory) { for (t in tiles) memory[t]?.let { have[t] = it } ?: missing.add(t) }+ val now = System.currentTimeMillis()+ for (t in missing) {+ if (now - (failedAt[t] ?: 0L) < 60_000) continue // wait a minute after a failure+ if (pending.add(t)) worker.execute { try { load(context.applicationContext, t) } finally { pending.remove(t) } }+ }+ return have+ }++ /** Tests: tiles as if already fetched. */+ internal fun put(t: Tile, roads: List<Road>) = synchronized(memory) { memory[t] = roads }+ internal fun clear() = synchronized(memory) { memory.clear() }++ private fun load(context: Context, t: Tile) {+ val url = tileUrl(context) ?: run { failedAt[t] = System.currentTimeMillis(); return }+ val version = url.substringAfter("/planet/").substringBefore('/').ifEmpty { "x" }+ val dir = File(context.cacheDir, "road-tiles/$version")+ val file = File(dir, "${Z}_${t.x}_${t.y}.pbf")+ val bytes = runCatching { if (file.exists()) file.readBytes() else null }.getOrNull()+ ?: download(url.replace("{z}", "$Z").replace("{x}", "${t.x}").replace("{y}", "${t.y}"))?.also { b ->+ runCatching { dir.mkdirs(); file.writeBytes(b); trim(context, dir) }+ }+ if (bytes == null) { failedAt[t] = System.currentTimeMillis(); return }+ val roads = decode(bytes, t)+ synchronized(memory) { memory[t] = roads }+ }++ /** The tile address of the current OpenFreeMap map (asked once a day). */+ private fun tileUrl(context: Context): String? {+ val now = System.currentTimeMillis()+ template?.takeIf { now - templateAt < 24 * 3_600_000L }?.let { return it }+ val json = download(TILEJSON)?.toString(Charsets.UTF_8) ?: return template+ val url = runCatching { org.json.JSONObject(json).getJSONArray("tiles").getString(0) }.getOrNull() ?: return template+ template = url; templateAt = now+ // An older map's tiles aren't needed any more.+ runCatching {+ val version = url.substringAfter("/planet/").substringBefore('/')+ File(context.cacheDir, "road-tiles").listFiles()?.filter { it.name != version }?.forEach { it.deleteRecursively() }+ }+ return url+ }++ private fun download(url: String): ByteArray? = runCatching {+ val c = URL(url).openConnection() as HttpURLConnection+ c.connectTimeout = 10_000; c.readTimeout = 15_000+ c.setRequestProperty("User-Agent", "RFSentinel/${com.rfsentinel.app.BuildConfig.VERSION_NAME}")+ try {+ if (c.responseCode != 200) null+ else c.inputStream.use { s ->+ val b = s.readBytes()+ // Served plain; gzip only if a server ever sends it without saying so.+ if (b.size > 2 && b[0] == 0x1f.toByte() && b[1] == 0x8b.toByte()) java.util.zip.GZIPInputStream(b.inputStream()).readBytes() else b+ }+ } finally { c.disconnect() }+ }.getOrNull()++ private fun trim(context: Context, dir: File) {+ val files = dir.listFiles() ?: return+ if (files.size <= DISK_TILES) return+ files.sortedBy { it.lastModified() }.take(files.size - DISK_TILES).forEach { it.delete() }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt b/app/src/main/java/com/rfsentinel/app/online/WazePolice.ktindex c373747..db4f65a 100644--- a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt+++ b/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt@@ -150,6 +150,9 @@ object WazePolice {@Volatile var latestAt = 0Lprivate set+ /** Report [id] while it's still among the current ones, or null (expired, or the checker stopped). */+ fun current(id: String): Shown? = latest.firstOrNull { it.report.id == id }+private val listeners = java.util.concurrent.CopyOnWriteArrayList<() -> Unit>()/**diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.ktindex e26c540..073c5dc 100644--- a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt@@ -60,6 +60,7 @@ class WazeWatch(private var via = WazePolice.VIA_DIRECTprivate var lastOkAt = 0Lprivate var shownIds: Set<String> = emptySet()+ private val road = AheadOnRoad()private var direct = falseprivate var wazeDirect: WazeRtFetcher? = nullprivate var wazeDirectRegion = ""@@ -243,8 +244,16 @@ class WazeWatch(}trend.keepOnly(known.keys)- // In the alert range, and (if asked) not behind you.- fun counts(s: WazePolice.Shown) = s.distanceM <= alertM && !(aheadOnly && s.where.isBehind)+ // 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.+ 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+ }+ // In the alert range, and (if asked) ahead on your road.+ fun counts(s: WazePolice.Shown) = s.distanceM <= alertM && !(aheadOnly && quiet(s))var fired = falsefor (s in shown) {diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex c367f02..4282787 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -1037,21 +1037,21 @@ class ScanForegroundService : Service() {val hit = alert.hitif (!Prefs.categoryEnabled(this, hit.category)) returnval now = System.currentTimeMillis()- val loc = lastLocationval tag = Prefs.gpsTaggingEnabled(this)+ // Logged where it was (the aircraft's own ADS-B position, the Waze report's spot), so its row opens the map there.if (alert.log) serviceScope.launch {AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(DetectionEntity(mac = alert.key.substringBefore(':').uppercase() + " " + alert.key.substringAfter(':'), label = hit.label,source = "ONLINE", rssi = 0, timestamp = now,- latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,+ latitude = if (tag) alert.lat else null, longitude = if (tag) alert.lon else null,category = hit.category.name, confidence = hit.confidence, evidence = hit.evidence))}if (alert.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&hit.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {- NotificationHelper.sendMapAlert(this, alert.key, hit, lat = alert.lat, lon = alert.lon)+ NotificationHelper.sendMapAlert(this, alert.key, hit, lat = alert.lat, lon = alert.lon, online = alert.key)if (alert.level == com.rfsentinel.app.online.WazePolice.Level.LOUD) {AlertPlayer.play(this, hit.tier, alert.spoken ?: com.rfsentinel.app.util.Spoken.shortWord(hit))}@@ -1099,7 +1099,8 @@ class ScanForegroundService : Service() {val now = System.currentTimeMillis()val ssid = DeviceRegistry.get(a.bssid)?.nameval net = ssid?.let { "\"$it\"" } ?: "network ${a.bssid}"- val detail = "${a.frames} deauthentication / disassociation frames in ${a.windowS} s for $net (channel ${a.channel})" ++ val channel = if (a.channel >= 5955) "6 GHz channel ${(a.channel - 5950) / 5}" else "channel ${a.channel}" // 6 GHz comes in MHz+ val detail = "${a.frames} deauthentication / disassociation frames in ${a.windowS} s for $net ($channel)" +(if (a.broadcast) ", sent to every device on it" else "") + ". Something is knocking devices off this WiFi: a jammer " +"or a hacking tool (ESP32 / ESP8266 deauther, Flipper Zero WiFi board, WiFi Pineapple). A normal network sends a " +"handful, never a stream. Heard by the USB WiFi adapter; nothing is sent."diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 93e2939..5ed1f4e 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -28,6 +28,7 @@ class SettingsActivity : AppCompatActivity() {/** Opens Settings on one section (expanded and scrolled to): e.g. [SECTION_MAP] from the map. */const val EXTRA_SECTION = "open_section"const val SECTION_MAP = "map"+ const val SECTION_DATA = "data"const val WAZE_WARNING_SHORT = "Use at your own risk. Reports come from third-party services RF Sentinel doesn't run or endorse " +"(OpenWeb Ninja with your own key, or Waze itself); your account, your responsibility."const val WAZE_WARNING = "Waze police reports are read through OpenWeb Ninja's Waze API with your own API key.\n\n" +@@ -405,7 +406,8 @@ class SettingsActivity : AppCompatActivity() {"• Alert range: how close a report must be to alert. Map range: how far the map shows them.\n" +"• Check every: how often Waze is asked. Slower when parked, faster on fast roads (direct), if you leave that on. " +"OpenWeb Ninja bills every check.\n" +- "• Only alert for reports ahead: while you drive, reports behind you stay on the list but stay quiet.\n" ++ "• Only alert for reports ahead: while you drive, only reports on your road ahead of you alert (checked against " ++ "the map's roads, from OpenFreeMap); the others stay on the list but stay quiet.\n" +"• Call out again: speaks at 1 km, 500 m and 200 m as a report gets closer (voice alerts on, or in the car).\n" +"• Each kind of report has its own level: sound and voice, notification only, or silent (list and map only).\n" +"• Pull the list down, or use the menu, to check right now. Waze status shows what is sent, and when.\n\n" +@@ -454,7 +456,15 @@ class SettingsActivity : AppCompatActivity() {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" +- "Cell towers: placed where your phone heard each one strongest - an estimate, not the tower's real position."),+ "Cell towers: placed where your phone heard each one strongest - an estimate, not the tower's real position.\n\n" ++ "The map button turns the map: north up, then with your direction of travel, then the 3D driving view - like " ++ "a car navigation app, your arrow low on the screen, closer in town and further ahead at speed.\n\n" ++ "3D view angle: how far the driving view leans back; on fast roads it leans up to 10° further (60° at most).\n\n" ++ "Default zoom: how close the map follows you. The 3D driving view pulls back from it as you speed up; the " ++ "north-up and heading-up views sit half a level wider. 17 is close to Waze.\n\n" ++ "Map provider: OpenFreeMap (OpenStreetMap data, free, no account) or Mapbox (Mapbox's own map: 3D buildings, " ++ "day and night light). Mapbox loads its map from Mapbox's servers, which see the area you look at, like any " ++ "online map; its usage statistics are switched off. The floating mini map always uses OpenFreeMap."),Section("cameras", binding.headerCameras, binding.sectionCameras,"Plate-reader and speed / red-light camera positions come from OpenStreetMap.\n\n" +"Download automatically: fetches the cameras of the map area you look at (the Overpass server sees that area, like map tiles).\n\n" +@@ -478,9 +488,13 @@ class SettingsActivity : AppCompatActivity() {"• ESP32 boards with OUI-Spy, GhostESP or Marauder firmware (also through a Flipper Zero), FREE-WiLi 2.\n\n" +"• USB WiFi adapters in monitor mode: longer range, and they hear devices connected to networks. " +"RTL8811AU / 8821AU (ALFA AWUS036ACS), RTL8812BU / 8822BU, RTL8814AU (AWUS1900), MT7612U (AWUS036ACM), " ++ "MT7921AU (AWUS036AXML, WiFi 6E: 2.4, 5 and 6 GHz, experimental), " +"RTL8187 (AWUS036H), RT3070 (AWUS036NH / NEH), AR9271 (AWUS036NHA, experimental).\n\n" +"AWUS036ACS 5 GHz (experimental, off by default): the RTL8811AU / 8821AU also hops 5 GHz channels 36-48 and " +"149-165. Untested on every unit: if it misbehaves, turn it off and send the adapter log. Applies when the adapter is plugged in.\n\n" ++ "Adapter light: the AWUS036ACS blinks with received traffic; switch it off to keep it dark (for example in a car at night). " ++ "Only adapters whose light the app can control have this option (the RTL8811AU / 8821AU); the others keep their own behaviour. " ++ "Applies at once.\n\n" +"• RTL-SDR dongle: notices two-way radios transmitting nearby (signal strength only, nothing is decoded).\n\n" +"OUI-SPY over Bluetooth needs its App-Controlled firmware. Relay mode passes on every network and device it hears " +"so RF Sentinel's own lists check them (the board also sends standard Wi-Fi scan probes).\n\n" +@@ -891,6 +905,9 @@ class SettingsActivity : AppCompatActivity() {/** Settings > Map: what the map shows (moved here from the map's menu). Saved as you switch. */private fun setupMapSection() {+ setupMapProvider()+ setupMapZoom()+ setupMapTilt()binding.mapKnownCamerasSwitch.isChecked = Prefs.showKnownAlpr(this)binding.mapKnownCamerasSwitch.setOnCheckedChangeListener { _, on -> Prefs.setShowKnownAlpr(this, on) }binding.mapTowersSwitch.isChecked = Prefs.showCellTowers(this)@@ -927,6 +944,70 @@ class SettingsActivity : AppCompatActivity() {}}+ /** Settings > Map > 3D view angle: how far the driving view leans back (flatter = more overhead, steeper = further down the road). */+ private fun setupMapTilt() {+ fun show(t: Double) {+ val what = when { t <= 40 -> "flatter, more overhead"; t <= 55 -> "balanced, like Waze"; else -> "steep: far down the road" }+ binding.map3dTiltText.text = "3D view angle: ${t.toInt()}° ($what)"+ }+ val t = Prefs.map3dTilt(this)+ binding.map3dTiltSlider.value = t.toFloat(); show(t)+ binding.map3dTiltSlider.setLabelFormatter { "${it.toInt()}°" }+ binding.map3dTiltSlider.addOnChangeListener { _, v, fromUser ->+ if (!fromUser) return@addOnChangeListener+ Prefs.setMap3dTilt(this, v.toDouble()); show(v.toDouble())+ }+ }++ /** Settings > Map > Default zoom: how close the map follows you (the "Waze-like" button is the default). */+ private fun setupMapZoom() {+ fun show(z: Double) {+ val what = when {+ z <= 15.25 -> "wide: a neighbourhood"+ z <= 16.25 -> "a few blocks"+ z <= 17.25 -> "street level, close to Waze"+ else -> "very close: the next intersection"+ }+ binding.mapZoomText.text = "Default zoom: ${"%.2f".format(java.util.Locale.US, z).trimEnd('0').trimEnd('.')} ($what)"+ }+ val z = Prefs.mapDefaultZoom(this)+ // The slider counts quarter levels (58 = 14.5 ... 74 = 18.5): whole numbers, no rounding errors.+ binding.mapZoomSlider.value = Math.round(z * 4).toFloat(); show(z)+ binding.mapZoomSlider.setLabelFormatter { "%.2f".format(java.util.Locale.US, it / 4.0).trimEnd('0').trimEnd('.') }+ binding.mapZoomSlider.addOnChangeListener { _, v, fromUser ->+ if (!fromUser) return@addOnChangeListener+ Prefs.setMapDefaultZoom(this, v / 4.0); show(v / 4.0)+ }+ binding.mapZoomReset.setOnClickListener {+ Prefs.setMapDefaultZoom(this, Prefs.MAP_ZOOM_WAZE)+ binding.mapZoomSlider.value = (Prefs.MAP_ZOOM_WAZE * 4).toFloat(); show(Prefs.MAP_ZOOM_WAZE)+ }+ }++ /** Settings > Map > Map: OpenFreeMap or Mapbox (the open maps follow it when you're back). */+ private fun setupMapProvider() {+ val btn = binding.mapProviderButton+ fun show() { btn.text = com.rfsentinel.app.ui.MapEngine.chosen(this).label.substringBefore(" (") + " ▾" }+ show()+ btn.setOnClickListener {+ val all = com.rfsentinel.app.ui.MapEngine.Provider.entries+ if (!com.rfsentinel.app.ui.MapEngine.mapboxAvailable) {+ Toast.makeText(this, "Mapbox isn't available in this build", Toast.LENGTH_SHORT).show()+ return@setOnClickListener+ }+ val current = all.indexOf(com.rfsentinel.app.ui.MapEngine.chosen(this))+ androidx.appcompat.app.AlertDialog.Builder(this)+ .setTitle("Map provider")+ .setSingleChoiceItems(all.map { it.label }.toTypedArray(), current) { d, which ->+ Prefs.setMapProvider(this, all[which].key)+ show()+ d.dismiss()+ }+ .setNegativeButton("Cancel", null)+ .show()+ }+ }+/** A small grey line under a category switch, indented like the AirTag option. */private fun indentedNote(text: String) = android.widget.TextView(this).apply {this.text = text@@ -1161,7 +1242,9 @@ class SettingsActivity : AppCompatActivity() {"Parked for 90 s: checks run 4 times less often. Over 80 km/h: twice as often (Waze direct only).",Prefs.wazeAdaptive(this)) { Prefs.setWazeAdaptive(this, it) }switchRow("Only alert for reports ahead of me",- "While you drive, reports behind you stay on the list but don't alert, flash or speak.",+ "While you drive, only reports on the road you're on, ahead of you, alert, flash or speak - checked on the map's " ++ "roads, so one on a parallel road, a cross street, an overpass or behind you stays quiet (it stays on the list). " ++ "Where the map can't tell yet, reports behind you stay quiet.",Prefs.wazeAheadOnly(this)) { Prefs.setWazeAheadOnly(this, it) }switchRow("Call out again as I get closer","Speaks at 1 km, 500 m and 200 m when voice alerts are on, or in the car.",@@ -1549,6 +1632,11 @@ class SettingsActivity : AppCompatActivity() {setupLiveExport()binding.hideTrustedSwitch.isChecked = Prefs.hideWhitelisted(this)binding.hideTrustedSwitch.setOnCheckedChangeListener { _, on -> Prefs.setHideWhitelisted(this, on) }+ binding.usbLightSwitch.isChecked = Prefs.usbAdapterLight(this)+ binding.usbLightSwitch.setOnCheckedChangeListener { _, on ->+ Prefs.setUsbAdapterLight(this, on)+ com.rfsentinel.app.usb.Rtl8821auMonitor.lightEnabled = on // live, also while scanning+ }binding.rtl5gSwitch.isChecked = Prefs.rtl8821au5g(this)binding.rtl5gSwitch.setOnCheckedChangeListener { _, on -> Prefs.setRtl8821au5g(this, on) }binding.autoUpdateSwitch.isChecked = Prefs.autoUpdateCheck(this)diff --git a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.ktindex 579132a..78043e5 100644--- a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt@@ -17,11 +17,13 @@ object AboutDialog {ABSOLUTELY NO WARRANTY. Source code: github.com/CIS-C0/RFSentinel<br/><br/>Passive, receive-only Bluetooth LE and WiFi scanner. It never transmits to,connects to, jams or spoofs any device. Scans, detections, history and traces stay- on this phone. Internet is used only for OpenStreetMap: map tiles while the map is- open, and the list of known plate, speed and red-light cameras for the area you look at on+ on this phone. Internet is used only for map data: the map (OpenFreeMap, or Mapbox if+ you choose it in Settings), the road tiles of your area while the Waze "only ahead"+ option is on, and the list of known plate, speed and red-light cameras for the area you look at onscreen; in Android Auto, destination search (Nominatim) and routes (OSRM) when younavigate. Those servers see your IP and that area or trip, never your scans or detections.- Map data © OpenStreetMap contributors (ODbL).<br/><br/>+ Map data © OpenStreetMap contributors (ODbL), © OpenMapTiles; map engine+ MapLibre Native (BSD-2-Clause), OpenFreeMap; Mapbox Maps SDK (Mapbox terms) when selected.<br/><br/><b>What a match means</b><br/>A device with that vendor or payload signature is broadcasting nearby. It is not@@ -36,6 +38,7 @@ object AboutDialog {• ASTM F3411 Remote ID, decoded per opendroneid-core-c (Apache-2.0)<br/>• Google Find Hub Network accessory spec; arXiv 2501.17452; AirGuard, SEEMOO / TU Darmstadt (Apache-2.0) (trackers)<br/>• European V2X (ITS-G5) frame layout after V2X2MAP by Peter Holzhauser (MIT); CAM / DENM decoded per ETSI EN 302 637-2 / -3<br/>+ • MT7921AU (WiFi 6E) USB driver after mt76-usb-macos by Network Weather and the Linux mt76 driver (MediaTek, Lorenzo Bianconi, Felix Fietkau; BSD-3-Clause-Clear); MediaTek firmware under its own licence<br/>• Research by ryanohoro and GainSec (Flock); Alan Meekins' DEF CON 31 talk (Axon)<br/><br/>DedSec, fsociety and Night Vision theme font: Share Tech Mono © Carrois Type Design, SIL Open Fontdiff --git a/app/src/main/java/com/rfsentinel/app/ui/CctvConeOverlay.kt b/app/src/main/java/com/rfsentinel/app/ui/CctvConeOverlay.ktdeleted file mode 100644index 2b29cfe..0000000--- a/app/src/main/java/com/rfsentinel/app/ui/CctvConeOverlay.kt+++ /dev/null@@ -1,68 +0,0 @@-package com.rfsentinel.app.ui--import android.graphics.Canvas-import android.graphics.Paint-import android.graphics.Path-import android.graphics.RectF-import com.rfsentinel.app.alpr.Cctv-import com.rfsentinel.app.alpr.CctvCamera-import org.osmdroid.util.GeoPoint-import org.osmdroid.views.MapView-import org.osmdroid.views.overlay.Overlay--/**- * The area each CCTV camera watches: a translucent wedge toward `camera:direction`, as wide- * as `camera:angle` and reaching about 5x the mounting height (see [Cctv.viewRangeM]);- * a faint circle for dome / panning cameras with no mapped direction. Drawn under the icons.- */-class CctvConeOverlay(private val density: Float) : Overlay() {-- @Volatile var cameras: List<CctvCamera> = emptyList()-- private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }- private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }- private val px = android.graphics.Point()- private val path = Path()- private val oval = RectF()-- override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) {- if (shadow) return- val proj = mapView.projection- val zoom = mapView.zoomLevelDouble- val w = mapView.width; val h = mapView.height- edge.strokeWidth = 1f * density- for (c in cameras) {- proj.toPixels(GeoPoint(c.lat, c.lon), px)- val x = px.x.toFloat(); val y = px.y.toFloat()- val r = proj.metersToPixels(Cctv.viewRangeM(c).toFloat(), c.lat, zoom)- if (x < -w - r || y < -h - r || x > 2 * w + r || y > 2 * h + r) continue- val color = if (c.isPrivate) PRIVATE_COLOR else PUBLIC_COLOR- fill.color = (color and 0x00FFFFFF) or 0x33000000- edge.color = (color and 0x00FFFFFF) or 0x88000000.toInt()- val dir = c.direction- if (dir == null) {- // No direction: only domes / panning cameras get a (fainter, smaller) all-round area.- if (c.cameraType != "dome" && c.cameraType != "panning") continue- fill.color = (color and 0x00FFFFFF) or 0x1A000000- canvas.drawCircle(x, y, r * 0.6f, fill)- continue- }- val sweep = Cctv.viewAngle(c).toFloat()- // A full-circle view: Android treats a 360° arc as empty.- if (sweep >= 359f) { canvas.drawCircle(x, y, r, fill); canvas.drawCircle(x, y, r, edge); continue }- oval.set(x - r, y - r, x + r, y + r)- path.reset()- path.moveTo(x, y)- // Bearings run clockwise from north; Android arcs start at 3 o'clock.- path.arcTo(oval, dir - 90f - sweep / 2f, sweep)- path.close()- canvas.drawPath(path, fill)- canvas.drawPath(path, edge)- }- }-- companion object {- const val PUBLIC_COLOR = 0xFF455A64.toInt() // slate- const val PRIVATE_COLOR = 0xFF8D6E63.toInt() // brown-grey- }-}diff --git a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.ktindex a96d0f3..7f4d07b 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt@@ -26,7 +26,7 @@ class DetectionLogActivity : AppCompatActivity() {title = "Match history"supportActionBar?.setDisplayHomeAsUpEnabled(true)- val adapter = DetectionAdapter(onClick = { DeviceActions.openDetails(this, it.mac) })+ val adapter = DetectionAdapter(onClick = { DeviceActions.openDetection(this, it) })binding.recyclerView.layoutManager = LinearLayoutManager(this)binding.recyclerView.adapter = adapterdiff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.ktindex 7d678c3..707ee43 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt@@ -29,6 +29,23 @@ import kotlinx.coroutines.launch/** Actions on one device, shared by the list, the radar and the detail screen. */object DeviceActions {+ /**+ * A logged match: the device's details, or for a police aircraft or a Waze report the map on it -+ * where it is now while the feed still has it, else where it was logged.+ */+ fun openDetection(activity: AppCompatActivity, d: com.rfsentinel.app.data.DetectionEntity) {+ // Internet alerts are logged as "AIR <ICAO address>" / "WAZE <report id>" (their alert key).+ val key = d.mac.takeIf { d.source == "ONLINE" && ' ' in it }?.let { it.substringBefore(' ').lowercase() + ":" + it.substringAfter(' ') }+ val intent = key?.let { MapActivity.onlineIntent(activity, it, d.latitude, d.longitude) }+ if (key == null || intent == null) { openDetails(activity, d.mac); return }+ if (d.latitude == null && !MapActivity.onlineIsLive(key)) {+ android.widget.Toast.makeText(activity, "Its position wasn't saved (GPS tagging off) and it's no longer current",+ android.widget.Toast.LENGTH_LONG).show()+ return+ }+ activity.startActivity(intent)+ }+fun openDetails(activity: AppCompatActivity, mac: String) {activity.startActivity(Intent(activity, DeviceDetailActivity::class.java).putExtra(DeviceDetailActivity.EXTRA_MAC, mac)diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.ktnew file mode 100644index 0000000..5aecc5d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt@@ -0,0 +1,153 @@+package com.rfsentinel.app.ui++import android.content.Intent+import android.graphics.Typeface+import android.os.Bundle+import android.text.format.DateUtils+import android.view.View+import android.view.ViewGroup+import android.widget.LinearLayout+import android.widget.TextView+import androidx.appcompat.app.AppCompatActivity+import androidx.core.widget.doAfterTextChanged+import androidx.lifecycle.lifecycleScope+import androidx.recyclerview.widget.DiffUtil+import androidx.recyclerview.widget.LinearLayoutManager+import androidx.recyclerview.widget.ListAdapter+import androidx.recyclerview.widget.RecyclerView+import com.google.android.material.chip.Chip+import com.rfsentinel.app.data.AppDatabase+import com.rfsentinel.app.data.KnownDeviceDao+import com.rfsentinel.app.data.KnownDeviceEntity+import com.rfsentinel.app.databinding.ActivityDeviceHistoryBinding+import com.rfsentinel.app.util.Prefs+import com.rfsentinel.app.util.applySystemBarInsets+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import java.util.Calendar++/**+ * Every device the app remembers, in range or not: search by MAC, name, vendor, type or your note,+ * and open the device's details page (its saved history) with a tap.+ */+class DeviceHistoryActivity : AppCompatActivity() {++ private enum class Filter(val label: String) { ALL("All"), FAVORITES("Favorites"), FLAGGED("Flagged before"), TODAY("Seen today") }++ private lateinit var binding: ActivityDeviceHistoryBinding+ private val adapter = Rows { DeviceActions.openDetails(this, it.mac) }+ private var filter = Filter.ALL+ private var searchJob: Job? = null++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ binding = ActivityDeviceHistoryBinding.inflate(layoutInflater)+ setContentView(binding.root)+ binding.root.applySystemBarInsets()+ title = "Device history"+ supportActionBar?.setDisplayHomeAsUpEnabled(true)++ binding.recyclerView.layoutManager = LinearLayoutManager(this)+ binding.recyclerView.adapter = adapter+ for (f in Filter.entries) {+ val chip = Chip(this, null, com.google.android.material.R.attr.chipStyle).apply {+ id = View.generateViewId(); text = f.label; isCheckable = true; isCheckedIconVisible = false+ ChipStyle.apply(this)+ isChecked = f == filter+ setOnClickListener { if (filter != f) { filter = f; search(now = true) } }+ }+ binding.filterChips.addView(chip)+ }+ binding.searchInput.doAfterTextChanged { search(now = false) }+ binding.keptText.setOnClickListener {+ startActivity(Intent(this, com.rfsentinel.app.settings.SettingsActivity::class.java)+ .putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION, com.rfsentinel.app.settings.SettingsActivity.SECTION_DATA))+ }+ }++ override fun onResume() {+ super.onResume()+ // Back from a device's page (a note, a favorite) or Settings: up to date.+ val days = Prefs.retentionDays(this)+ binding.keptText.text = (if (days <= 0) "History is kept forever" else "History is kept for $days days") ++ " (change in Settings > Data)"+ search(now = true)+ }++ /** Runs the search, a moment after the last key so typing stays smooth. */+ private fun search(now: Boolean) {+ searchJob?.cancel()+ searchJob = lifecycleScope.launch {+ if (!now) delay(250)+ val q = binding.searchInput.text?.toString()?.trim().orEmpty()+ val dao = AppDatabase.getInstance(this@DeviceHistoryActivity).knownDeviceDao()+ val since = if (filter == Filter.TODAY) startOfToday() else 0L+ val rows = dao.search(q, KnownDeviceDao.like(q), KnownDeviceDao.likeHex(q),+ filter == Filter.FAVORITES, filter == Filter.FLAGGED, since, LIMIT)+ val total = dao.count()+ adapter.submitList(rows)+ binding.emptyText.visibility = if (rows.isEmpty()) View.VISIBLE else View.GONE+ binding.emptyText.text = when {+ total == 0 -> "No devices remembered yet. Start scanning: every device heard is kept here."+ else -> "Nothing matches."+ }+ supportActionBar?.subtitle = when {+ rows.size >= LIMIT -> "First $LIMIT of the matches · $total remembered"+ q.isEmpty() && filter == Filter.ALL -> "$total remembered"+ else -> "${rows.size} found · $total remembered"+ }+ }+ }++ private fun startOfToday() = Calendar.getInstance().apply {+ set(Calendar.HOUR_OF_DAY, 0); set(Calendar.MINUTE, 0); set(Calendar.SECOND, 0); set(Calendar.MILLISECOND, 0)+ }.timeInMillis++ override fun onSupportNavigateUp(): Boolean { finish(); return true }++ private companion object { const val LIMIT = 500 }++ /** One device: name (or MAC) and type, then vendor and MAC, then when it was seen. */+ private class Rows(private val open: (KnownDeviceEntity) -> Unit) :+ ListAdapter<KnownDeviceEntity, Rows.Holder>(object : DiffUtil.ItemCallback<KnownDeviceEntity>() {+ override fun areItemsTheSame(a: KnownDeviceEntity, b: KnownDeviceEntity) = a.mac == b.mac+ override fun areContentsTheSame(a: KnownDeviceEntity, b: KnownDeviceEntity) = a == b+ }) {++ class Holder(val root: LinearLayout, val title: TextView, val line: TextView, val seen: TextView) : RecyclerView.ViewHolder(root)++ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {+ val c = parent.context+ val d = c.resources.displayMetrics.density+ fun text(size: Float) = TextView(c).apply { textSize = size }+ val title = text(16f).apply { setTypeface(typeface, Typeface.BOLD) }+ val line = text(13f).apply { alpha = 0.8f }+ val seen = text(12f).apply { alpha = 0.65f }+ val root = LinearLayout(c).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(0, (10 * d).toInt(), 0, (10 * d).toInt())+ layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)+ val ripple = android.util.TypedValue()+ c.theme.resolveAttribute(android.R.attr.selectableItemBackground, ripple, true)+ setBackgroundResource(ripple.resourceId)+ addView(title); addView(line); addView(seen)+ }+ return Holder(root, title, line, seen)+ }++ override fun onBindViewHolder(h: Holder, position: Int) {+ val k = getItem(position)+ val c = h.root.context+ h.title.text = (if (k.favorite) "★ " else "") + (k.name?.takeIf { it.isNotBlank() } ?: k.mac) ++ (k.deviceType?.takeIf { it.isNotBlank() }?.let { " · $it" } ?: "")+ h.line.text = listOfNotNull(k.vendor?.takeIf { it.isNotBlank() }, k.mac.takeIf { k.name?.isNotBlank() == true },+ k.note?.takeIf { it.isNotBlank() }?.let { "Note: $it" }).joinToString(" · ").ifEmpty { "Unknown vendor" }+ h.line.visibility = View.VISIBLE+ val last = DateUtils.getRelativeTimeSpanString(k.lastSeen, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS)+ val first = DateUtils.formatDateTime(c, k.firstSeen, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_MONTH)+ h.seen.text = "Last seen $last · first $first · ${k.sessions} session${if (k.sessions == 1) "" else "s"}"+ h.root.setOnClickListener { open(k) }+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.ktindex 598f23d..018242a 100644--- a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt@@ -25,11 +25,23 @@ import android.widget.Toastimport androidx.core.content.editimport com.rfsentinel.app.service.ScanForegroundServiceimport com.rfsentinel.app.util.Prefs-import org.osmdroid.tileprovider.tilesource.TileSourceFactory-import org.osmdroid.util.GeoPoint-import org.osmdroid.views.CustomZoomButtonsController-import org.osmdroid.views.MapView-import org.osmdroid.views.overlay.TilesOverlay+import org.maplibre.android.MapLibre+import org.maplibre.android.camera.CameraPosition+import org.maplibre.android.camera.CameraUpdateFactory+import org.maplibre.android.geometry.LatLng+import org.maplibre.android.maps.MapLibreMap+import org.maplibre.android.maps.MapLibreMapOptions+import org.maplibre.android.maps.MapView+import org.maplibre.android.maps.Style+import org.maplibre.android.style.expressions.Expression.get+import org.maplibre.android.style.expressions.Expression.toColor+import org.maplibre.android.style.layers.CircleLayer+import org.maplibre.android.style.layers.PropertyFactory+import org.maplibre.android.style.layers.SymbolLayer+import org.maplibre.android.style.sources.GeoJsonSource+import org.maplibre.geojson.Feature+import org.maplibre.geojson.FeatureCollection+import org.maplibre.geojson.Pointimport kotlin.math.abs/**@@ -38,7 +50,8 @@ import kotlin.math.abs* on top), a border in the threat colour and the flagged count. Drag to move, tap to* open the full map, ✕ to turn it off. Needs "Display over other apps"; hidden while* RF Sentinel itself is on screen. While it shows, location runs in precise mode, like- * the full map.+ * the full map. Always OpenFreeMap (MapLibre), whichever map Settings picks for the app: a window+ * this small has no room for another provider's logo and info button.*/object FloatingMap {@@ -50,21 +63,26 @@ object FloatingMap {private const val SIZE_DP = 170private const val MIN_DP = 120+ /** Zoom levels as saved (the old raster map's); the vector map shows the same scale one level lower. */private const val ZOOM = 16.0private const val MIN_ZOOM = 11.0private const val MAX_ZOOM = 19.0+ private const val ZOOM_SHIFT = 1.0private const val ME_COLOR = 0xFF1A73E8.toInt()private val main = Handler(Looper.getMainLooper())private var root: FrameLayout? = null- private var map: MapView? = null+ private var view: MapView? = null+ private var map: MapLibreMap? = nullprivate var badge: TextView? = nullprivate var waiting: TextView? = nullprivate var border: GradientDrawable? = null- private var dots: PointsOverlay<Unit>? = null- private var me: PointsOverlay<Unit>? = null- private var cams: PointsOverlay<Unit>? = null- private var camIcons: Map<com.rfsentinel.app.alpr.KnownCamera.Kind, android.graphics.Bitmap> = emptyMap()+ /** The latest dots and position, drawn as soon as the map's style is in (and with every update). */+ private var lastDevices: List<Dot> = emptyList()+ private var lastCameras: List<Cam> = emptyList()+ private var lastHere: Location? = null+ /** Saved-scale zoom (see [ZOOM_SHIFT]). */+ private var zoom = ZOOMfun canShow(context: Context) = Settings.canDrawOverlays(context)@@ -79,30 +97,44 @@ object FloatingMap {text = if (flagged == 0) "✓" else if (flagged > 99) "99+" else flagged.toString()background = GradientDrawable().apply { cornerRadius = dp(app, 11f).toFloat(); setColor(level.color) }}- cams?.points = cameras.mapNotNull { c ->- val icon = camIcons[c.kind] ?: return@mapNotNull null- PointsOverlay.Point(c.lat, c.lon, Unit, icon = icon, alpha = if (c.ignored) 90 else 255)- }- dots?.points = devices.sortedBy { it.flagged }.map {- PointsOverlay.Point(it.lat, it.lon, Unit, color = it.color, sizeDp = if (it.flagged) 15f else 9f)+ lastDevices = devices; lastCameras = cameras; lastHere = here+ waiting?.visibility = if (here != null) View.GONE else View.VISIBLE+ draw()+ }++ /** The cameras, the devices (flagged ones larger, on top) and you, centred. */+ private fun draw() {+ val m = map ?: return+ val style = m.style?.takeIf { it.isFullyLoaded } ?: return+ runCatching {+ style.getSourceAs<GeoJsonSource>(CAMS)?.setGeoJson(FeatureCollection.fromFeatures(lastCameras.map { c ->+ Feature.fromGeometry(Point.fromLngLat(c.lon, c.lat)).apply {+ addStringProperty("icon", "fm-cam-${c.kind.name}"); addNumberProperty("opacity", if (c.ignored) 0.35f else 1f)+ }+ }))+ style.getSourceAs<GeoJsonSource>(DOTS)?.setGeoJson(FeatureCollection.fromFeatures(lastDevices.sortedBy { it.flagged }.map { d ->+ Feature.fromGeometry(Point.fromLngLat(d.lon, d.lat)).apply {+ addStringProperty("color", String.format("#%06X", d.color and 0xFFFFFF))+ addNumberProperty("r", if (d.flagged) 7.5f else 4.5f)+ addNumberProperty("k", if (d.flagged) 1f else 0f)+ }+ }))+ val here = lastHere+ style.getSourceAs<GeoJsonSource>(ME)?.setGeoJson(FeatureCollection.fromFeatures(+ if (here == null) emptyList() else listOf(Feature.fromGeometry(Point.fromLngLat(here.longitude, here.latitude)))))+ if (here != null) m.moveCamera(CameraUpdateFactory.newLatLng(LatLng(here.latitude, here.longitude)))}- val m = map ?: return@post- if (here != null) {- val p = GeoPoint(here.latitude, here.longitude)- me?.points = listOf(PointsOverlay.Point(p.latitude, p.longitude, Unit, color = ME_COLOR, sizeDp = 14f))- m.controller.setCenter(p)- waiting?.visibility = View.GONE- } else waiting?.visibility = View.VISIBLE- m.invalidate()}+ private const val CAMS = "fm-cams"; private const val DOTS = "fm-dots"; private const val ME = "fm-me"+fun hide(context: Context) = main.post { removeNow(context.applicationContext) }private fun removeNow(context: Context) {val r = root ?: returnrunCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(r) }- runCatching { map?.onDetach() }- root = null; map = null; badge = null; waiting = null; border = null; dots = null; me = null; cams = null+ view?.let { v -> runCatching { v.onPause(); v.onStop(); v.onDestroy() } }+ root = null; view = null; map = null; badge = null; waiting = null; border = nullScanForegroundService.mapHidden(context)}@@ -129,7 +161,7 @@ object FloatingMap {y = prefs.getInt("y", dp(context, 120f))}- MapIcons.configureOsm(context)+ MapLibre.getInstance(context)val radius = 18f * dval frame = FrameLayout(context).apply {background = GradientDrawable().apply { cornerRadius = radius; setColor(Color.BLACK) }.also { border = it }@@ -139,22 +171,32 @@ object FloatingMap {clipToOutline = trueelevation = 6f * d}- val m = MapView(context).apply {- setTileSource(TileSourceFactory.MAPNIK)- setMultiTouchControls(false)- zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)- isTilesScaledToDpi = true- controller.setZoom(prefs.getFloat("zoom", ZOOM.toFloat()).toDouble().coerceIn(MIN_ZOOM, MAX_ZOOM))+ zoom = prefs.getFloat("zoom", ZOOM.toFloat()).toDouble().coerceIn(MIN_ZOOM, MAX_ZOOM)+ // A window over other apps: the texture view draws there reliably; the map engine needs its+ // lifecycle by hand (no activity owns it).+ val m = MapView(context, MapLibreMapOptions.createFromAttributes(context).textureMode(true)+ .camera(CameraPosition.Builder().target(LatLng(0.0, 0.0)).zoom(zoom - ZOOM_SHIFT).build())+ .compassEnabled(false).logoEnabled(false).attributionEnabled(false)+ .scrollGesturesEnabled(false).zoomGesturesEnabled(false).rotateGesturesEnabled(false).tiltGesturesEnabled(false))+ m.onCreate(null)+ m.getMapAsync { lm ->+ map = lmval night = (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES- if (night) overlayManager.tilesOverlay.setColorFilter(TilesOverlay.INVERT_COLORS)+ lm.setStyle(Style.Builder().fromUri(if (night) MapLibreEngine.DARK_STYLE else MapLibreEngine.LIGHT_STYLE)) { style ->+ runCatching {+ com.rfsentinel.app.alpr.KnownCamera.Kind.entries.forEach { style.addImage("fm-cam-${it.name}", MapIcons.cameraIcon(d * 0.85f, it)) }+ listOf(CAMS, DOTS, ME).forEach { style.addSource(GeoJsonSource(it)) }+ style.addLayer(SymbolLayer(CAMS, CAMS).withProperties(PropertyFactory.iconImage(get("icon")),+ PropertyFactory.iconOpacity(get("opacity")), PropertyFactory.iconAllowOverlap(true), PropertyFactory.iconIgnorePlacement(true)))+ style.addLayer(CircleLayer(DOTS, DOTS).withProperties(PropertyFactory.circleColor(toColor(get("color"))),+ PropertyFactory.circleRadius(get("r")), PropertyFactory.circleSortKey(get("k")),+ PropertyFactory.circleStrokeColor("#FFFFFF"), PropertyFactory.circleStrokeWidth(1.2f)))+ style.addLayer(CircleLayer(ME, ME).withProperties(PropertyFactory.circleColor(String.format("#%06X", ME_COLOR and 0xFFFFFF)),+ PropertyFactory.circleRadius(7f), PropertyFactory.circleStrokeColor("#FFFFFF"), PropertyFactory.circleStrokeWidth(2f)))+ draw()+ }+ }}- val dotLayer = PointsOverlay<Unit>(d) {}- val meLayer = PointsOverlay<Unit>(d) {}- val camLayer = PointsOverlay<Unit>(d) {}- if (camIcons.isEmpty()) camIcons = com.rfsentinel.app.alpr.KnownCamera.Kind.entries.associateWith { MapIcons.cameraIcon(d * 0.85f, it) }- m.overlays.add(camLayer)- m.overlays.add(dotLayer)- m.overlays.add(meLayer)val inset = dp(context, 3f)frame.addView(m, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT).apply {setMargins(inset, inset, inset, inset)@@ -200,8 +242,8 @@ object FloatingMap {// One zoom level per doubling of the finger spread, in or out.val now = span(e)if (now > 1f) {- val z = (m.zoomLevelDouble + Math.log((now / pinchSpan).toDouble()) / Math.log(2.0)).coerceIn(MIN_ZOOM, MAX_ZOOM)- m.controller.setZoom(z)+ zoom = (zoom + Math.log((now / pinchSpan).toDouble()) / Math.log(2.0)).coerceIn(MIN_ZOOM, MAX_ZOOM)+ map?.moveCamera(CameraUpdateFactory.zoomTo(zoom - ZOOM_SHIFT))pinchSpan = now}} else if (!pinched && e.pointerCount == 1) {@@ -211,7 +253,7 @@ object FloatingMap {if (moved) { lp.x = startX - dx.toInt(); lp.y = startY + dy.toInt(); runCatching { wm.updateViewLayout(frame, lp) } }}MotionEvent.ACTION_UP -> {- if (pinched) prefs.edit { putFloat("zoom", m.zoomLevelDouble.toFloat()) }+ if (pinched) prefs.edit { putFloat("zoom", zoom.toFloat()) }else if (moved) prefs.edit { putInt("x", lp.x); putInt("y", lp.y) }else if (v === close) turnOff(context)else context.startActivity(Intent(context, MapActivity::class.java)@@ -254,8 +296,8 @@ object FloatingMap {return runCatching {wm.addView(frame, lp)- m.onResume()- root = frame; map = m; badge = count; waiting = wait; dots = dotLayer; me = meLayer; cams = camLayer+ m.onStart(); m.onResume()+ root = frame; view = m; badge = count; waiting = waitScanForegroundService.mapShown(context)frame}.getOrNull()diff --git a/app/src/main/java/com/rfsentinel/app/ui/HeatmapOverlay.kt b/app/src/main/java/com/rfsentinel/app/ui/HeatmapOverlay.ktdeleted file mode 100644index 06d1122..0000000--- a/app/src/main/java/com/rfsentinel/app/ui/HeatmapOverlay.kt+++ /dev/null@@ -1,82 +0,0 @@-package com.rfsentinel.app.ui--import android.graphics.Bitmap-import android.graphics.Canvas-import android.graphics.Color-import android.graphics.Paint-import android.graphics.RadialGradient-import android.graphics.Rect-import android.graphics.Shader-import org.osmdroid.util.GeoPoint-import org.osmdroid.views.MapView-import org.osmdroid.views.overlay.Overlay--/**- * A classic density heatmap: every point adds a soft blob of "heat" to an- * intensity buffer (drawn at quarter resolution for speed), and the summed- * intensity is coloured blue -> green -> yellow -> red. Recomputed only when- * the view moves or zooms.- */-class HeatmapOverlay(private val radiusDp: Float) : Overlay() {-- var points: List<GeoPoint> = emptyList()- set(value) { field = value; cacheKey = null }-- private val palette = IntArray(256) { i -> heatColor(i / 255f) }- private var cache: Bitmap? = null- private var cacheKey: String? = null- private val blit = Paint(Paint.FILTER_BITMAP_FLAG)-- override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) {- if (shadow || points.isEmpty()) return- val w = mapView.width; val h = mapView.height- if (w == 0 || h == 0) return- val key = "${mapView.boundingBox}|${mapView.zoomLevelDouble}|$w|$h|${points.size}"- if (key != cacheKey) {- cache = render(mapView, w, h)- cacheKey = key- }- val bmp = cache ?: return- // Map rotation isn't enabled, so the overlay canvas is in screen coordinates.- canvas.drawBitmap(bmp, null, Rect(0, 0, w, h), blit)- }-- private fun render(mapView: MapView, w: Int, h: Int): Bitmap {- val scale = 4- val bw = (w / scale).coerceAtLeast(1); val bh = (h / scale).coerceAtLeast(1)- val intensity = Bitmap.createBitmap(bw, bh, Bitmap.Config.ALPHA_8)- val c = Canvas(intensity)- val r = radiusDp * mapView.resources.displayMetrics.density / scale- val paint = Paint(Paint.ANTI_ALIAS_FLAG)- val pt = android.graphics.Point()- val proj = mapView.projection- for (p in points) {- proj.toPixels(p, pt)- val x = pt.x / scale.toFloat(); val y = pt.y / scale.toFloat()- if (x < -r || y < -r || x > bw + r || y > bh + r) continue- // Each point adds up to ~25% opacity; overlapping points build up heat.- paint.shader = RadialGradient(x, y, r, 0x40000000, 0x00000000, Shader.TileMode.CLAMP)- c.drawCircle(x, y, r, paint)- }- val alpha = ByteArray(bw * bh)- intensity.copyPixelsToBuffer(java.nio.ByteBuffer.wrap(alpha))- intensity.recycle()- val colors = IntArray(bw * bh)- for (i in alpha.indices) {- val a = alpha[i].toInt() and 0xFF- colors[i] = if (a < 4) Color.TRANSPARENT else palette[a]- }- return Bitmap.createBitmap(colors, bw, bh, Bitmap.Config.ARGB_8888)- }-- /** 0..1 -> translucent blue, cyan, green, yellow, opaque red. */- private fun heatColor(t: Float): Int {- val stops = floatArrayOf(0f, 0.25f, 0.5f, 0.75f, 1f)- val cols = intArrayOf(0x2020A0FF, 0x7000E5FF, 0x9000D060.toInt(), 0xB0FFE000.toInt(), 0xE0FF2020.toInt())- val i = stops.indexOfLast { it <= t }.coerceIn(0, stops.size - 2)- val f = ((t - stops[i]) / (stops[i + 1] - stops[i])).coerceIn(0f, 1f)- fun lerp(a: Int, b: Int, s: Int) = (((a shr s) and 0xFF) + (((b shr s) and 0xFF) - ((a shr s) and 0xFF)) * f).toInt() shl s- val a = cols[i]; val b = cols[i + 1]- return lerp(a, b, 24) or lerp(a, b, 16) or lerp(a, b, 8) or lerp(a, b, 0)- }-}diff --git a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.ktindex 11fc8c7..bac56f8 100644--- a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt@@ -1,32 +1,22 @@package com.rfsentinel.app.ui-import android.graphics.Color-import android.graphics.drawable.GradientDrawableimport android.os.Bundleimport android.view.MenuItemimport androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScope-import com.rfsentinel.app.BuildConfigimport com.rfsentinel.app.Rimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.databinding.ActivityHistoryBindingimport com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.history.Historyimport com.rfsentinel.app.history.HistoryEvent+import com.rfsentinel.app.util.Prefsimport com.rfsentinel.app.util.applySystemBarInsetsimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext-import org.osmdroid.config.Configuration-import org.osmdroid.tileprovider.tilesource.TileSourceFactory-import org.osmdroid.util.BoundingBox-import org.osmdroid.util.GeoPoint-import org.osmdroid.views.CustomZoomButtonsController-import org.osmdroid.views.overlay.CopyrightOverlay-import org.osmdroid.views.overlay.FolderOverlay-import org.osmdroid.views.overlay.Marker-import java.io.File+import org.json.JSONObjectimport java.text.DateFormatimport java.util.Date@@ -38,19 +28,16 @@ import java.util.Dateclass HistoryActivity : AppCompatActivity() {private lateinit var binding: ActivityHistoryBinding- private val heat by lazy { HeatmapOverlay(radiusDp = 38f) }- private val points = FolderOverlay()+ private var engine: MapEngine? = null+ private var map: MapEngine? = nullprivate var events: List<HistoryEvent> = emptyList()+ /** The encounters drawn as points, to find what a tap hit. */+ private var shown: List<HistoryEvent> = emptyList()private var fitted = falseprivate val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)- Configuration.getInstance().apply {- userAgentValue = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}"- osmdroidBasePath = File(cacheDir, "osmdroid")- osmdroidTileCache = File(cacheDir, "osmdroid/tiles")- }binding = ActivityHistoryBinding.inflate(layoutInflater)setContentView(binding.root)title = "History map & timeline"@@ -58,15 +45,28 @@ class HistoryActivity : AppCompatActivity() {// Edge-to-edge: keep the filter row below the action bar and the panel above the nav bar.binding.root.applySystemBarInsets()- val map = binding.map- map.setTileSource(TileSourceFactory.MAPNIK)- map.setMultiTouchControls(true)- map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)- map.minZoomLevel = 3.0- map.controller.setZoom(4.0)- map.overlays.add(heat)- map.overlays.add(points)- map.overlays.add(CopyrightOverlay(this)) // "© OpenStreetMap contributors"+ // The map chosen in Settings > Map (OpenFreeMap or Mapbox).+ val e = MapEngine.create(this).also { engine = it }+ binding.map.addView(e.view, android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,+ android.view.ViewGroup.LayoutParams.MATCH_PARENT))+ binding.mapCredit.text = e.credit+ e.onCreate(savedInstanceState)+ e.whenReady {+ if (isDestroyed) return@whenReady+ map = e+ e.setMinZoom(2.0)+ e.jumpTo(30.0, 0.0, 3.0)+ e.onClick = { x, y -> onTap(e, x, y) }+ val dark = Prefs.mapDark(this) ?: ((resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==+ android.content.res.Configuration.UI_MODE_NIGHT_YES)+ if (dark) { binding.mapCredit.setBackgroundColor(0x99000000.toInt()); binding.mapCredit.setTextColor(0xFFDDDDDD.toInt()) }+ // Mapbox's logo and info button, top left of the map.+ binding.mapCredit.post { if (!isDestroyed) e.placeBranding(0) }+ e.setStyle(dark) { fresh ->+ if (fresh) runCatching { addLayers(e) }+ render()+ }+ }var lastRange = binding.rangeChips.checkedChipIdbinding.rangeChips.setOnCheckedStateChangeListener { group, ids ->@@ -107,13 +107,39 @@ class HistoryActivity : AppCompatActivity() {}}+ /**+ * The heatmap: every encounter adds heat, coloured blue -> cyan -> green -> yellow -> red as it+ * builds up (as before); points: one dot per encounter in its category's colour.+ */+ private fun addLayers(m: MapEngine) {+ m.addSource(HEAT)+ m.addSource(POINTS)+ m.addLayer(JSONObject("""{"id":"$HEAT","type":"heatmap","source":"$HEAT","paint":{+ "heatmap-radius":38,"heatmap-weight":0.35,"heatmap-opacity":0.9,+ "heatmap-color":["interpolate",["linear"],["heatmap-density"],+ 0,"rgba(0,0,0,0)",0.1,"rgba(32,32,160,0.13)",0.3,"rgba(0,229,255,0.44)",+ 0.55,"rgba(0,208,96,0.56)",0.8,"rgba(255,224,0,0.69)",1,"rgba(255,32,32,0.88)"]}}"""))+ m.addLayer(JSONObject("""{"id":"$POINTS","type":"circle","source":"$POINTS","paint":{+ "circle-color":["to-color",["get","color"]],"circle-radius":6,+ "circle-stroke-color":"#FFFFFF","circle-stroke-width":1.5,"circle-pitch-alignment":"viewport"}}"""))+ }+private fun render() {val positioned = events.filter { it.positioned }- val geo = positioned.map { GeoPoint(it.lat!!, it.lon!!) }val showHeat = binding.heatChip.isChecked- heat.points = if (showHeat) geo else emptyList()- points.items.clear()- if (!showHeat) drawPoints(positioned)+ val m = map+ m?.takeIf { it.styleLoaded }?.let { mm ->+ runCatching {+ mm.setData(HEAT, GeoJson.collection(+ if (showHeat) positioned.map { GeoJson.feature(GeoJson.point(it.lat!!, it.lon!!)) } else emptyList()))+ shown = if (showHeat) emptyList() else positioned.take(3000)+ mm.setData(POINTS, GeoJson.collection(shown.withIndex().map { (i, e) ->+ GeoJson.feature(GeoJson.point(e.lat!!, e.lon!!), "i" to i.toString(),+ "color" to String.format("#%06X",+ ThemeManager.ink(this@HistoryActivity, Category.parse(e.category)?.colorArgb ?: 0xFF607D8B.toInt()) and 0xFFFFFF))+ }))+ }+ }binding.summaryText.text = when {events.isEmpty() -> "No flagged equipment logged in this period"@@ -130,47 +156,46 @@ class HistoryActivity : AppCompatActivity() {binding.hourChart.set(History.byHour(events), List(24) { h -> if (h % 6 == 0) "${h}h" else null })binding.dayChart.set(History.byWeekday(events), listOf("M", "T", "W", "T", "F", "S", "S"))- if (!fitted && geo.isNotEmpty()) {+ if (!fitted && positioned.isNotEmpty() && m != null && m.styleLoaded) {fitted = truebinding.map.post {- if (geo.size == 1) { binding.map.controller.setZoom(15.0); binding.map.controller.setCenter(geo[0]) }- else binding.map.zoomToBoundingBox(BoundingBox.fromGeoPoints(geo).increaseByScale(1.4f), false)+ runCatching {+ if (positioned.size == 1) m.jumpTo(positioned[0].lat!!, positioned[0].lon!!, 14.0)+ else m.fit(positioned.map { it.lat!! to it.lon!! }, (48 * resources.displayMetrics.density).toInt())+ }}}- binding.map.invalidate()}private fun top(): String = History.topLabels(events).joinToString(", ") { "${it.first} (${it.second})" }- private fun drawPoints(list: List<HistoryEvent>) {- val dp = resources.displayMetrics.density- list.take(3000).forEach { e ->- val color = ThemeManager.ink(this, Category.parse(e.category)?.colorArgb ?: 0xFF607D8B.toInt())- points.add(Marker(binding.map).apply {- position = GeoPoint(e.lat!!, e.lon!!)- icon = GradientDrawable().apply {- shape = GradientDrawable.OVAL- setColor(color)- setStroke((1.5f * dp).toInt(), Color.WHITE)- setSize((12 * dp).toInt(), (12 * dp).toInt())- }- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- setOnMarkerClickListener { _, _ ->- AlertDialog.Builder(this@HistoryActivity)- .setTitle(e.label)- .setMessage("${dateFmt.format(Date(e.time))}\n${e.mac}")- .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(this@HistoryActivity, e.mac) }- .setNegativeButton("Close", null)- .show()- true- }- })+ /** A tapped point: when it was, and the device. */+ private fun onTap(m: MapEngine, x: Float, y: Float) {+ val r = 18f * resources.displayMetrics.density+ m.query(android.graphics.RectF(x - r, y - r, x + r, y + r), listOf(POINTS to "i")) { found ->+ if (isFinishing || isDestroyed) return@query+ val e = found.firstOrNull()?.firstOrNull()?.toIntOrNull()?.let { shown.getOrNull(it) } ?: return@query+ AlertDialog.Builder(this)+ .setTitle(e.label)+ .setMessage("${dateFmt.format(Date(e.time))}\n${e.mac}")+ .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(this, e.mac) }+ .setNegativeButton("Close", null)+ .show()}}- override fun onResume() { super.onResume(); binding.map.onResume() }- override fun onPause() { binding.map.onPause(); super.onPause() }- override fun onDestroy() { binding.map.onDetach(); super.onDestroy() }+ override fun onStart() { super.onStart(); engine?.onStart() }+ override fun onResume() { super.onResume(); engine?.onResume() }+ override fun onPause() { engine?.onPause(); super.onPause() }+ override fun onStop() { engine?.onStop(); super.onStop() }+ override fun onLowMemory() { super.onLowMemory(); engine?.onLowMemory() }+ override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState); engine?.onSaveInstanceState(outState) }+ override fun onDestroy() { engine?.onDestroy(); engine = null; map = null; super.onDestroy() }++ private companion object {+ const val HEAT = "history-heat"+ const val POINTS = "history-points"+ }override fun onOptionsItemSelected(item: MenuItem): Boolean {if (item.itemId == android.R.id.home) { finish(); return true }diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.ktindex 5fb2710..b0824cb 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt@@ -19,6 +19,29 @@ class MapActivity : AppCompatActivity() {const val EXTRA_CENTER_LON = MapFragment.EXTRA_CENTER_LON/** Turn the cell tower layer on. */const val EXTRA_SHOW_TOWERS = MapFragment.EXTRA_SHOW_TOWERS+ /** Open the map on an aircraft (its ICAO address): where it is now, else its last known position. */+ const val EXTRA_AIRCRAFT = MapFragment.EXTRA_AIRCRAFT+ /** Open the map on a Waze report (its id), with its details while it's current. */+ const val EXTRA_WAZE = MapFragment.EXTRA_WAZE++ /**+ * The map on what an internet alert is about - [key] "air:<ICAO address>" or "waze:<report id>" -+ * last seen at [lat] / [lon] (null when not saved); null for any other key.+ */+ fun onlineIntent(context: android.content.Context, key: String, lat: Double?, lon: Double?): android.content.Intent? {+ val extra = when (key.substringBefore(':')) { "air" -> EXTRA_AIRCRAFT; "waze" -> EXTRA_WAZE; else -> return null }+ return android.content.Intent(context, MapActivity::class.java).apply {+ putExtra(extra, key.substringAfter(':'))+ if (lat != null && lon != null) { putExtra(EXTRA_CENTER_LAT, lat); putExtra(EXTRA_CENTER_LON, lon) }+ }+ }++ /** Whether what [key] is about is still in the live feed (an aircraft in range, a current Waze report). */+ fun onlineIsLive(key: String): Boolean = when (key.substringBefore(':')) {+ "air" -> com.rfsentinel.app.online.PoliceAircraft.current(key.substringAfter(':')) != null+ "waze" -> com.rfsentinel.app.online.WazePolice.current(key.substringAfter(':')) != null+ else -> false+ }}override fun onCreate(savedInstanceState: Bundle?) {diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapEngine.ktnew file mode 100644index 0000000..322fa96--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt@@ -0,0 +1,145 @@+package com.rfsentinel.app.ui++import android.content.Context+import android.graphics.Bitmap+import android.graphics.RectF+import android.location.Location+import android.os.Bundle+import android.view.View+import com.rfsentinel.app.BuildConfig+import com.rfsentinel.app.util.Prefs+import org.json.JSONArray+import org.json.JSONObject++/**+ * The map engine under RF Sentinel's maps: MapLibre with OpenFreeMap (free, no account - the+ * default) or Mapbox's own SDK and maps (Settings > Map > Map provider). Layers are written once,+ * as map style JSON, and data goes in as GeoJSON, so [RfMap] and the screens draw the same on both.+ */+internal interface MapEngine {++ enum class Provider(val key: String, val label: String) {+ OPENFREEMAP("openfreemap", "OpenFreeMap (OpenStreetMap, free, no account)"),+ MAPBOX("mapbox", "Mapbox");++ companion object {+ fun parse(key: String?) = entries.firstOrNull { it.key == key } ?: OPENFREEMAP+ }+ }++ /** Following your position: not at all, north up, or turning with your heading. */+ enum class Follow { NONE, NORTH, HEADING }++ data class Camera(val lat: Double, val lon: Double, val zoom: Double, val bearing: Double, val tilt: Double)++ /** North, east, south, west. */+ data class Box(val north: Double, val east: Double, val south: Double, val west: Double) {+ fun contains(o: Box) = o.north <= north && o.south >= south && o.east <= east && o.west >= west+ fun contains(lat: Double, lon: Double) = lat in south..north && lon in west..east+ }++ val provider: Provider+ val view: View+ /** The map data credit to show on the map (Mapbox also shows its logo and an info button). */+ val credit: String+ /** Fonts the map's labels can use (each provider serves its own). */+ val labelFont: List<String>++ // ---- lifecycle (forwarded by the screen) ----+ fun onCreate(state: Bundle?)+ fun onStart()+ fun onResume()+ fun onPause()+ fun onStop()+ fun onLowMemory()+ fun onSaveInstanceState(out: Bundle)+ fun onDestroy()++ fun whenReady(ready: () -> Unit)++ // ---- style ----+ /** The light or night map; [loaded] gets true when the style is new (its layers need adding again). */+ fun setStyle(dark: Boolean, loaded: (fresh: Boolean) -> Unit)+ val styleLoaded: Boolean+ fun hasSource(id: String): Boolean+ fun addImage(id: String, bitmap: Bitmap)+ /** An empty GeoJSON source. */+ fun addSource(id: String)+ fun setData(source: String, geoJson: String)+ /** A layer as map style JSON ({"id", "type", "source", "minzoom", "filter", "layout", "paint"}). */+ fun addLayer(json: JSONObject)+ /** Changes one paint property (a colour...) of a layer already on the map. */+ fun setPaint(layer: String, name: String, value: String)++ // ---- camera ----+ val camera: Camera+ fun jumpTo(lat: Double, lon: Double, zoom: Double? = null)+ fun zoomTo(zoom: Double)+ /** Animated; null keeps that part. [flat] also drops any padding. */+ fun easeTo(lat: Double? = null, lon: Double? = null, zoom: Double? = null, bearing: Double? = null,+ tilt: Double? = null, flat: Boolean = false, ms: Long = 600)+ fun fit(points: List<Pair<Double, Double>>, paddingPx: Int)+ fun visibleBox(): Box?+ fun toLatLon(x: Float, y: Float): Pair<Double, Double>?+ fun setMinZoom(zoom: Double)++ var onCameraMove: (() -> Unit)?+ var onIdle: (() -> Unit)?+ var onClick: ((x: Float, y: Float) -> Unit)?+ /** A gesture (pinch...) moved the map while following. */+ var onUserGesture: (() -> Unit)?++ /** The [key] property of what's drawn in [box] for each (layer, key), in the same order. */+ fun query(box: RectF, layers: List<Pair<String, String>>, result: (List<List<String>>) -> Unit)++ // ---- your position ----+ /** Shows your arrow (once the style is in); false without location permission. */+ fun startPuck(): Boolean+ val puckOn: Boolean+ fun pushFix(fix: Location)+ /** Keeps you in view: [topPaddingPx] lowers your arrow, [tilt] and [zoom] (null: leave it) set the view. */+ fun follow(mode: Follow, topPaddingPx: Double?, tilt: Double, zoom: Double?, ms: Long)+ /** You panned away: the map stopped following. */+ var onFollowDismissed: (() -> Unit)?+ /** Where the provider's logo and info button go (Mapbox: under the credit line). */+ fun placeBranding(topPx: Int)++ companion object {+ val mapboxAvailable get() = BuildConfig.MAPBOX_TOKEN.isNotEmpty()++ fun chosen(context: Context): Provider =+ Provider.parse(Prefs.mapProvider(context)).takeIf { it != Provider.MAPBOX || mapboxAvailable } ?: Provider.OPENFREEMAP++ fun create(context: Context, provider: Provider = chosen(context)): MapEngine = when (provider) {+ Provider.MAPBOX -> MapboxEngine(context)+ Provider.OPENFREEMAP -> MapLibreEngine(context)+ }+ }+}++/** GeoJSON for the map sources, built the same way for both engines. */+internal object GeoJson {+ fun point(lat: Double, lon: Double): JSONObject =+ JSONObject().put("type", "Point").put("coordinates", JSONArray().put(lon).put(lat))++ fun line(points: List<Pair<Double, Double>>): JSONObject =+ JSONObject().put("type", "LineString").put("coordinates", coords(points))++ /** A (lat, lon) ring. */+ fun polygon(ring: List<Pair<Double, Double>>): JSONObject =+ JSONObject().put("type", "Polygon").put("coordinates", JSONArray().put(coords(ring)))++ private fun coords(points: List<Pair<Double, Double>>) =+ JSONArray().apply { points.forEach { put(JSONArray().put(it.second).put(it.first)) } }++ fun feature(geometry: JSONObject, vararg props: Pair<String, Any?>): JSONObject {+ val p = JSONObject()+ for ((k, v) in props) if (v != null) p.put(k, v)+ return JSONObject().put("type", "Feature").put("geometry", geometry).put("properties", p)+ }++ fun collection(features: List<JSONObject>): String =+ JSONObject().put("type", "FeatureCollection").put("features", JSONArray(features)).toString()++ const val EMPTY = """{"type":"FeatureCollection","features":[]}"""+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.ktindex ee24578..cbd81e5 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt@@ -1,14 +1,17 @@package com.rfsentinel.app.ui+import android.annotation.SuppressLintimport android.content.Intent-import android.graphics.Color-import android.graphics.drawable.GradientDrawable+import android.location.Location+import android.location.LocationListener+import android.location.LocationManager+import android.os.Buildimport android.os.Bundle+import android.os.Looperimport android.view.LayoutInflaterimport android.view.Menuimport android.view.MenuInflaterimport android.view.MenuItem-import android.view.MotionEventimport android.view.Viewimport android.view.ViewGroupimport android.widget.EditText@@ -33,36 +36,28 @@ import com.rfsentinel.app.service.ScanForegroundServiceimport com.rfsentinel.app.service.TripRecorderimport com.rfsentinel.app.util.Exporterimport com.rfsentinel.app.util.Permissions+import com.rfsentinel.app.util.Prefsimport kotlinx.coroutines.delayimport kotlinx.coroutines.isActiveimport kotlinx.coroutines.launch-import org.osmdroid.tileprovider.tilesource.TileSourceFactory-import org.osmdroid.util.BoundingBox-import org.osmdroid.util.GeoPoint-import org.osmdroid.views.CustomZoomButtonsController-import org.osmdroid.views.overlay.CopyrightOverlay-import org.osmdroid.views.overlay.FolderOverlay-import org.osmdroid.views.overlay.Marker-import org.osmdroid.views.overlay.Polygon-import org.osmdroid.views.overlay.Polyline-import org.osmdroid.views.overlay.ScaleBarOverlay-import org.osmdroid.views.overlay.TilesOverlay-import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider-import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlayimport java.text.DateFormatimport java.util.Dateimport java.util.Locale/**- * OpenStreetMap view of a scan. Live mode shows your position, the trace being- * recorded and nearby devices; trip mode shows a saved trace. Devices are drawn- * where YOUR phone was when their signal was strongest - an approximation.+ * The map of a scan, on the chosen [MapEngine] - OpenFreeMap or Mapbox ([RfMap] draws it). Live mode+ * shows your position, the trace being recorded and everything detected around you; trip mode+ * shows a saved trace. Devices are drawn where YOUR phone was when their signal was strongest -+ * an approximation - unless pinpointed.+ *+ * The map button turns it: north up -> heading up -> 3D driving view (a real 3D camera that+ * follows your heading, your arrow low on the screen, closer in town and further ahead at speed).** Shown full screen by [MapActivity] (a saved trace, a place to look at, a notification) and* embedded in the main screen's Map view, where the main screen's filter chips drive it and* its menu items are in the main screen's menu.*- * Network use: map tiles only (OpenStreetMap), cached in the app's cache dir.+ * Network use: the map (OpenFreeMap, or Mapbox when chosen in Settings), cached by the map engine.*/class MapFragment : Fragment() {@@ -75,35 +70,52 @@ class MapFragment : Fragment() {const val EXTRA_CENTER_LON = "center_lon"/** Turn the cell tower layer on. */const val EXTRA_SHOW_TOWERS = "show_towers"+ /**+ * An aircraft's ICAO address (hex): the map opens on where it is now when the ADS-B feed still+ * has it, else on [EXTRA_CENTER_LAT] / [EXTRA_CENTER_LON] (its last known position), with its details.+ */+ const val EXTRA_AIRCRAFT = "aircraft"+ /** A Waze report's id: the map opens on it ([EXTRA_CENTER_LAT] / [EXTRA_CENTER_LON]) with its details while it's current. */+ const val EXTRA_WAZE = "waze"/** Inside the main screen (its chips drive the filter; the menu is a button on the map). */const val ARG_EMBEDDED = "embedded"/** A failed camera download stays in the status line this long (the retry runs after a minute). */private const val CAMERA_FAIL_SHOWN_MS = 90_000L- private const val TRACE_COLOR = 0xFFE0622D.toInt()- private const val PAST_TRACE_COLOR = 0xFF1F5FBF.toInt()- private const val DRONE_COLOR = 0xFF1F5FBF.toInt()private const val GPS_MOVING_MS = 1_000Lprivate const val GPS_PARKED_MS = 5_000L+ /** [MapStart]'s levels are the classic raster map's: the vector map's are this much lower. */+ private const val ZOOM_SHIFT = MapStart.VECTOR_SHIFT+ /** 3D: your arrow this far down the map (navigation apps: about 70 %), so you see more road ahead. */+ internal const val ARROW_HEIGHT = 0.72++ fun create(args: Bundle) = MapFragment().apply { arguments = args }+/**- * 3D view: the tilt, and the camera distance in map-area heights (proportional, so the- * perspective looks the same in a small pane and full screen; the size is worked out in tiltFit).+ * 3D camera zoom from speed: close street level in town, wider on fast roads so the next+ * kilometre stays on screen (vector zoom levels: 17 up to 30 km/h, 15.4 from 110 km/h).*/- /** Upper limit for the tilted view's height, in map-area heights. */- private const val TILT_MAX_HEIGHT = 6f- private const val TILT_DEGREES = 50f- private const val TILT_CAMERA = 14.3f+ internal fun zoomFor(kmh: Float, base: Double = Prefs.MAP_ZOOM_WAZE): Double = when {+ kmh <= 30f -> base+ kmh >= 110f -> base - 1.6+ else -> base - (kmh - 30f) / 80f * 1.6+ }- fun create(args: Bundle) = MapFragment().apply { arguments = args }- }+ /** The flat views (north up / heading up) sit this much wider than the 3D view at the same default. */+ internal const val FLAT_ZOOM_OFFSET = 0.5++ /** 3D tilt from speed: 50° in town (junctions readable), up to 60° on fast roads (further down the road). */+ internal fun tiltFor(kmh: Float, base: Double = Prefs.MAP_TILT_DEFAULT): Double = when {+ kmh <= 30f -> base+ kmh >= 110f -> (base + 10.0).coerceAtMost(MAX_TILT)+ else -> (base + (kmh - 30f) / 80f * 10.0).coerceAtMost(MAX_TILT)+ }++ /** The most the map engines tilt (MapLibre's limit). */+ internal const val MAX_TILT = 60.0- /** One device to draw, from the live registry or a saved trip. */- private data class Pin(- val mac: String, val lat: Double, val lon: Double, val label: String, val flagged: Boolean,- val color: Int, val details: String,- /** Pinpointed (see [com.rfsentinel.app.detect.Locator]): the circle it is very likely in. */- val radiusM: Double? = null,- val whereNote: String = "Position = where your phone was when this device's signal was strongest (approximate)."- )+ /** Top padding (px) that puts the camera's focus - your arrow - [ARROW_HEIGHT] of the way down a [height] px map. */+ internal fun topPaddingFor(height: Int): Double = height * (2 * ARROW_HEIGHT - 1)+ }private var _binding: ActivityMapBinding? = nullprivate val binding get() = _binding!!@@ -125,52 +137,19 @@ class MapFragment : Fragment() {private var startedOnWorld = false/** The map keeps your position centred until you pan it yourself. */private var following = false-- private val trace = Polyline()- /** Pinpointed flagged devices: a faint circle where each one very likely is, under the dots. */- private val precision = FolderOverlay()- private val pins by lazy { PointsOverlay<Pin>(resources.displayMetrics.density) { showPins(it) } }- /** Live drones from Remote ID: aircraft, operator and the line between them. */- private val drones = FolderOverlay()- /** Aircraft from the ADS-B feeds (Settings > What to detect > Police / government aircraft). */- private val aircraft = FolderOverlay()- /** Waze reports (Settings > What to detect > Waze): shown on the All and Waze chips. */- private val wazeLayer = FolderOverlay()- private var planeZoomStep = -1- /** Plate-reader cameras mapped in OpenStreetMap (downloaded on request). */- private val knownAlpr by lazy {- PointsOverlay<com.rfsentinel.app.alpr.KnownCamera>(resources.displayMetrics.density) { showKnownCamera(it.first()) }- }- private var knownAlprDrawnFor: BoundingBox? = null- /** CCTV cameras mapped in OpenStreetMap (Settings > Known cameras, off by default): icons over their view cones. */- private val cctv by lazy {- PointsOverlay<com.rfsentinel.app.alpr.CctvCamera>(resources.displayMetrics.density) { showCctv(it.first()) }- }- private val cctvCones by lazy { CctvConeOverlay(resources.displayMetrics.density) }- /** Cell towers seen while scanning, at their estimated (strongest-signal) spot. */- private val towers by lazy {- PointsOverlay<com.rfsentinel.app.service.CellTowerStore.Tower>(resources.displayMetrics.density) { showTower(it.first()) }- }- private val towerIcon by lazy { MapIcons.towerIcon(resources.displayMetrics.density) }- private lateinit var myLocation: MyLocationNewOverlay- private val scaleBar by lazy { ScaleBarOverlay(binding.map).apply { setAlignBottom(false); setScaleBarOffset(20, 180) } }-- private fun placeScaleBar() {- val b = _binding ?: return- val gap = (8 * resources.displayMetrics.density).toInt()- val box = b.statusBox- val y = if (box.height > 0) box.bottom + box.translationY.toInt() + gap else box.top + box.translationY.toInt()- scaleBar.setScaleBarOffset(20, y.coerceAtLeast(gap))- // The 3D view's map credit takes the scale bar's place.- b.osmCredit.translationY = y.coerceAtLeast(gap).toFloat()- b.map.invalidate()- }+ /** 3D: you pinched - your zoom until the follow button. */+ private var userZoom = false++ private var engine: MapEngine? = null+ private var rf: RfMap? = null+ private val map: MapEngine? get() = rf?.map+ private var lastFix: Location? = null+ private var lastBearing: Float? = null+ private var smoothKmh = -1f+ private var stopObservingBulk: (() -> Unit)? = nullprivate val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {- // osmdroid: identify ourselves to the tile server (OSM tile policy) and keep- // the tile cache inside the app's private cache.- MapIcons.configureOsm(requireContext())_binding = ActivityMapBinding.inflate(inflater, container, false)return binding.root}@@ -187,10 +166,7 @@ class MapFragment : Fragment() {insets}- if (args.getBoolean(EXTRA_SHOW_TOWERS, false)) com.rfsentinel.app.util.Prefs.setShowCellTowers(act, true)- setupMap()- binding.map.post { if (_binding != null) drawKnownAlpr() }- // Every device heard around you by default (same colours as the list and radar).+ if (args.getBoolean(EXTRA_SHOW_TOWERS, false)) Prefs.setShowCellTowers(act, true)setupFilterChips()styleFollowButton()// Outlined "Traces" in the theme highlight (the stock dark teal was unreadable on dark themes).@@ -198,12 +174,19 @@ class MapFragment : Fragment() {binding.tracesButton.setTextColor(accent)binding.tracesButton.strokeColor = android.content.res.ColorStateList.valueOf(accent)}- binding.centerButton.setOnClickListener {- if (tripId == null) setFollow(true) else centerOnMe()- }+ binding.centerButton.setOnClickListener { if (tripId == null) setFollow(true) else centerOnMe() }binding.tracesButton.setOnClickListener { startActivity(Intent(act, TripsActivity::class.java)) }setupThemeButton()+ setupSettingsButton()+ setupOrientationButton()setupMenu()+ // The scale and the map credit sit just under the status banner, or at the very top when there is none.+ binding.statusBox.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> placeScaleBar() }++ createEngine(savedInstanceState, null)+ binding.map.addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->+ if (bottom - top != oldBottom - oldTop) applyMode(animate = false)+ }if (tripId == null) {observeBulk()@@ -226,40 +209,147 @@ class MapFragment : Fragment() {}} else {binding.recordButton.visibility = View.GONE- loadTrip()}if (embedded) compactControls()}/** The main screen's filter chip, for the embedded map. */fun setFilter(f: DeviceFilter) {- if (f == filter || _binding == null) { filter = f; return }+ if (f == filter || _binding == null) { filter = f; rf?.filter = f; return }filter = f+ rf?.filter = fif (tripId != null) loadTrip() else renderLive()- drawTowers()- }-- // ---- Light / dark map ------------------------------------------------------------------------------- private fun darkTiles(): Boolean = com.rfsentinel.app.util.Prefs.mapDark(act)+ rf?.maybeRedrawStatic(force = true)+ }++ // ---- The map -----------------------------------------------------------------------------------++ /** The map engine chosen in Settings > Map; [restore] is where the one it replaces was looking. */+ private fun createEngine(state: Bundle?, restore: MapEngine.Camera?) {+ val e = MapEngine.create(act)+ engine = e+ binding.map.addView(e.view, 0, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))+ binding.osmCredit.text = e.credit+ e.onCreate(state)+ e.whenReady { if (alive && engine === e) onMapReady(e, restore) }+ }++ /** Back from Settings with the other map provider chosen: the map changes in place, looking at the same spot. */+ private fun swapEngineIfChanged() {+ val old = engine ?: return+ if (old.provider == MapEngine.chosen(act)) return+ val cam = old.camera.takeIf { rf != null }+ rf = null+ old.onPause(); old.onStop(); old.onDestroy()+ binding.map.removeView(old.view)+ createEngine(null, cam)+ engine?.apply { onStart(); onResume() }+ }++ private fun onMapReady(m: MapEngine, restore: MapEngine.Camera?) {+ val r = RfMap(act, m).also { rf = it }+ r.filter = filter+ r.tripMode = tripId != null+ r.onStaticChanged = { if (alive) { renderLive(); refreshServiceLocation() } }+ m.setMinZoom(2.0)+ // Two fingers in 3D: a pinch is your zoom now (until the follow button).+ m.onUserGesture = { if (following) userZoom = true }+ m.onFollowDismissed = { if (alive && following) { following = false; styleFollowButton() } }+ m.onCameraMove = { updateScale() }+ m.onIdle = { r.safe("static") { r.maybeRedrawStatic(); updateScale() } }+ m.onClick = { x, y -> r.safe("tap") { r.onTap(x, y, myPosition()) } }+ if (restore != null) { m.jumpTo(restore.lat, restore.lon, restore.zoom); centeredOnce = true }+ else placeCameraAtStart(m)+ placeScaleBar()+ loadStyle()+ }++ private fun darkTiles(): Boolean = Prefs.mapDark(act)?: ((resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==android.content.res.Configuration.UI_MODE_NIGHT_YES)- /** Dark map = the OpenStreetMap tiles with their colours inverted (as in dark mode before). */- private fun applyTiles() {- binding.map.overlayManager.tilesOverlay.setColorFilter(if (darkTiles()) TilesOverlay.INVERT_COLORS else null)+ private fun loadStyle() {+ val r = rf ?: return+ val dark = darkTiles()styleThemeButton()- binding.map.invalidate()+ binding.osmCredit.setBackgroundColor(if (dark) 0x99000000.toInt() else 0x99FFFFFF.toInt())+ binding.osmCredit.setTextColor(if (dark) 0xFFDDDDDD.toInt() else 0xFF333333.toInt())+ r.loadStyle(dark) {+ if (!alive) return@loadStyle+ r.safe("location") { startLocation() }+ if (tripId != null) loadTrip() else renderLive()+ r.safe("static") { r.maybeRedrawStatic(force = true) }+ }}+ /**+ * Where the map first looks: a place it was opened on (an aircraft, a Waze report, a tower), else+ * where you are or were (never open sea at street zoom), else a world view.+ */+ private fun placeCameraAtStart(m: MapEngine) {+ val planeHex = args.getString(EXTRA_AIRCRAFT)+ val wazeId = args.getString(EXTRA_WAZE)+ val focusPlane = planeHex?.let { com.rfsentinel.app.online.PoliceAircraft.current(it) }+ val focusWaze = wazeId?.let { com.rfsentinel.app.online.WazePolice.current(it) }+ val focus = focusPlane?.let { it.plane.lat to it.plane.lon }+ ?: focusWaze?.let { it.report.lat to it.report.lon }+ ?: if (args.containsKey(EXTRA_CENTER_LAT)) args.getDouble(EXTRA_CENTER_LAT) to args.getDouble(EXTRA_CENTER_LON) else null+ if (focus != null) {+ // Aircraft: room around it to see where it's going.+ m.jumpTo(focus.first, focus.second, (if (planeHex != null) 12.0 else 15.0) - ZOOM_SHIFT)+ centeredOnce = true+ binding.map.post {+ if (!alive) return@post+ when {+ focusPlane != null -> rf?.showAircraft(focusPlane, myPosition())+ focusWaze != null -> MapDialogs.showWaze(act, focusWaze)+ planeHex != null -> Toast.makeText(act, "No longer in range - this is where it was last seen", Toast.LENGTH_LONG).show()+ wazeId != null -> Toast.makeText(act, "This Waze report has expired - this is where it was", Toast.LENGTH_LONG).show()+ }+ }+ return+ }+ if (tripId != null) return // framed on the trace once it's loaded+ val knownFix = knownFix()+ val start = MapStart.camera(+ listOf(knownFix?.let { MapStart.Fix(it.latitude, it.longitude, it.time) }),+ Prefs.lastMapCenter(act), MapStart.savedZoom(Prefs.mapDefaultZoom(act) - FLAT_ZOOM_OFFSET), System.currentTimeMillis()+ )+ startedOnWorld = start.zoom <= MapStart.WORLD_ZOOM - ZOOM_SHIFT+ m.jumpTo(start.lat, start.lon, start.zoom)+ if (start.fresh) { centeredOnce = true; lastFix = knownFix }+ // Live map: keep your position centred until you pan away.+ if (Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION)) following = true+ styleFollowButton()+ }++ /** Your position (lat, lon) for distances in the details, when known. */+ private fun myPosition(): Pair<Double, Double>? =+ (lastFix ?: ScanForegroundService.lastFix)?.let { it.latitude to it.longitude }++ // ---- Light / dark map -----------------------------------------------------------------------------+private fun setupThemeButton() {binding.themeButton.setOnClickListener {val dark = !darkTiles()- com.rfsentinel.app.util.Prefs.setMapDark(act, dark)- applyTiles()+ Prefs.setMapDark(act, dark)+ loadStyle()Toast.makeText(act, if (dark) "Dark map" else "Light map", Toast.LENGTH_SHORT).show()}- applyTiles()+ styleThemeButton()+ }++ /** The gear on the map: Settings > Map (the map provider, what the map shows). */+ private fun setupSettingsButton() {+ binding.mapSettingsButton.backgroundTintList = android.content.res.ColorStateList.valueOf(0xFFFFFFFF.toInt())+ binding.mapSettingsButton.imageTintList = android.content.res.ColorStateList.valueOf(0xFF0B5C63.toInt())+ binding.mapSettingsButton.setOnClickListener { openMapSettings() }+ }++ private fun openMapSettings() {+ startActivity(Intent(act, com.rfsentinel.app.settings.SettingsActivity::class.java)+ .putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION,+ com.rfsentinel.app.settings.SettingsActivity.SECTION_MAP))}private fun styleThemeButton() {@@ -270,6 +360,33 @@ class MapFragment : Fragment() {binding.themeButton.contentDescription = if (dark) "Dark map (tap for light)" else "Light map (tap for dark)"}+ // ---- Scale and credit ----------------------------------------------------------------------------++ private fun placeScaleBar() {+ val b = _binding ?: return+ val gap = (8 * resources.displayMetrics.density).toInt()+ val box = b.statusBox+ val y = (if (box.height > 0) box.bottom + box.translationY.toInt() + gap else box.top + box.translationY.toInt()).coerceAtLeast(gap)+ b.scaleBar.translationY = y.toFloat()+ b.osmCredit.translationY = (y + b.scaleBar.height).toFloat()+ // Mapbox's logo and info button just under the credit line.+ engine?.placeBranding(y + b.scaleBar.height + b.osmCredit.height + gap / 2)+ }++ private fun updateScale() {+ val m = map ?: return+ val b = _binding ?: return+ // Tilted, the scale differs across the screen: no single scale to show.+ if (m.camera.tilt > 5) { b.scaleBar.visibility = View.INVISIBLE; return }+ b.scaleBar.visibility = View.VISIBLE+ // Measured on the ground between two points 100 px apart across the middle of the map.+ val w = b.map.width; val h = b.map.height+ if (w < 200 || h == 0) return+ val a = m.toLatLon(w / 2f - 50f, h / 2f) ?: return+ val z = m.toLatLon(w / 2f + 50f, h / 2f) ?: return+ b.scaleBar.setMetersPerPixel(DeviceRegistry.metersBetween(a.first, a.second, z.first, z.second) / 100.0)+ }+// ---- Embedded in the main screen ------------------------------------------------------------------/**@@ -289,10 +406,10 @@ class MapFragment : Fragment() {binding.fullscreenButton.backgroundTintList = android.content.res.ColorStateList.valueOf(0xFFFFFFFF.toInt())binding.fullscreenButton.imageTintList = android.content.res.ColorStateList.valueOf(0xFF0B5C63.toInt())binding.fullscreenButton.setOnClickListener { startActivity(Intent(act, MapActivity::class.java)) }- // A short pane has no room for four buttons stacked on the right: light / dark and full- // screen join Record and Traces along the bottom; the compass and follow stay on the right.+ // A short pane has no room for five buttons stacked on the right: map settings, light / dark and+ // full screen join Record and Traces along the bottom; the compass and follow stay on the right.val gap = (8 * resources.displayMetrics.density).toInt()- for (v in listOf(binding.themeButton, binding.fullscreenButton)) {+ for (v in listOf(binding.mapSettingsButton, binding.themeButton, binding.fullscreenButton)) {(v.parent as? ViewGroup)?.removeView(v)binding.compactControls.addView(v, android.widget.LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginStart = gap })@@ -302,408 +419,272 @@ class MapFragment : Fragment() {binding.statusText.textSize = 12f}- private fun setupMap() {- val map = binding.map- map.setTileSource(TileSourceFactory.MAPNIK)- map.setMultiTouchControls(true)- // Pinch to zoom; no + / - buttons.- map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)- // Open where you are, not on (0, 0): the live map used to sit on open sea until the first GPS fix.- val liveHere = tripId == null && !args.containsKey(EXTRA_CENTER_LAT)- val knownFix = if (liveHere) knownFix() else null- val start = if (liveHere) MapStart.pick(- listOf(knownFix?.let { MapStart.Fix(it.latitude, it.longitude, it.time) }),- com.rfsentinel.app.util.Prefs.lastMapCenter(act), com.rfsentinel.app.util.Prefs.mapZoom(act), System.currentTimeMillis()- ) else null- map.controller.setZoom(start?.zoom ?: if (liveHere) MapStart.WORLD_ZOOM else MapStart.DEFAULT_ZOOM)- startedOnWorld = liveHere && start == null- if (start != null) {- map.controller.setCenter(GeoPoint(start.lat, start.lon))- if (start.fresh) centeredOnce = true // already where you are: the first GPS fix need not move the map- }- map.minZoomLevel = 3.0- map.maxZoomLevel = 20.0+ // ---- Your position --------------------------------------------------------------------------------- trace.outlinePaint.apply {- color = if (tripId == null) TRACE_COLOR else PAST_TRACE_COLOR- strokeWidth = 7f * resources.displayMetrics.density / 2- }- map.overlays.add(cctvCones)- map.overlays.add(cctv)- map.overlays.add(knownAlpr)- map.overlays.add(towers)- map.overlays.add(trace)- map.overlays.add(precision)- map.overlays.add(pins)- map.overlays.add(drones)- map.overlays.add(wazeLayer)- map.overlays.add(aircraft)- // Redraw the camera layer for the visible area after panning / zooming.- map.addMapListener(object : org.osmdroid.events.MapListener {- override fun onScroll(event: org.osmdroid.events.ScrollEvent?) = false.also {- drawKnownAlprSoon()- // osmdroid stops following when you drag the map: show that on the button.- if (following && !myLocation.isFollowLocationEnabled) setFollow(false)- }- override fun onZoom(event: org.osmdroid.events.ZoomEvent?) = false.also {- drawKnownAlprSoon()- // Plane icons grow as you zoom in (and shrink as you zoom out).- val step = kotlin.math.round(binding.map.zoomLevelDouble * 2).toInt()- if (step != planeZoomStep) { planeZoomStep = step; drawAircraft() }- }- })+ private fun startLocation() {+ val m = map ?: return+ if (!m.startPuck()) return+ (lastFix ?: knownFix())?.let { m.pushFix(steady(it)) }+ applyMode(animate = false)+ }- myLocation = object : MyLocationNewOverlay(gps, map) {- override fun onLocationChanged(location: android.location.Location?, source: org.osmdroid.views.overlay.mylocation.IMyLocationProvider?) {- super.onLocationChanged(arrowFix(location), source)- if (location != null) activity?.runOnUiThread { if (alive) { turnToHeading(location); adaptGpsRate(location); autoZoomFor(location) } }- }- init { defaultPerson = mPersonBitmap; defaultArrow = mDirectionArrowBitmap }- }- if (Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION)) {- myLocation.enableMyLocation()- if (args.containsKey(EXTRA_CENTER_LAT)) {- // Opened on a place (a cell tower): look there instead of following you.- map.controller.setZoom(15.0)- map.controller.setCenter(GeoPoint(args.getDouble(EXTRA_CENTER_LAT), args.getDouble(EXTRA_CENTER_LON)))- centeredOnce = true- } else if (tripId == null) {- // Live map: keep your position centred from the first fix until you pan away.- setFollow(true, quiet = true)- myLocation.runOnFirstFix {- activity?.runOnUiThread {- if (alive && !centeredOnce) {- centeredOnce = true- if (following) {- if (startedOnWorld) { startedOnWorld = false; binding.map.controller.setZoom(MapStart.DEFAULT_ZOOM) }- centerOnMe()- }- }- }- }- // A current position puts the arrow on the map straight away instead of after the first GPS update.- if (start?.fresh == true) knownFix?.let { myLocation.onLocationChanged(it, null) }- }- }- // Under the device dots, drones, Waze reports and aircraft (above the trace and the camera layers), so it never hides what was detected.- map.overlays.add(map.overlays.indexOf(pins).coerceAtLeast(0), myLocation)- setupOrientationButton()- map.overlays.add(scaleBar)- setup3dPinch(map)- // The scale sits just under the status banner, or at the very top when there is none.- binding.statusBox.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> placeScaleBar() }- map.overlays.add(CopyrightOverlay(act)) // "© OpenStreetMap contributors" (required attribution)- binding.root.addOnLayoutChangeListener { _, l, t, r, btm, ol, ot, or, ob ->- if (r - l != or - ol || btm - t != ob - ot) binding.root.post { apply3d() }+ /**+ * A fix as the map gets it: stopped or crawling, the GPS course is noise - keep the last real+ * heading so a turning map doesn't swing around at a red light.+ */+ private fun steady(fix: Location): Location {+ val moving = fix.hasSpeed() && fix.speed >= HEADING_MIN_SPEED_MS && fix.hasBearing()+ if (moving) { lastBearing = fix.bearing; return fix }+ return Location(fix).apply { lastBearing?.let { bearing = it } }+ }++ private val gpsListener = LocationListener { fix -> rf?.safe("fix") { onFix(fix) } ?: onFix(fix) }++ private fun onFix(fix: Location) {+ if (!alive) return+ lastFix = fix+ val m = map?.takeIf { it.puckOn } ?: return+ m.pushFix(steady(fix))+ adaptGpsRate(fix)+ val kmh = if (fix.hasSpeed()) fix.speed * 3.6f else 0f+ val before = smoothKmh+ smoothKmh = if (smoothKmh < 0f) kmh else smoothKmh * 0.7f + kmh * 0.3f+ if (!centeredOnce && following) {+ centeredOnce = true+ if (startedOnWorld) { startedOnWorld = false; m.zoomTo(Prefs.mapDefaultZoom(act) - FLAT_ZOOM_OFFSET) }+ applyMode(animate = false)}+ // 3D: re-aim only when the speed changed enough to matter (no constant zoom pumping).+ val base = Prefs.mapDefaultZoom(act)+ val drives = is3d() || (tripId == null && Prefs.mapHeadingUp(act))+ if (drives && (before < 0f || kotlin.math.abs(zoomFor(smoothKmh, base) - zoomFor(before.coerceAtLeast(0f), base)) > 0.1)) applyMode(animate = true)}// ---- Battery: the map's own GPS ---------------------------------------------------------------------/*** The position arrow's GPS: a fix a second (2 m) while moving - smooth enough for driving -- * and every 5 s (10 m) after a minute parked, instead of osmdroid's default of every fix.- * Runs only while the map is on screen (off with the screen, the app in the background,- * or the main screen's Map view turned off).+ * and every 5 s (10 m) after a minute parked. Runs only while the map is on screen (off with+ * the screen, the app in the background, or the main screen's Map view turned off).*/- private val gps by lazy {- GpsMyLocationProvider(act).apply { locationUpdateMinTime = GPS_MOVING_MS; locationUpdateMinDistance = 2f }- }+ private var listening = falseprivate var gpsParked = falseprivate var stillSince = 0L- private fun adaptGpsRate(fix: android.location.Location) {+ @SuppressLint("MissingPermission")+ private fun startGps() {+ if (listening || !Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION)) return+ val lm = act.getSystemService(android.content.Context.LOCATION_SERVICE) as LocationManager+ val provider = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && lm.hasProvider(LocationManager.FUSED_PROVIDER))+ LocationManager.FUSED_PROVIDER else LocationManager.GPS_PROVIDER+ val ms = if (gpsParked) GPS_PARKED_MS else GPS_MOVING_MS+ val meters = if (gpsParked) 10f else 2f+ runCatching {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ val req = android.location.LocationRequest.Builder(ms)+ .setQuality(android.location.LocationRequest.QUALITY_HIGH_ACCURACY)+ .setMinUpdateDistanceMeters(meters)+ .build()+ lm.requestLocationUpdates(provider, req, act.mainExecutor, gpsListener)+ } else lm.requestLocationUpdates(provider, ms, meters, gpsListener, Looper.getMainLooper())+ listening = true+ }+ }++ private fun stopGps() {+ if (!listening) return+ runCatching { (act.getSystemService(android.content.Context.LOCATION_SERVICE) as LocationManager).removeUpdates(gpsListener) }+ listening = false+ }++ private fun adaptGpsRate(fix: Location) {val now = android.os.SystemClock.elapsedRealtime()val moving = fix.hasSpeed() && fix.speed >= 1.0fif (moving) stillSince = 0L else if (stillSince == 0L) stillSince = nowval parked = !moving && stillSince != 0L && now - stillSince > 60_000Lif (parked == gpsParked) returngpsParked = parked- gps.locationUpdateMinTime = if (parked) GPS_PARKED_MS else GPS_MOVING_MS- gps.locationUpdateMinDistance = if (parked) 10f else 2f// Re-register with the new rate; the arrow stays where it is meanwhile.- if (myLocation.isMyLocationEnabled) { gps.stopLocationProvider(); gps.startLocationProvider(myLocation) }+ if (listening) { stopGps(); startGps() }}- // ---- 3D driving view ---------------------------------------------------------------------------------+ // ---- North up / heading up / 3D --------------------------------------------------------------------- private fun is3d() = tripId == null && com.rfsentinel.app.util.Prefs.map3d(act) && com.rfsentinel.app.util.Prefs.mapHeadingUp(act)-- /**- * Like a car navigation app: heading up, the map tilted back in perspective so you see further- * down the road, and your position low on the screen. The map view is made larger than the- * screen and tilted (osmdroid has no 3D of its own); taps still land on the right dot.- */- private var pinching = false- private var pinchSpan = 0f- private var pinchZoom = 0.0+ private fun is3d() = tripId == null && Prefs.map3d(act) && Prefs.mapHeadingUp(act)/**- * 3D pinch zoom. The map view is tilted, so Android hands it finger positions on the tilted- * plane: near the top a tiny finger move is a long way on the map, and osmdroid's pinch zoom- * jumps. In 3D the pinch is measured on the screen instead and zooms around your position- * (like a car navigation app); one-finger drags and taps still go to the map.+ * Points the camera for the mode: following you north up, turning with your heading, or the 3D+ * driving view (tilt and zoom from your speed, your arrow low on the screen); not following, it+ * stays where you left it.*/- /** The distance between two fingers on the screen itself (not on the tilted map). */- @androidx.annotation.RequiresApi(29)- private fun span(e: MotionEvent): Float {- if (e.pointerCount < 2) return 0f- val dx = e.getRawX(0) - e.getRawX(1); val dy = e.getRawY(0) - e.getRawY(1)- return kotlin.math.hypot(dx, dy)+ private fun applyMode(animate: Boolean) {+ val m = map?.takeIf { it.puckOn } ?: return+ val ms = if (animate) 1_000L else 0L+ if (!following || tripId != null) {+ m.follow(MapEngine.Follow.NONE, null, 0.0, null, 0)+ return+ }+ val h = binding.map.height+ val base = Prefs.mapDefaultZoom(act)+ val kmh = smoothKmh.coerceAtLeast(0f)+ if (is3d()) {+ m.follow(MapEngine.Follow.HEADING, if (h > 0) topPaddingFor(h) else null, tiltFor(kmh, Prefs.map3dTilt(act)), if (userZoom) null else zoomFor(kmh, base), ms)+ } else if (Prefs.mapHeadingUp(act)) {+ // Turning with you: pulls back at speed like the 3D view; a pinch is yours until the follow button.+ m.follow(MapEngine.Follow.HEADING, 0.0, 0.0, if (userZoom) null else zoomFor(kmh, base) - FLAT_ZOOM_OFFSET, ms)+ } else {+ m.follow(MapEngine.Follow.NORTH, 0.0, 0.0, if (userZoom) null else base - FLAT_ZOOM_OFFSET, ms)+ }}- @android.annotation.SuppressLint("ClickableViewAccessibility")- private fun setup3dPinch(map: org.osmdroid.views.MapView) {- map.setOnTouchListener { v, e ->- if (rewriting) return@setOnTouchListener false- if (android.os.Build.VERSION.SDK_INT < 29 || !is3d()) { pinching = false; return@setOnTouchListener false }- when (e.actionMasked) {- MotionEvent.ACTION_POINTER_DOWN -> if (!pinching && e.pointerCount == 2) {- // Take the gesture over: the map forgets the drag it had started.- MotionEvent.obtain(e).apply { action = MotionEvent.ACTION_CANCEL }.also { v.dispatchTouchEvent(it); it.recycle() }- pinching = true- pinchSpan = span(e)- pinchZoom = map.zoomLevelDouble- }- MotionEvent.ACTION_MOVE -> if (pinching) {- val now = span(e)- if (now > 10f && pinchSpan > 10f) {- val z = (pinchZoom + kotlin.math.ln((now / pinchSpan).toDouble()) / kotlin.math.ln(2.0))- .coerceIn(map.minZoomLevel, map.maxZoomLevel)- map.controller.setZoom(z)- autoZoom = false // your zoom now, until the follow button- }- }- MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> if (pinching) {- pinching = false- drawKnownAlprSoon()- return@setOnTouchListener true- }+ /** The map button: north up -> heading up -> 3D driving view -> north up. */+ private fun setupOrientationButton() {+ val btn = binding.orientationButton+ if (tripId != null) { btn.visibility = View.GONE; return }+ btn.setOnClickListener {+ val prefs = Prefs+ val heading = prefs.mapHeadingUp(act); val tilt = prefs.map3d(act)+ when {+ !heading -> { prefs.setMapHeadingUp(act, true); prefs.setMap3d(act, false) }+ !tilt -> prefs.setMap3d(act, true)+ else -> { prefs.setMapHeadingUp(act, false); prefs.setMap3d(act, false) }}- if (pinching) return@setOnTouchListener true- // One finger (tap, drag, long-press): hand the map the point really under the finger.- if (e.pointerCount == 1) {- val at = screenToMap(map, e.rawX, e.rawY) ?: return@setOnTouchListener false- val fixed = MotionEvent.obtain(e).apply { setLocation(at[0], at[1]) }- rewriting = true- try { v.dispatchTouchEvent(fixed) } finally { rewriting = false; fixed.recycle() }- return@setOnTouchListener true+ if (prefs.mapHeadingUp(act)) {+ // Turning with you (and 3D) only makes sense around you: follow again.+ setFollow(true, quiet = true)+ Toast.makeText(act, if (prefs.map3d(act)) "3D driving view" else "Map turns with your direction of travel", Toast.LENGTH_SHORT).show()+ } else {+ // Back to a flat, north-up map, wherever it was looking.+ map?.easeTo(bearing = 0.0, tilt = 0.0, flat = true, ms = 600)+ applyMode(animate = true)+ Toast.makeText(act, "Map fixed with north up", Toast.LENGTH_SHORT).show()}- false+ styleOrientationButton()}+ styleOrientationButton()}- private var rewriting = false-- /**- * Where a point of the screen falls on the tilted map view: the view's own 3D matrix,- * inverted. (Android's own conversion of touches through a tilted view is off, so taps- * missed the icons drawn under the finger.)- */- private fun screenToMap(map: org.osmdroid.views.MapView, rawX: Float, rawY: Float): FloatArray? {- val parent = map.parent as? View ?: return null- val inverse = android.graphics.Matrix()- if (!map.matrix.invert(inverse)) return null- val origin = IntArray(2).also { parent.getLocationOnScreen(it) }- val pts = floatArrayOf(rawX - origin[0] - map.left, rawY - origin[1] - map.top)- inverse.mapPoints(pts)- return pts+ private fun styleOrientationButton() {+ val heading = Prefs.mapHeadingUp(act)+ val tilt = is3d()+ val (accent, onAccent) = ChipStyle.accent(act)+ binding.orientationButton.setImageResource(when {+ tilt -> com.rfsentinel.app.R.drawable.ic_view_3d+ heading -> com.rfsentinel.app.R.drawable.ic_heading_up+ else -> com.rfsentinel.app.R.drawable.ic_north_up+ })+ binding.orientationButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (heading) accent else 0xFFFFFFFF.toInt())+ binding.orientationButton.imageTintList = android.content.res.ColorStateList.valueOf(if (heading) onAccent else 0xFF0B5C63.toInt())+ binding.orientationButton.contentDescription = when {+ tilt -> "Map: 3D driving view (tap for north up)"+ heading -> "Map: heading up (tap for the 3D driving view)"+ else -> "Map: north up (tap to turn with your direction)"+ }}- /**- * The tilted map view's size for a [w] x [h] map area, and the centre offset that puts your- * position a quarter of the way up: asks the view's own 3D matrix (with the tilt and camera- * already set) where its points land, so nothing depends on screen size or density.- * Returns width, height, centre offset (px).- */- private fun tiltFit(m: org.osmdroid.views.MapView, w: Int, h: Int): IntArray {- val pt = FloatArray(2)- // Pivot on the bottom-centre; x measured from the centre line.- fun project(height: Float, x: Float, y: Float): FloatArray {- m.pivotX = 0f; m.pivotY = height- pt[0] = x; pt[1] = y- m.matrix.mapPoints(pt)- return pt+ /** Turns following on (re-centres now and keeps you centred) or off (after you pan). */+ private fun setFollow(on: Boolean, quiet: Boolean = false) {+ following = on+ if (on) {+ userZoom = false+ if (map?.puckOn != true && !quiet) Toast.makeText(act, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()+ else if (lastFix == null && ScanForegroundService.lastFix == null && !quiet) Toast.makeText(act, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()}- // Where the top edge lands on screen (from the map area's top) for a view this tall.- fun topOnScreen(height: Float) = (h - height) + project(height, 0f, 0f)[1]- // Smallest height whose top edge reaches the top (the edge only rises as the view grows).- var lo = h.toFloat(); var hi = h * TILT_MAX_HEIGHT- if (topOnScreen(hi) <= 0f) repeat(24) { val mid = (lo + hi) / 2; if (topOnScreen(mid) <= 0f) hi = mid else lo = mid }- val height = hi + h * 0.01f- // How much the far edge shrinks: the view must be this much wider than the area.- val shrink = project(height, 1000f, 0f)[0] / 1000f- val width = (w / shrink.coerceIn(0.2f, 1f)) * 1.02f- // Your position: the point of the view that lands 3/4 of the way down the map area.- val target = h * 0.75f- var a = 0f; var bb = height- repeat(24) { val mid = (a + bb) / 2; if ((h - height) + project(height, 0f, mid)[1] < target) a = mid else bb = mid }- return intArrayOf(width.toInt(), height.toInt(), (a - height / 2f).toInt())+ applyMode(animate = true)+ styleFollowButton()}- // ---- 3D: navigation zoom and arrow --------------------------------------------------------------- /**- * What the position arrow is drawn from. Heading up / 3D: below walking-to-crawling speed the- * GPS direction is noise, and the map (rightly) stops turning - so the arrow drops it too and- * stays pointing up, the way you were last going, instead of swinging sideways. Moving, the- * arrow follows the GPS course, which is also what turns the map: it points straight up the road.- */- private fun arrowFix(fix: android.location.Location?): android.location.Location? {- if (fix == null || !fix.hasBearing() || !alive || tripId != null || !com.rfsentinel.app.util.Prefs.mapHeadingUp(act)) return fix- if (fix.hasSpeed() && fix.speed >= HEADING_MIN_SPEED_MS) return fix- return android.location.Location(fix).apply {- @Suppress("DEPRECATION") removeBearing()- }+ /** Filled with the theme highlight while following, plain otherwise. */+ private fun styleFollowButton() {+ val on = following+ val (accent, onAccent) = ChipStyle.accent(act)+ val plain = 0xFFFFFFFF.toInt()+ binding.centerButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (on) accent else plain)+ binding.centerButton.imageTintList = android.content.res.ColorStateList.valueOf(if (on) onAccent else 0xFF0B5C63.toInt())+ binding.centerButton.contentDescription = if (on) "Following your position" else "Follow my position"}- /** Street-level zoom from your speed while following you in 3D; off once you pinch, back with the follow button. */- private var autoZoom = true- private var smoothKmh = -1f- private var defaultPerson: android.graphics.Bitmap? = null- private var defaultArrow: android.graphics.Bitmap? = null- private val navArrow by lazy { navArrowIcon(resources.displayMetrics.density) }+ /** A saved trace: glides to where you are (the map doesn't follow you there). */+ private fun centerOnMe() {+ val p = myPosition() ?: TripRecorder.livePoints().lastOrNull()?.let { it.lat to it.lon }+ if (p != null) map?.easeTo(p.first, p.second, ms = 600)+ else Toast.makeText(act, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()+ }- /** In 3D the zoom levels are shifted (screen-density tiles): the flat map's level minus this. */- private fun tileShift() = kotlin.math.ln(resources.displayMetrics.density.toDouble()) / kotlin.math.ln(2.0)+ /** The best position known before this screen's own GPS answers: the running scan's fix, else the system's last known. */+ private fun knownFix(): Location? = listOfNotNull(ScanForegroundService.lastFix, systemLastKnown()).maxByOrNull { it.time }- /**- * Like a car navigation app: close street level in town, gradually wider on faster roads- * (flat-map zoom 18 up to 30 km/h, down to 16 from 110 km/h), eased in so it doesn't pump.- */- private fun autoZoomFor(fix: android.location.Location, now: Boolean = false) {- val m = _binding?.map ?: return- if (!is3d() || !autoZoom || !following || pinching) return- val kmh = if (fix.hasSpeed()) fix.speed * 3.6f else 0f- smoothKmh = if (smoothKmh < 0f || now) kmh else smoothKmh * 0.7f + kmh * 0.3f- val flat = when {- smoothKmh <= 30f -> 18.0- smoothKmh >= 110f -> 16.0- else -> 18.0 - (smoothKmh - 30f) / 80f * 2.0- }- val target = (flat - tileShift()).coerceIn(m.minZoomLevel, m.maxZoomLevel)- if (kotlin.math.abs(target - m.zoomLevelDouble) < 0.15) return- if (now) m.controller.setZoom(target)- else if (!m.isAnimating) m.controller.zoomTo(target, 900L)+ @SuppressLint("MissingPermission")+ private fun systemLastKnown(): Location? {+ if (!Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION) &&+ !Permissions.granted(act, android.Manifest.permission.ACCESS_COARSE_LOCATION)) return null+ val manager = act.getSystemService(android.content.Context.LOCATION_SERVICE) as? LocationManager ?: return null+ return runCatching {+ manager.getProviders(true).mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }.maxByOrNull { it.time }+ }.getOrNull()}- /** Heading up and 3D: a blue navigation arrow for your position (pointing the way you go); north up: osmdroid's own icons. */- private fun styleMyLocation(on: Boolean) {- if (!::myLocation.isInitialized) return- if (on) {- myLocation.setDirectionIcon(navArrow); myLocation.setPersonIcon(navArrow)- myLocation.setDirectionAnchor(0.5f, 0.5f); myLocation.setPersonAnchor(0.5f, 0.5f)- } else {- defaultArrow?.let { myLocation.setDirectionIcon(it); myLocation.setDirectionAnchor(0.5f, 0.5f) }- // osmdroid's person is anchored near its feet.- defaultPerson?.let { myLocation.setPersonIcon(it); myLocation.setPersonAnchor(0.5f, 0.8125f) }- }+ /** Remembers where the live map is looking, so it can open there next time. */+ private fun saveView() {+ if (tripId != null || args.containsKey(EXTRA_CENTER_LAT) || args.containsKey(EXTRA_AIRCRAFT) || args.containsKey(EXTRA_WAZE)) return+ val cam = map?.camera ?: return+ if (kotlin.math.abs(cam.lat) < 1e-4 && kotlin.math.abs(cam.lon) < 1e-4) return // it never looked anywhere+ if (startedOnWorld) return+ Prefs.saveMapView(act, cam.lat, cam.lon, MapStart.savedZoom(cam.zoom))}- private fun navArrowIcon(dp: Float): android.graphics.Bitmap {- val size = (46 * dp).toInt()- val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)- val c = android.graphics.Canvas(bmp)- val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)- val r = size / 2f- // Soft white disc behind, like the navigation apps' puck.- c.drawCircle(r, r, r - 1 * dp, paint.apply { color = 0xE6FFFFFF.toInt(); style = android.graphics.Paint.Style.FILL; setShadowLayer(3 * dp, 0f, 1 * dp, 0x55000000) })- paint.clearShadowLayer()- val path = android.graphics.Path().apply {- moveTo(r, 7 * dp); lineTo(size - 11 * dp, size - 10 * dp)- lineTo(r, size - 16 * dp); lineTo(11 * dp, size - 10 * dp); close()- }- c.drawPath(path, paint.apply { color = 0xFF1A73E8.toInt(); style = android.graphics.Paint.Style.FILL })- c.drawPath(path, paint.apply { color = 0xFFFFFFFF.toInt(); style = android.graphics.Paint.Style.STROKE; strokeWidth = 1.5f * dp; strokeJoin = android.graphics.Paint.Join.ROUND })- return bmp- }+ // ---- Lifecycle (the map engine needs every step) ------------------------------------------------- private fun apply3d() {- val b = _binding ?: return- val w = b.root.width; val h = b.root.height- if (w == 0 || h == 0) return- val m = b.map- val on = is3d()- // The tilted view is several screens' worth of map: drawn with screen-density tiles it needs- // ~7x fewer of them (smooth zooming, readable street names). The zoom level is shifted so- // switching in or out of 3D keeps the same scale.- if (m.isTilesScaledToDpi != on) {- val shift = kotlin.math.ln(resources.displayMetrics.density.toDouble()) / kotlin.math.ln(2.0)- val zoom = m.zoomLevelDouble + if (on) -shift else shift- m.isTilesScaledToDpi = on- m.controller.setZoom(zoom.coerceIn(m.minZoomLevel, m.maxZoomLevel))- }- m.cameraDistance = TILT_CAMERA * h- m.rotationX = if (on) TILT_DEGREES else 0f- val lp = m.layoutParams as android.widget.FrameLayout.LayoutParams- var mw = w; var mh = h; var offsetY = 0- if (on) {- // Exact size, from the tilt itself: just tall enough that the far edge reaches the top of- // the map area, just wide enough there to cover its width (no black corners at any size).- val fit = tiltFit(m, w, h)- mw = fit[0]; mh = fit[1]; offsetY = fit[2]- }- val wantW = if (on) mw else android.widget.FrameLayout.LayoutParams.MATCH_PARENT- val wantH = if (on) mh else android.widget.FrameLayout.LayoutParams.MATCH_PARENT- if (lp.width != wantW || lp.height != wantH) {- lp.width = wantW; lp.height = wantH- lp.gravity = if (on) android.view.Gravity.BOTTOM or android.view.Gravity.CENTER_HORIZONTAL else android.view.Gravity.NO_GRAVITY- m.layoutParams = lp- }- m.pivotX = mw / 2f- m.pivotY = mh.toFloat()- m.setMapCenterOffset(0, offsetY)- scaleBar.isEnabled = !on- b.osmCredit.visibility = if (on) View.VISIBLE else View.GONE- // The navigation arrow whenever the map turns with you (heading up and 3D).- styleMyLocation(tripId == null && com.rfsentinel.app.util.Prefs.mapHeadingUp(act))- if (on) lastFixForHeading?.let { autoZoomFor(it, now = true) }- m.invalidate()- }+ override fun onStart() { super.onStart(); engine?.onStart() }override fun onResume() {super.onResume()- binding.map.onResume()- applyTiles()- // The location overlay's GPS runs only while the map is on screen.- if (Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION)) {- myLocation.enableMyLocation()- if (following) myLocation.enableFollowLocation()- }+ engine?.onResume()+ swapEngineIfChanged()+ startGps()// Precise GPS while the map is on screen, so devices land where they were heard.if (tripId == null) ScanForegroundService.mapShown(act)+ com.rfsentinel.app.alpr.CctvStore.onChanged = { activity?.runOnUiThread { if (alive) rf?.safe("static") { rf?.maybeRedrawStatic(force = true); renderLive() } } }// Back from Settings > Map: show what's switched on now (and nothing that was switched off).- drawTowers()- drawKnownAlpr()- if (com.rfsentinel.app.util.Prefs.showCctv(act)) viewLifecycleOwner.lifecycleScope.launch {+ if (Prefs.showCctv(act)) viewLifecycleOwner.lifecycleScope.launch {kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.rfsentinel.app.alpr.CctvStore.load(act) }- drawCctv()- maybeDownloadCctv()- } else drawCctv()+ rf?.safe("static") { rf?.maybeRedrawStatic(force = true) }+ } else rf?.safe("static") { rf?.maybeRedrawStatic(force = true) }+ if (rf != null && rf?.isDark != darkTiles()) loadStyle()+ styleOrientationButton()+ applyMode(animate = false)}override fun onPause() {saveView()+ stopGps()if (tripId == null) ScanForegroundService.mapHidden(act)- myLocation.disableMyLocation()- binding.map.onPause()+ engine?.onPause()super.onPause()}+ override fun onStop() { engine?.onStop(); super.onStop() }++ override fun onLowMemory() { super.onLowMemory(); engine?.onLowMemory() }++ override fun onSaveInstanceState(outState: Bundle) {+ super.onSaveInstanceState(outState)+ engine?.onSaveInstanceState(outState)+ }+override fun onDestroyView() {stopObservingBulk?.invoke()com.rfsentinel.app.alpr.CctvStore.onChanged = null- myLocation.disableMyLocation()- binding.map.removeCallbacks(autoDownloadCameras)- binding.map.removeCallbacks(redrawKnownAlpr)- // These two were left pending: one firing after onDetach() below touches detached overlays and crashes.- binding.map.removeCallbacks(redrawCctv)- binding.map.removeCallbacks(downloadCctv)- binding.map.onDetach()+ stopGps()+ rf = null+ engine?.onDestroy()+ engine = null_binding = nullsuper.onDestroyView()}+ // ---- Filter chips ---------------------------------------------------------------------------------+private fun setupFilterChips() {if (embedded) {binding.mapFilterScroll.visibility = View.GONE@@ -711,7 +692,7 @@ class MapFragment : Fragment() {return}val options = if (tripId == null) DeviceFilter.entries.filter { it != DeviceFilter.RADIO } else listOf(DeviceFilter.ALL, DeviceFilter.FLAGGED)- filter = DeviceFilter.parse(com.rfsentinel.app.util.Prefs.mapFilter(act)).takeIf { it in options } ?: DeviceFilter.ALL+ filter = DeviceFilter.parse(Prefs.mapFilter(act)).takeIf { it in options } ?: DeviceFilter.ALLval group = binding.mapFilterChipsfor (f in options) {val chip = com.google.android.material.chip.Chip(act, null, com.google.android.material.R.attr.chipStyle).apply {@@ -728,9 +709,10 @@ class MapFragment : Fragment() {group.setOnCheckedStateChangeListener { _, ids ->val picked = filterChips.entries.firstOrNull { it.value.id == ids.firstOrNull() }?.key ?: return@setOnCheckedStateChangeListenerfilter = picked- com.rfsentinel.app.util.Prefs.setMapFilter(act, picked.name)+ rf?.filter = picked+ Prefs.setMapFilter(act, picked.name)if (tripId != null) loadTrip() else renderLive()- drawTowers()+ rf?.safe("static") { rf?.maybeRedrawStatic(force = true) }}}@@ -739,147 +721,18 @@ class MapFragment : Fragment() {val placed = devices.filter { it.place != null }for ((f, chip) in filterChips) {val n = when (f) {- DeviceFilter.CELLS -> towerCount- DeviceFilter.WAZE -> currentWaze().size+ DeviceFilter.CELLS -> rf?.towerCount ?: 0+ DeviceFilter.WAZE -> com.rfsentinel.app.online.WazePolice.latest.sizeelse -> placed.count { f.matches(it) }}chip.text = if (f == DeviceFilter.ALL || n > 0) "${f.label} $n" else f.label}}- // ---- North up / heading up -------------------------------------------------------------------- /** The map button: north up (fixed) or heading up (turns with your direction of travel). */- private fun setupOrientationButton() {- val btn = binding.orientationButton- if (tripId != null) { btn.visibility = View.GONE; return }- btn.setOnClickListener {- // North up -> heading up -> 3D driving view -> north up.- val prefs = com.rfsentinel.app.util.Prefs- val heading = prefs.mapHeadingUp(act); val tilt = prefs.map3d(act)- when {- !heading -> { prefs.setMapHeadingUp(act, true); prefs.setMap3d(act, false) }- !tilt -> prefs.setMap3d(act, true)- else -> { prefs.setMapHeadingUp(act, false); prefs.setMap3d(act, false) }- }- if (prefs.mapHeadingUp(act)) {- lastFixForHeading?.let { turnToHeading(it, force = true) }- // 3D only makes sense around you: follow again.- if (prefs.map3d(act)) setFollow(true, quiet = true)- Toast.makeText(act, if (prefs.map3d(act)) "3D driving view" else "Map turns with your direction of travel", Toast.LENGTH_SHORT).show()- } else {- binding.map.mapOrientation = 0f- Toast.makeText(act, "Map fixed with north up", Toast.LENGTH_SHORT).show()- }- apply3d()- styleOrientationButton()- }- styleOrientationButton()- if (!com.rfsentinel.app.util.Prefs.mapHeadingUp(act)) binding.map.mapOrientation = 0f- }-- private fun styleOrientationButton() {- val heading = com.rfsentinel.app.util.Prefs.mapHeadingUp(act)- val tilt = is3d()- val (accent, onAccent) = ChipStyle.accent(act)- binding.orientationButton.setImageResource(when {- tilt -> com.rfsentinel.app.R.drawable.ic_view_3d- heading -> com.rfsentinel.app.R.drawable.ic_heading_up- else -> com.rfsentinel.app.R.drawable.ic_north_up- })- binding.orientationButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (heading) accent else 0xFFFFFFFF.toInt())- binding.orientationButton.imageTintList = android.content.res.ColorStateList.valueOf(if (heading) onAccent else 0xFF0B5C63.toInt())- binding.orientationButton.contentDescription = when {- tilt -> "Map: 3D driving view (tap for north up)"- heading -> "Map: heading up (tap for the 3D driving view)"- else -> "Map: north up (tap to turn with your direction)"- }- }-- private var lastFixForHeading: android.location.Location? = null-- /**- * Heading up: the direction of travel points to the top of the screen. Only from the GPS- * course while moving (above ~5 km/h) - stopped, the bearing is noise, so the map keeps its angle.- */- private fun turnToHeading(fix: android.location.Location, force: Boolean = false) {- lastFixForHeading = fix- if (tripId != null || !com.rfsentinel.app.util.Prefs.mapHeadingUp(act)) return- if (!fix.hasBearing() || (!force && (!fix.hasSpeed() || fix.speed < HEADING_MIN_SPEED_MS))) return- val target = -fix.bearing- // Small wobbles at speed aren't worth a redraw.- val diff = ((target - binding.map.mapOrientation + 540f) % 360f) - 180f- if (!force && kotlin.math.abs(diff) < 3f) return- binding.map.mapOrientation = (target + 360f) % 360f- }-- /** Turns following on (re-centres now and keeps you centred) or off (after you pan). */- private fun setFollow(on: Boolean, quiet: Boolean = false) {- following = on- if (on) {- myLocation.enableFollowLocation()- centerOnMe(quiet)- autoZoom = true- lastFixForHeading?.let { autoZoomFor(it, now = true) }- } else {- myLocation.disableFollowLocation()- }- styleFollowButton()- }-- /** Filled with the theme highlight while following, plain otherwise. */- private fun styleFollowButton() {- val on = following- val (accent, onAccent) = ChipStyle.accent(act)- val plain = 0xFFFFFFFF.toInt()- binding.centerButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (on) accent else plain)- binding.centerButton.imageTintList = android.content.res.ColorStateList.valueOf(if (on) onAccent else 0xFF0B5C63.toInt())- binding.centerButton.contentDescription = if (on) "Following your position" else "Follow my position"- }-- private fun centerOnMe(quiet: Boolean = false) {- val fix = myLocation.myLocation- ?: TripRecorder.livePoints().lastOrNull()?.let { GeoPoint(it.lat, it.lon) }- if (fix != null) goTo(fix)- else if (!quiet) Toast.makeText(act, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()- }-- /** Glides to a nearby place; jumps when it is far (an old position, or the first fix after a long trip). */- private fun goTo(p: GeoPoint) {- val map = binding.map- val here = map.mapCenter- val far = !map.isLayoutOccurred ||- DeviceRegistry.metersBetween(here.latitude, here.longitude, p.latitude, p.longitude) > 3_000- if (far) map.controller.setCenter(p) else map.controller.animateTo(p)- }-- /** The best position known before this screen's own GPS answers: the running scan's fix, else the system's last known. */- private fun knownFix(): android.location.Location? =- listOfNotNull(ScanForegroundService.lastFix, systemLastKnown()).maxByOrNull { it.time }-- @android.annotation.SuppressLint("MissingPermission")- private fun systemLastKnown(): android.location.Location? {- if (!Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION) &&- !Permissions.granted(act, android.Manifest.permission.ACCESS_COARSE_LOCATION)) return null- val manager = act.getSystemService(android.content.Context.LOCATION_SERVICE) as? android.location.LocationManager ?: return null- return runCatching {- manager.getProviders(true).mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }.maxByOrNull { it.time }- }.getOrNull()- }-- /** Remembers where the live map is looking, so it can open there next time. */- private fun saveView() {- if (tripId != null || args.containsKey(EXTRA_CENTER_LAT)) return- val c = binding.map.mapCenter- if (kotlin.math.abs(c.latitude) < 1e-4 && kotlin.math.abs(c.longitude) < 1e-4) return // it never looked anywhere- // In 3D the zoom level is shifted (bigger tiles, see apply3d): save the flat map's equivalent.- val shift = if (binding.map.isTilesScaledToDpi) kotlin.math.ln(resources.displayMetrics.density.toDouble()) / kotlin.math.ln(2.0) else 0.0- com.rfsentinel.app.util.Prefs.saveMapView(act, c.latitude, c.longitude, binding.map.zoomLevelDouble + shift)- }-// ---- Live mode ----------------------------------------------------------------private fun renderLive() {+ if (!alive || tripId != null) returnval recording = TripRecorder.isRecordingbinding.recordButton.text = if (recording) "Stop recording" else "Record trace"val (accent, onAccent) = ChipStyle.accent(act)@@ -893,47 +746,11 @@ class MapFragment : Fragment() {binding.recordFab.setImageResource(if (recording) com.rfsentinel.app.R.drawable.ic_car_stop else com.rfsentinel.app.R.drawable.ic_record)binding.recordFab.contentDescription = if (recording) "Stop recording" else "Record trace"- // Only the trace being recorded right now; a stopped one is under Traces.- trace.setPoints(if (recording) TripRecorder.livePoints().map { GeoPoint(it.lat, it.lon) } else emptyList())-// Includes devices from a scan that just stopped: the registry drops them after 3 minutes.val devices = DeviceRegistry.snapshot()- val drawn = devices.mapNotNull { s ->- val pos = s.place ?: return@mapNotNull null- val flagged = DeviceColors.isFlagged(s)- val located = s.located?.takeIf { flagged && s.broadcast == null }- if (!filter.matches(s) || filter == DeviceFilter.RADIO) return@mapNotNull null- val best = s.best- Pin(- s.mac, pos.lat, pos.lon,- best?.label ?: s.name ?: s.deviceType,- flagged,- DeviceColors.forDevice(act, s),- buildString {- append(s.mac)- s.vendor?.let { append("\n").append(it) }- if (best != null) append("\n${best.category.title} · ${best.tier.label} ${best.confidence}%\n${best.evidence}")- if (located != null) append("\nPinpointed ${com.rfsentinel.app.detect.Locator.describe(located)}")- append("\nStrongest signal: ${s.bestRssi} dBm")- },- radiusM = located?.radiusM,- whereNote = if (s.broadcast != null)- "Position = the vehicle's own GPS, broadcast over V2X (exact, not an estimate)."- else if (located != null)- "Position = pinpointed from the signal at the many spots you passed: very likely inside the circle " +- "(${located.radiusM.toInt()} m). The more sides you pass it from, the smaller the circle."- else if (flagged)- "Position = where your phone was when this device's signal was strongest (approximate). " +- "Drive or walk past it from another side - around the block - to pinpoint it."- else "Position = where your phone was when this device's signal was strongest (approximate)."- )- }- drawPins(drawn)- drawPrecision(drawn)+ var drawn = emptyList<MapPin>()+ rf?.let { r -> r.safe("live") { drawn = r.drawLive(devices) } }updateFilterCounts(devices)- drawDrones(devices.filter { it.remoteId?.hasPosition == true })- drawAircraft()- drawWaze()val positioned = devices.count { it.place != null }val status = when {@@ -953,11 +770,10 @@ class MapFragment : Fragment() {embedded -> nullelse -> "Scanning · ${drawn.size} on map" + if (filter != DeviceFilter.ALL) " (${filter.label} only)" else ""}- val text = listOfNotNull(status, cctvLine).joinToString("\n")+ val text = listOfNotNull(status, rf?.cctvLine).joinToString("\n")binding.statusText.text = textbinding.statusText.visibility = if (text.isEmpty()) View.GONE else View.VISIBLEbinding.statusText.background.mutate().setTint(if (recording) 0xFFB3261E.toInt() else 0xCC0B5C63.toInt())- binding.map.invalidate()}private fun toggleRecording() {@@ -1020,10 +836,14 @@ class MapFragment : Fragment() {val dao = AppDatabase.getInstance(act).tripDao()val t = dao.get(id) ?: run { act.finish(); return@launch }trip = t- val points = dao.points(id).map { GeoPoint(it.lat, it.lon) }+ val points = dao.points(id).map { it.lat to it.lon }val devices = dao.devices(id)- trace.setPoints(points)- drawPins(devices.filter { it.lat != null && (it.flagged || filter == DeviceFilter.ALL) }.map { it.toPin() })+ if (!alive) return@launch+ val r = rf+ r?.safe("trip") {+ r.drawTrace(points, RfMap.PAST_TRACE_COLOR)+ r.drawPins(devices.filter { it.lat != null && (it.flagged || filter == DeviceFilter.ALL) }.map { it.toPin() })+ }val mins = ((t.endTime ?: System.currentTimeMillis()) - t.startTime) / 60000binding.statusText.text = String.format(Locale.US, "%s\n%s · %d:%02d · %.2f km · %s (%d flagged)",@@ -1031,20 +851,24 @@ class MapFragment : Fragment() {devicesLabel(t.deviceCount), t.flaggedCount)binding.statusText.background.mutate().setTint(0xCC1F5FBF.toInt())- val all = points + devices.filter { it.lat != null }.map { GeoPoint(it.lat!!, it.lon!!) }- if (all.isNotEmpty()) {+ val all = points + devices.filter { it.lat != null }.map { it.lat!! to it.lon!! }+ val m = map+ if (all.isNotEmpty() && m != null && !centeredOnce) {+ centeredOnce = truebinding.map.post {- if (all.size == 1) binding.map.controller.setCenter(all[0])- else binding.map.zoomToBoundingBox(BoundingBox.fromGeoPoints(all).increaseByScale(1.3f), false)+ if (!alive) return@post+ r?.safe("frame") {+ if (all.size == 1) m.jumpTo(all[0].first, all[0].second, MapStart.DEFAULT_ZOOM - ZOOM_SHIFT)+ else m.fit(all, (48 * resources.displayMetrics.density).toInt())+ }}}- binding.map.invalidate()}}- private fun TripDeviceEntity.toPin(): Pin {+ private fun TripDeviceEntity.toPin(): MapPin {val cat = Category.parse(category)- return Pin(+ return MapPin(mac, lat!!, lon!!, label, flagged,DeviceColors.forMatch(act, if (flagged) cat else null, confidence),buildString {@@ -1059,510 +883,7 @@ class MapFragment : Fragment() {)}- // ---- Drawing ------------------------------------------------------------------------ /**- * Each device sits exactly where it was heard best. Devices heard from the same- * spot overlap; tapping there lists them all.- */- /** The circle each pinpointed device is very likely in, in its colour. Taps go through to the dots. */- private fun drawPrecision(list: List<Pin>) {- val circles = list.filter { it.radiusM != null }- if (circles.isEmpty() && precision.items.isEmpty()) return- precision.items.clear()- val density = resources.displayMetrics.density- for (p in circles) {- precision.add(Polygon(binding.map).apply {- points = Polygon.pointsAsCircle(GeoPoint(p.lat, p.lon), p.radiusM!!)- fillPaint.color = (p.color and 0x00FFFFFF) or 0x2E000000- outlinePaint.color = (p.color and 0x00FFFFFF) or 0xB4000000.toInt()- outlinePaint.strokeWidth = 1.5f * density- setOnClickListener { _, _, _ -> false }- infoWindow = null- })- }- binding.map.invalidate()- }-- private fun drawPins(list: List<Pin>) {- // Ordinary devices first so flagged ones are drawn on top.- pins.points = list.sortedBy { it.flagged }.map { p ->- PointsOverlay.Point(p.lat, p.lon, p, color = p.color, sizeDp = if (p.flagged) 24f else 16f)- }- }-- /**- * Drones place themselves: Remote ID broadcasts the aircraft's own GPS fix- * (and usually the operator's / take-off point), so these markers are real- * positions, unlike RSSI-based device pins.- */- private fun drawDrones(list: List<DeviceRegistry.Snapshot>) {- drones.items.clear()- val dp = resources.displayMetrics.density- for (s in list) {- val r = s.remoteId ?: continue- val aircraft = GeoPoint(r.latitude!!, r.longitude!!)- val details = droneDetails(s, r)- if (r.hasOperatorPosition) {- val operator = GeoPoint(r.operatorLatitude!!, r.operatorLongitude!!)- drones.add(Polyline().apply {- setPoints(listOf(operator, aircraft))- outlinePaint.apply {- color = DRONE_COLOR- strokeWidth = 2.5f * dp- pathEffect = android.graphics.DashPathEffect(floatArrayOf(10 * dp, 6 * dp), 0f)- }- })- drones.add(Marker(binding.map).apply {- position = operator- icon = GradientDrawable().apply {- shape = GradientDrawable.RECTANGLE- setColor(0xFFF5E100.toInt())- setStroke((2 * dp).toInt(), DRONE_COLOR)- setSize((14 * dp).toInt(), (14 * dp).toInt())- }- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = "Drone operator / take-off point"- setOnMarkerClickListener { _, _ -> showDrone(s, "Operator of this drone (or its take-off point)\n\n$details"); true }- })- }- drones.add(Marker(binding.map).apply {- position = aircraft- icon = android.graphics.drawable.BitmapDrawable(resources, droneArrow(dp))- rotation = -(r.directionDeg ?: 0).toFloat() // osmdroid rotates counter-clockwise- isFlat = true- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = "Drone"- setOnMarkerClickListener { _, _ -> showDrone(s, details); true }- })- }- }-- /** The Waze reports from the checker, which clears them when it stops. */- private fun currentWaze(): List<com.rfsentinel.app.online.WazePolice.Shown> = com.rfsentinel.app.online.WazePolice.latest-- /**- * Waze reports as coloured dots (blue police, red accident, orange hazard, brown closure,- * purple jam) with a white outline. Tap one for what it is, how far, how old, how many confirmed.- */- private fun drawWaze() {- wazeLayer.items.clear()- val show = tripId == null && (filter == DeviceFilter.ALL || filter == DeviceFilter.WAZE)- if (show) {- val dp = resources.displayMetrics.density- for (w in currentWaze()) {- wazeLayer.add(Marker(binding.map).apply {- position = GeoPoint(w.report.lat, w.report.lon)- icon = GradientDrawable().apply {- shape = GradientDrawable.OVAL- setColor(w.report.type.color)- setStroke((2 * dp).toInt(), android.graphics.Color.WHITE)- setSize((20 * dp).toInt(), (20 * dp).toInt())- }- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = w.hit.label- setOnMarkerClickListener { _, _ -> showWaze(w); true }- })- }- }- binding.map.invalidate()- }-- private fun showWaze(w: com.rfsentinel.app.online.WazePolice.Shown) {- AlertDialog.Builder(act)- .setTitle(w.hit.label)- .setMessage("${w.hit.tier.label} ${w.hit.confidence}%\n${com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend)}\n${w.hit.evidence}")- .setNegativeButton("Close", null)- .show()- }-- /**- * Aircraft from the latest ADS-B poll: police / government / circling ones in bold- * purple with their agency and altitude, every other aircraft small and grey, each- * pointing along its track. Tap one for its details.- */- private fun drawAircraft() {- aircraft.items.clear()- binding.map.invalidate()- val list = com.rfsentinel.app.online.PoliceAircraft.latest- if (list.isEmpty() || System.currentTimeMillis() - com.rfsentinel.app.online.PoliceAircraft.latestAt > 3 * 60_000L) return- val dp = resources.displayMetrics.density- // Sized to the zoom: 0.5x at a city-wide view (zoom 10), 1x at zoom 13, 2.2x at street level (17+).- val scale = (0.5 + (binding.map.zoomLevelDouble - 10.0) * (1.7 / 7.0)).coerceIn(0.5, 2.2).toFloat()- val icons = HashMap<Boolean, android.graphics.drawable.BitmapDrawable>()- // Ordinary traffic first, so flagged aircraft are drawn on top.- for ((p, hit) in list.sortedBy { it.hit != null }) {- val flagged = hit != null- val at = GeoPoint(p.lat, p.lon)- aircraft.add(Marker(binding.map).apply {- position = at- icon = icons.getOrPut(flagged) { android.graphics.drawable.BitmapDrawable(resources, MapIcons.planeIcon(dp, flagged, scale)) }- rotation = -(p.trackDeg ?: 0.0).toFloat() // osmdroid rotates counter-clockwise- isFlat = true- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- setOnMarkerClickListener { _, _ -> showAircraft(p, hit); true }- })- if (flagged) {- val label = listOfNotNull(- hit!!.label.substringAfter(": ", hit.label).take(28),- p.altitudeFt?.takeIf { it > 0 }?.let { "$it ft" }- ).joinToString(" · ")- aircraft.add(Marker(binding.map).apply {- position = at- icon = android.graphics.drawable.BitmapDrawable(resources, aircraftLabel(dp, label))- setAnchor(Marker.ANCHOR_CENTER, -0.9f) // just below the plane, never rotated- setOnMarkerClickListener { _, _ -> showAircraft(p, hit); true }- })- }- }- }-- private fun aircraftLabel(dp: Float, text: String): android.graphics.Bitmap {- val p = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {- textSize = 11 * dp- color = android.graphics.Color.WHITE- typeface = android.graphics.Typeface.DEFAULT_BOLD- }- val pad = 4 * dp- val w = (p.measureText(text) + 2 * pad).toInt()- val h = (p.textSize + 2 * pad).toInt()- val bmp = android.graphics.Bitmap.createBitmap(w, h, android.graphics.Bitmap.Config.ARGB_8888)- val c = android.graphics.Canvas(bmp)- val bg = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = MapIcons.POLICE_AIRCRAFT_COLOR }- c.drawRoundRect(android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat()), 4 * dp, 4 * dp, bg)- c.drawText(text, pad, h - pad - p.descent() / 2, p)- return bmp- }-- private fun showAircraft(p: com.rfsentinel.app.online.PoliceAircraft.Plane, hit: com.rfsentinel.app.detect.Hit?) {- val me = myLocation.myLocation- val text = buildString {- hit?.let { append(it.evidence).append("\n\n") }- p.registration?.let { append("Registration: $it\n") }- p.callsign?.let { append("Callsign: $it\n") }- p.type?.let { append("Type: $it\n") }- p.owner?.let { append("Owner / operator: $it\n") }- p.altitudeFt?.let { append(if (it <= 0) "On the ground\n" else "Altitude: $it ft\n") }- p.speedKt?.let { append(String.format(Locale.US, "Speed: %.0f kt (%.0f km/h)\n", it, it * 1.852)) }- p.trackDeg?.let { append(String.format(Locale.US, "Heading: %.0f°\n", it)) }- me?.let { append(String.format(Locale.US, "Distance: %.1f km\n",- DeviceRegistry.metersBetween(it.latitude, it.longitude, p.lat, p.lon) / 1000)) }- append("ICAO address: ${p.hex.uppercase()}\nSource: community ADS-B (adsb.fi / adsb.lol)")- }- AlertDialog.Builder(act)- .setTitle(hit?.label ?: (p.registration ?: p.callsign ?: "Aircraft"))- .setMessage(text)- .setPositiveButton("OK", null)- .show()- }-- private fun droneDetails(s: DeviceRegistry.Snapshot, r: com.rfsentinel.app.detect.RemoteId.Info) = buildString {- r.uasId?.let { append("ID: $it\n") }- r.uaType?.let { append("Type: $it\n") }- r.status?.let { append("Status: $it\n") }- r.heightM?.let { append(String.format(Locale.US, "Height: %.0f m\n", it)) }- r.altitudeGeoM?.let { append(String.format(Locale.US, "Altitude (GPS): %.0f m\n", it)) }- r.speedMs?.let { append(String.format(Locale.US, "Speed: %.0f km/h\n", it * 3.6)) }- r.directionDeg?.let { append("Heading: $it°\n") }- r.operatorId?.let { append("Operator ID: $it\n") }- r.selfIdDescription?.let { append("Description: $it\n") }- append("Radio: ${s.mac} · ${s.rssi} dBm")- }-- private fun showDrone(s: DeviceRegistry.Snapshot, text: String) {- AlertDialog.Builder(act)- .setTitle("Drone (Remote ID)")- .setMessage(text + "\n\nPositions are broadcast by the drone itself (ASTM F3411 Remote ID).")- .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(act, s.mac) }- .setNegativeButton("Close", null)- .show()- }-- /** A blue arrow pointing north; the marker rotation turns it to the drone's heading. */- private fun droneArrow(dp: Float): android.graphics.Bitmap {- val size = (30 * dp).toInt()- val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)- val c = android.graphics.Canvas(bmp)- val path = android.graphics.Path().apply {- moveTo(size / 2f, 2 * dp); lineTo(size - 5 * dp, size - 4 * dp)- lineTo(size / 2f, size * 0.68f); lineTo(5 * dp, size - 4 * dp); close()- }- val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)- c.drawPath(path, paint.apply { color = DRONE_COLOR; style = android.graphics.Paint.Style.FILL })- c.drawPath(path, paint.apply { color = Color.WHITE; style = android.graphics.Paint.Style.STROKE; strokeWidth = 2 * dp })- return bmp- }-- // ---- Known plate, speed and red-light cameras (OpenStreetMap) ---------------------------------------------- private val redrawKnownAlpr = Runnable { if (alive) drawKnownAlpr() }-- private fun drawKnownAlprSoon() {- binding.map.removeCallbacks(redrawKnownAlpr)- binding.map.postDelayed(redrawKnownAlpr, 250)- binding.map.removeCallbacks(redrawCctv)- binding.map.postDelayed(redrawCctv, 250)- }-- // ---- CCTV cameras (OpenStreetMap) ----------------------------------------------------------------- private val redrawCctv = Runnable { if (alive) drawCctv() }- private fun drawCctvSoon() {- binding.map.removeCallbacks(redrawCctv)- binding.map.postDelayed(redrawCctv, 300)- }- private val downloadCctv = Runnable { if (alive) maybeDownloadCctv() }-- /** Below this zoom the layer is hidden (cities hold thousands of cameras); view cones from [cctvConeZoom]. */- private val cctvMinZoom = 12.0- private val cctvConeZoom = 15.0-- /** What the CCTV layer is doing, added to the status line (null while the layer is off). */- @Volatile private var cctvLine: String? = null-- private fun setCctvLine(text: String?) {- if (text == cctvLine) return- cctvLine = text- if (tripId == null) renderLive()- }-- private fun drawCctv() {- com.rfsentinel.app.alpr.CctvStore.onChanged = { if (alive) drawCctvSoon() }- val map = binding.map- val on = com.rfsentinel.app.util.Prefs.showCctv(act) && tripId == null- if (!on || map.zoomLevelDouble < cctvMinZoom) {- if (cctv.points.isNotEmpty() || cctvCones.cameras.isNotEmpty()) {- cctv.points = emptyList(); cctvCones.cameras = emptyList(); map.invalidate()- }- setCctvLine(if (!on) null else com.rfsentinel.app.alpr.CctvStore.progress?.let { "CCTV: downloading around you, $it" }- ?: "CCTV: zoom in to see the cameras")- return- }- map.removeCallbacks(downloadCctv)- map.postDelayed(downloadCctv, 1_200)- val private = com.rfsentinel.app.util.Prefs.cctvPrivate(act)- val box = map.boundingBox.increaseByScale(1.5f)- val center = map.mapCenter- val inView = com.rfsentinel.app.alpr.CctvStore.cameras.filter {- (private || !it.isPrivate) && it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast- }.let { all ->- // Zoomed out over a city: the ones nearest the centre of the screen.- if (all.size <= 3000) all- else all.sortedBy { (it.lat - center.latitude).let { d -> d * d } + (it.lon - center.longitude).let { d -> d * d } }.take(3000)- }- val dp = resources.displayMetrics.density- val publicIcon = MapIcons.cctvIcon(dp, false); val privateIcon = MapIcons.cctvIcon(dp, true)- cctvCones.cameras = if (map.zoomLevelDouble >= cctvConeZoom) inView else emptyList()- cctv.points = inView.map { PointsOverlay.Point(it.lat, it.lon, it, icon = if (it.isPrivate) privateIcon else publicIcon) }- map.invalidate()- val store = com.rfsentinel.app.alpr.CctvStore- val view = map.boundingBox- val hiddenPrivate = if (private) 0 else store.cameras.count {- it.isPrivate && it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast- }- val shown = inView.count { it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast }- setCctvLine(when {- store.progress != null -> "CCTV: downloading around you, ${store.progress}"- store.isBusy -> "CCTV: downloading..."- System.currentTimeMillis() - store.lastFailureAt < 60_000 -> "CCTV: map server busy - retrying"- store.missingAreas > 0 && shown > 0 -> "CCTV: $shown in view - ${store.missingAreas} area(s) around you still missing (servers busy), retried next time"- shown == 0 && store.needsDownload(view.latSouth, view.lonWest, view.latNorth, view.lonEast) -> "CCTV: downloading..."- shown == 0 && hiddenPrivate > 0 -> "CCTV: only private ones here ($hiddenPrivate) - Settings > Known cameras > Include private"- shown == 0 -> "CCTV: none mapped here"- else -> "CCTV: $shown in view" + if (hiddenPrivate > 0) " (+$hiddenPrivate private hidden)" else ""- })- }-- /**- * Fetches the CCTV cameras within the download radius around you (once, in the- * background), and the area on screen when you look somewhere outside it.- */- private fun maybeDownloadCctv() {- val map = binding.map- if (!com.rfsentinel.app.util.Prefs.showCctv(act) || tripId != null) return- val store = com.rfsentinel.app.alpr.CctvStore- if (map.isAnimating || store.isBusy) { map.postDelayed(downloadCctv, 2_000); return }- val here = myLocation.myLocation ?: ScanForegroundService.lastFix?.let { GeoPoint(it.latitude, it.longitude) }- if (here != null) {- val radius = com.rfsentinel.app.util.Prefs.cameraRadiusKm(act).toDouble()- store.ensureAround(act, here.latitude, here.longitude, radius)- if (store.isBusy) return- }- if (map.zoomLevelDouble < cctvMinZoom) return- val box = map.boundingBox- viewLifecycleOwner.lifecycleScope.launch {- com.rfsentinel.app.alpr.CctvStore.autoDownload(act, box.latSouth, box.lonWest, box.latNorth, box.lonEast)- // Redraw either way: new cameras, or the status line (none mapped / server busy).- drawCctv()- // After a failure, try again once the back-off has passed.- if (System.currentTimeMillis() - com.rfsentinel.app.alpr.CctvStore.lastFailureAt < 60_000)- binding.map.postDelayed(downloadCctv, 61_000)- }- }-- private fun showCctv(c: com.rfsentinel.app.alpr.CctvCamera) {- val text = buildString {- append(when (c.zone) {- "public" -> "Watches a public space (street, square, station...).\n"- "outdoor" -> "A private camera that watches outside (an entrance, a car park...).\n"- "indoor" -> "Inside a building or shop.\n"- else -> "Whether it watches public space isn't mapped.\n"- })- c.area?.let { append("Watches: $it\n") }- c.operator?.let { append("Operator: $it\n") }- c.mount?.let { append("Mounted on: $it\n") }- c.height?.let { append("Height: ${"%.0f".format(it)} m\n") }- c.direction?.let { append("Faces: $it°" + (c.angle?.let { a -> ", $a° wide" } ?: "") + "\n") }- append("OSM: ${c.osmId}\n\n")- append("Mapped by OpenStreetMap volunteers. Most of these cameras are wired and give off no Bluetooth or WiFi " +- "signal, so the scan can't detect them - this layer shows the ones that have been mapped. " +- "The shaded area is an estimate of what it sees.\n\nMap data © OpenStreetMap contributors (ODbL).")- }- AlertDialog.Builder(act)- .setTitle(com.rfsentinel.app.alpr.Cctv.title(c))- .setMessage(text)- .setPositiveButton("Close", null)- .setNeutralButton("Open in OpenStreetMap") { _, _ ->- runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${c.osmId}"))) }- }- .show()- }-- private val autoDownloadCameras = Runnable { if (alive) maybeAutoDownloadCameras() }-- /**- * Fetches the cameras for the area on screen when it isn't cached yet, so- * they're always on the map without a manual download. Runs once the map- * has stopped moving for a moment.- */- private fun maybeAutoDownloadCameras() {- val prefs = com.rfsentinel.app.util.Prefs- if (!prefs.autoCameras(act) || !prefs.showKnownAlpr(act) || tripId != null) return- // Still gliding to your position (or another target): wait until it stops.- if (binding.map.isAnimating) { binding.map.postDelayed(autoDownloadCameras, 1_000); return }- val box = binding.map.boundingBox- val span = com.rfsentinel.app.alpr.AlprStore.MAX_SPAN_DEG- if (box.latNorth - box.latSouth > span || box.lonEast - box.lonWest > span) return- // The map starts at 0°,0° until it's moved to your position: don't fetch the ocean.- if (kotlin.math.abs(box.centerLatitude) < 0.5 && kotlin.math.abs(box.centerLongitude) < 0.5) return- // Another download (e.g. the car screen's) is running: look again shortly.- if (com.rfsentinel.app.alpr.AlprStore.isBusy) { binding.map.postDelayed(autoDownloadCameras, 3_000); return }- viewLifecycleOwner.lifecycleScope.launch {- val changed = com.rfsentinel.app.alpr.AlprStore.autoDownload(- act, box.latSouth, box.lonWest, box.latNorth, box.lonEast- )- // Redrawing also re-checks the area now on screen, in case the map moved meanwhile.- if (changed) { drawKnownAlpr(); refreshServiceLocation() }- }- }-- /** Draws the cameras in (and just around) the visible area; skipped when zoomed far out. */- private fun drawKnownAlpr() {- val map = binding.map- map.removeCallbacks(autoDownloadCameras)- map.postDelayed(autoDownloadCameras, 1_200)- if (!com.rfsentinel.app.util.Prefs.showKnownAlpr(act) || map.zoomLevelDouble < 9.0) {- knownAlpr.points = emptyList(); map.invalidate(); return- }- val box = map.boundingBox.increaseByScale(1.5f)- val inView = com.rfsentinel.app.alpr.AlprStore.cameras.filter {- it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast- }.take(1500)- val dp = resources.displayMetrics.density- val icons = com.rfsentinel.app.alpr.KnownCamera.Kind.entries.associateWith { cameraIcon(dp, it) }- knownAlpr.points = inView.map { cam ->- // Cameras whose alerts you turned off stay on the map, faded.- val ignored = com.rfsentinel.app.alpr.IgnoredCameras.contains(act, cam.osmId)- PointsOverlay.Point(cam.lat, cam.lon, cam, icon = icons.getValue(cam.type), alpha = if (ignored) 90 else 255)- }- knownAlprDrawnFor = box- map.invalidate()- }-- private fun cameraIcon(dp: Float, kind: com.rfsentinel.app.alpr.KnownCamera.Kind) = MapIcons.cameraIcon(dp, kind)-- private fun showKnownCamera(cam: com.rfsentinel.app.alpr.KnownCamera) {- val ignored = com.rfsentinel.app.alpr.IgnoredCameras.contains(act, cam.osmId)- val text = buildString {- if (ignored) append("Alerts for this camera are off.\n\n")- append(when (cam.type) {- com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> "A license-plate reader mapped in OpenStreetMap.\n\n"- com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> "A speed camera mapped in OpenStreetMap.\n\n"- com.rfsentinel.app.alpr.KnownCamera.Kind.RED_LIGHT -> "A red-light camera mapped in OpenStreetMap.\n\n"- })- cam.brand?.let { append("Maker: $it\n") }- cam.operator?.let { append("Operator: $it\n") }- cam.direction?.let { append("Faces: $it°\n") }- append("OSM: ${cam.osmId}\n\n")- append("These cameras send their data over cellular or wire and have no Bluetooth/WiFi signature, so they can't be detected by radio - this map is the only warning. Mobile speed cameras move and are rarely mapped.\n\nMap data © OpenStreetMap contributors (ODbL).")- }- AlertDialog.Builder(act)- .setTitle(cam.label)- .setMessage(text)- // Kept until turned back on here (or cleared in Settings).- .setPositiveButton(if (ignored) "Alert again" else "Ignore alerts") { _, _ ->- com.rfsentinel.app.alpr.IgnoredCameras.set(act, cam.osmId, !ignored)- Toast.makeText(act, if (ignored) "You'll be warned about this camera again"- else "No more alerts for this camera (tap it again to undo)", Toast.LENGTH_SHORT).show()- drawKnownAlpr()- }- .setNegativeButton("Close", null)- .setNeutralButton("Open in OpenStreetMap") { _, _ ->- runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${cam.osmId}"))) }- }- .show()- }-- /** Towers with a map position (the Cells chip's count), refreshed with the layer. */- private var towerCount = 0-- private fun drawTowers() {- towerCount = com.rfsentinel.app.service.CellTowerStore.all(act).count { it.bestLat != null }- // The Cells chip shows the towers (only them); All adds them when the map menu's switch is on;- // every other chip hides them.- val show = filter == DeviceFilter.CELLS ||- (filter == DeviceFilter.ALL && com.rfsentinel.app.util.Prefs.showCellTowers(act))- towers.points = if (tripId != null || !show) emptyList()- else com.rfsentinel.app.service.CellTowerStore.all(act).filter { it.bestLat != null }.map {- PointsOverlay.Point(it.bestLat!!, it.bestLon!!, it, icon = towerIcon)- }- binding.map.invalidate()- }-- private fun showTower(t: com.rfsentinel.app.service.CellTowerStore.Tower) {- val net = listOfNotNull(t.operator, "${t.mcc ?: "?"}-${t.mnc ?: "?"}").joinToString(" · ")- AlertDialog.Builder(act)- .setTitle(t.ratLabel)- .setMessage("$net\nArea ${t.area ?: "?"} · Cell ${t.cellId}" +- (t.bestDbm?.let { "\nStrongest signal $it dBm" } ?: "") +- "\nSeen ${t.timesSeen}×, last ${dateFmt.format(java.util.Date(t.lastSeen))}" +- "\n\nPlaced where your phone heard it strongest: an estimate, not the tower's exact position.")- .setPositiveButton("All towers") { _, _ -> startActivity(Intent(act, CellTowersActivity::class.java)) }- .setNegativeButton("Close", null)- .show()- }-- /** One device, or a list to pick from when several were heard at the same spot. */- private fun showPins(list: List<Pin>) {- if (list.size == 1) { showPin(list[0]); return }- val sorted = list.sortedByDescending { it.flagged }- AlertDialog.Builder(act)- .setTitle("${list.size} devices here")- .setItems(sorted.map { (if (it.flagged) "⚠ " else "") + it.label }.toTypedArray()) { _, i -> showPin(sorted[i]) }- .setNegativeButton("Close", null)- .show()- }-- private fun showPin(p: Pin) {- AlertDialog.Builder(act)- .setTitle(p.label)- .setMessage(p.details + "\n\n" + p.whereNote)- .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(act, p.mac) }- .setNegativeButton("Close", null)- .show()- }-- private var stopObservingBulk: (() -> Unit)? = null+ // ---- DeFlock downloads ----------------------------------------------------------------/** Status text while a DeFlock download runs, or null when none does. */private fun bulkStatus(): String? = when (val s = com.rfsentinel.app.alpr.DeflockBulk.state) {@@ -1586,13 +907,13 @@ class MapFragment : Fragment() {}is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras -> {// DeFlock's cameras are saved: show them now; the bar keeps moving for the extras.- com.rfsentinel.app.util.Prefs.setShowKnownAlpr(act, true)- drawKnownAlpr(); refreshServiceLocation()+ Prefs.setShowKnownAlpr(act, true)+ rf?.safe("static") { rf?.maybeRedrawStatic(force = true) }; refreshServiceLocation()bar.visibility = View.INVISIBLE; bar.isIndeterminate = true; bar.visibility = View.VISIBLE}is com.rfsentinel.app.alpr.DeflockBulk.State.Done -> {bar.visibility = View.GONE- drawKnownAlpr(); refreshServiceLocation()+ rf?.safe("static") { rf?.maybeRedrawStatic(force = true) }; refreshServiceLocation()}is com.rfsentinel.app.alpr.DeflockBulk.State.Failed -> {bar.visibility = View.GONE@@ -1636,12 +957,7 @@ class MapFragment : Fragment() {1 -> { id?.let { Exporter.showTripExport(act, it) }; true }2 -> { id?.let { rename(it) }; true }3 -> { id?.let { confirmDelete(it) }; true }- 12 -> {- startActivity(Intent(act, com.rfsentinel.app.settings.SettingsActivity::class.java)- .putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION,- com.rfsentinel.app.settings.SettingsActivity.SECTION_MAP))- true- }+ 12 -> { openMapSettings(); true }13 -> { WazeUi.checkNow(act); true }14 -> { WazeUi.openStatus(act); true }else -> falsediff --git a/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.ktindex d2e50a4..9226be2 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt@@ -15,13 +15,17 @@ import java.io.File/** Map pieces shared by the phone map and the Android Auto map. */object MapIcons {+ /** CCTV cameras and their view: public ones slate, private ones brown-grey. */+ const val CCTV_PUBLIC_COLOR = 0xFF455A64.toInt()+ const val CCTV_PRIVATE_COLOR = 0xFF8D6E63.toInt()+/** A small CCTV camera (body on a bracket) for the OpenStreetMap CCTV layer. */fun cctvIcon(dp: Float, private: Boolean): Bitmap {val w = (16 * dp).toInt(); val h = (14 * dp).toInt()val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)val c = Canvas(bmp)val p = Paint(Paint.ANTI_ALIAS_FLAG)- val color = if (private) CctvConeOverlay.PRIVATE_COLOR else CctvConeOverlay.PUBLIC_COLOR+ val color = if (private) CCTV_PRIVATE_COLOR else CCTV_PUBLIC_COLORval body = RectF(1.5f * dp, 2 * dp, w - 3 * dp, 8 * dp)p.color = colorc.drawRoundRect(body, 2 * dp, 2 * dp, p)diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.ktnew file mode 100644index 0000000..2906bf1--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt@@ -0,0 +1,356 @@+package com.rfsentinel.app.ui++import android.annotation.SuppressLint+import android.content.Context+import android.graphics.Bitmap+import android.graphics.PointF+import android.graphics.RectF+import android.location.Location+import android.os.Bundle+import com.rfsentinel.app.util.Permissions+import org.json.JSONArray+import org.json.JSONObject+import org.maplibre.android.MapLibre+import org.maplibre.android.camera.CameraPosition+import org.maplibre.android.camera.CameraUpdateFactory+import org.maplibre.android.geometry.LatLng+import org.maplibre.android.geometry.LatLngBounds+import org.maplibre.android.location.LocationComponent+import org.maplibre.android.location.LocationComponentActivationOptions+import org.maplibre.android.location.LocationComponentOptions+import org.maplibre.android.location.OnCameraTrackingChangedListener+import org.maplibre.android.location.modes.CameraMode+import org.maplibre.android.location.modes.RenderMode+import org.maplibre.android.maps.MapLibreMap+import org.maplibre.android.maps.MapLibreMapOptions+import org.maplibre.android.maps.MapView+import org.maplibre.android.maps.Style+import org.maplibre.android.style.expressions.Expression+import org.maplibre.android.style.layers.CircleLayer+import org.maplibre.android.style.layers.FillExtrusionLayer+import org.maplibre.android.style.layers.FillLayer+import org.maplibre.android.style.layers.HeatmapLayer+import org.maplibre.android.style.layers.Layer+import org.maplibre.android.style.layers.LayoutPropertyValue+import org.maplibre.android.style.layers.LineLayer+import org.maplibre.android.style.layers.PaintPropertyValue+import org.maplibre.android.style.layers.PropertyFactory+import org.maplibre.android.style.layers.PropertyValue+import org.maplibre.android.style.layers.SymbolLayer+import org.maplibre.android.style.sources.GeoJsonSource++/** [MapEngine] on MapLibre with OpenFreeMap's vector maps (free, no account, no key). */+internal class MapLibreEngine(private val context: Context) : MapEngine {++ companion object {+ /** OpenFreeMap: OpenStreetMap vector tiles, free, no account, no key, no cookies. */+ const val LIGHT_STYLE = "https://tiles.openfreemap.org/styles/liberty"+ /** A navy night map (like Waze's), lifted further in [nightTweaks]: OpenFreeMap's "dark" is near black. */+ const val DARK_STYLE = "https://tiles.openfreemap.org/styles/fiord"+ const val CREDIT = "© OpenFreeMap © OpenMapTiles © OpenStreetMap contributors"+ private const val BUILDINGS = "rf-buildings-3d"+ private const val GRASS = "rf-night-grass"+ /** Style properties whose value is a plain array, not an expression. */+ private val ARRAY_PROPERTIES = setOf("text-font", "text-offset", "icon-offset", "line-dasharray", "text-variable-anchor", "text-translate", "icon-translate", "circle-translate", "fill-translate", "line-translate")++ /** A style JSON value as MapLibre wants it: expressions, float numbers, typed arrays. */+ internal fun value(name: String, v: Any?): Any? = when {+ v is JSONArray && name in ARRAY_PROPERTIES ->+ if (v.length() > 0 && v.get(0) is String) Array(v.length()) { v.getString(it) }+ else Array(v.length()) { v.getDouble(it).toFloat() }+ v is JSONArray -> Expression.Converter.convert(v.toString())+ v is Number -> v.toFloat()+ else -> v+ }+ }++ override val provider = MapEngine.Provider.OPENFREEMAP+ override val credit = CREDIT+ override val labelFont = listOf("Noto Sans Regular")++ init { MapLibre.getInstance(context.applicationContext) }++ override val view = MapView(context, MapLibreMapOptions.createFromAttributes(context))+ private var map: MapLibreMap? = null++ override var onCameraMove: (() -> Unit)? = null+ override var onIdle: (() -> Unit)? = null+ override var onClick: ((Float, Float) -> Unit)? = null+ override var onUserGesture: (() -> Unit)? = null+ override var onFollowDismissed: (() -> Unit)? = null++ override fun onCreate(state: Bundle?) = view.onCreate(state)+ override fun onStart() = view.onStart()+ override fun onResume() = view.onResume()+ override fun onPause() = view.onPause()+ override fun onStop() = view.onStop()+ override fun onLowMemory() = view.onLowMemory()+ override fun onSaveInstanceState(out: Bundle) = view.onSaveInstanceState(out)+ override fun onDestroy() { map = null; view.onDestroy() }++ override fun whenReady(ready: () -> Unit) {+ view.getMapAsync { m ->+ map = m+ m.uiSettings.isCompassEnabled = false+ m.uiSettings.isLogoEnabled = false+ m.uiSettings.isAttributionEnabled = false // the credit line on the map instead+ m.uiSettings.isTiltGesturesEnabled = true+ m.addOnCameraMoveStartedListener { reason ->+ if (reason == MapLibreMap.OnCameraMoveStartedListener.REASON_API_GESTURE) onUserGesture?.invoke()+ }+ m.addOnCameraMoveListener { onCameraMove?.invoke() }+ m.addOnCameraIdleListener { onIdle?.invoke() }+ m.addOnMapClickListener { at ->+ val p = m.projection.toScreenLocation(at)+ onClick?.invoke(p.x, p.y)+ false+ }+ ready()+ }+ }++ // ---- style ----++ override fun setStyle(dark: Boolean, loaded: (Boolean) -> Unit) {+ val m = map ?: return+ m.setStyle(Style.Builder().fromUri(if (dark) DARK_STYLE else LIGHT_STYLE)) { style ->+ if (dark) runCatching { nightTweaks(style) }+ loaded(true)+ }+ }++ /**+ * The night map, made easier to read at a glance: residential areas drawn near-white in+ * OpenFreeMap's navy style go navy, roads lighter than the ground (as in Waze at night), and+ * 3D buildings, which the style hasn't got.+ */+ private fun nightTweaks(style: Style) {+ // Ground a little lighter, water deeper, and nature green (the style has no green at all).+ style.getLayer("background")?.setProperties(PropertyFactory.backgroundColor("#4D5977"))+ style.getLayer("water")?.setProperties(PropertyFactory.fillColor("#2C3B60"))+ style.getLayer("landuse_residential")?.setProperties(PropertyFactory.fillColor("#58647F"), PropertyFactory.fillOpacity(0.45f))+ style.getLayer("park")?.setProperties(PropertyFactory.fillColor("#3E6E52"), PropertyFactory.fillOpacity(0.7f))+ style.getLayer("park_outline")?.setProperties(PropertyFactory.lineColor("#4F8463"))+ style.getLayer("landcover_wood")?.setProperties(PropertyFactory.fillColor("#3A6650"),+ PropertyFactory.fillOpacity(Expression.interpolate(Expression.linear(), Expression.zoom(),+ Expression.stop(8, 0.4f), Expression.stop(12, 0.7f))))+ style.getLayer("building")?.setProperties(PropertyFactory.fillColor("#5F6B8A"), PropertyFactory.fillOpacity(0.6f))+ addPlaceLabels(style)+ if (style.getLayer("night-oneway") == null) NightLabels.layers.forEach { runCatching { addLayerTo(style, JSONObject(it)) } }+ // Labels: the style's grey-blue text with faint halos disappears on the ground; near-white on a dark outline instead.+ for (layer in style.layers) {+ if (layer !is SymbolLayer || layer.id.startsWith("rf-") || layer.id.startsWith("night-shield")) continue+ val road = layer.id.contains("highway") || layer.id.contains("water") || layer.id.contains("path")+ layer.setProperties(+ PropertyFactory.textColor(if (road) "#D3DCEC" else "#EEF3FA"),+ PropertyFactory.textHaloColor("#1C2436"),+ PropertyFactory.textHaloWidth(1.6f),+ PropertyFactory.textHaloBlur(0.3f),+ PropertyFactory.textOpacity(1f))+ }+ if (style.getLayer(GRASS) == null) {+ // Grass, meadows and farmland, which the night style doesn't draw: a fainter green, under the woods.+ val grass = FillLayer(GRASS, "openmaptiles").withSourceLayer("landcover").withProperties(+ PropertyFactory.fillColor("#41694F"), PropertyFactory.fillOpacity(0.45f)+ ).withFilter(Expression.Converter.convert("""["match", ["get", "class"], ["grass", "farmland"], true, false]"""))+ if (style.getLayer("landcover_wood") != null) style.addLayerBelow(grass, "landcover_wood") else style.addLayerAbove(grass, "water")+ }+ style.getLayer("highway_minor")?.setProperties(PropertyFactory.lineColor("#6A7899"))+ style.getLayer("highway_major_inner")?.setProperties(PropertyFactory.lineColor("#8190B3"))+ style.getLayer("highway_major_subtle")?.setProperties(PropertyFactory.lineColor("#8190B3"))+ style.getLayer("highway_motorway_inner")?.setProperties(PropertyFactory.lineColor("#9AA8CB"))+ style.getLayer("highway_motorway_subtle")?.setProperties(PropertyFactory.lineColor("#9AA8CB"))+ if (style.getLayer(BUILDINGS) == null) {+ val buildings = FillExtrusionLayer(BUILDINGS, "openmaptiles").withSourceLayer("building").withProperties(+ PropertyFactory.fillExtrusionColor("#36425F"),+ PropertyFactory.fillExtrusionHeight(Expression.get("render_height")),+ PropertyFactory.fillExtrusionBase(Expression.get("render_min_height")),+ PropertyFactory.fillExtrusionOpacity(0.8f)+ ).apply { minZoom = 14f }+ val firstLabel = style.layers.firstOrNull { it is SymbolLayer }?.id+ if (firstLabel != null) style.addLayerBelow(buildings, firstLabel) else style.addLayer(buildings)+ }+ }++ /**+ * Shops, businesses, landmarks and transit stops, which the night style doesn't draw at all (the+ * light map does): the same layers, icons and zoom levels as the light map, from the same tiles.+ */+ private fun addPlaceLabels(style: Style) {+ if (style.getLayer("night-poi-r1") != null) return+ fun ex(json: String) = Expression.Converter.convert(json)+ val name = ex("""["coalesce", ["get", "name_en"], ["get", "name"]]""")+ val icon = ex("""["match", ["get", "subclass"], ["florist", "furniture"], ["get", "subclass"], ["get", "class"]]""")+ fun poi(id: String, minZoom: Float, filter: String) = SymbolLayer(id, "openmaptiles").withSourceLayer("poi").withFilter(ex(filter))+ .withProperties(PropertyFactory.iconImage(icon), PropertyFactory.textField(name),+ PropertyFactory.textFont(arrayOf("Noto Sans Italic")), PropertyFactory.textSize(12f),+ PropertyFactory.textAnchor("top"), PropertyFactory.textOffset(arrayOf(0f, 0.6f)), PropertyFactory.textMaxWidth(9f))+ .also { it.minZoom = minZoom }+ val point = """["match", ["geometry-type"], ["MultiPoint", "Point"], true, false]"""+ val layers = listOf(+ poi("night-poi-r20", 17f, """["all", $point, [">=", ["get", "rank"], 20]]"""),+ poi("night-poi-r7", 16f, """["all", $point, [">=", ["get", "rank"], 7], ["<", ["get", "rank"], 20]]"""),+ poi("night-poi-r1", 15f, """["all", $point, [">=", ["get", "rank"], 1], ["<", ["get", "rank"], 7]]"""),+ SymbolLayer("night-poi-transit", "openmaptiles").withSourceLayer("poi")+ .withFilter(ex("""["match", ["get", "class"], ["airport", "bus", "rail"], true, false]"""))+ .withProperties(PropertyFactory.iconImage(ex("""["to-string", ["get", "class"]]""")), PropertyFactory.iconSize(0.7f),+ PropertyFactory.textField(name), PropertyFactory.textFont(arrayOf("Noto Sans Italic")), PropertyFactory.textSize(12f),+ PropertyFactory.textAnchor("left"), PropertyFactory.textOffset(arrayOf(0.9f, 0f)), PropertyFactory.textMaxWidth(9f))+ )+ layers.forEach { style.addLayer(it) }+ }++ private fun style(): Style? = map?.style?.takeIf { it.isFullyLoaded }+ override val styleLoaded get() = style() != null+ override fun hasSource(id: String) = style()?.getSource(id) != null+ override fun addImage(id: String, bitmap: Bitmap) { style()?.addImage(id, bitmap) }+ override fun addSource(id: String) { style()?.addSource(GeoJsonSource(id)) }+ override fun setData(source: String, geoJson: String) { style()?.getSourceAs<GeoJsonSource>(source)?.setGeoJson(geoJson) }++ override fun addLayer(json: JSONObject) { style()?.let { addLayerTo(it, json) } }++ private fun addLayerTo(style: Style, json: JSONObject) {+ val id = json.getString("id"); val src = json.getString("source")+ val layer: Layer = when (val type = json.getString("type")) {+ "circle" -> CircleLayer(id, src)+ "fill" -> FillLayer(id, src)+ "line" -> LineLayer(id, src)+ "symbol" -> SymbolLayer(id, src)+ "heatmap" -> HeatmapLayer(id, src)+ "fill-extrusion" -> FillExtrusionLayer(id, src)+ else -> throw IllegalArgumentException("layer type $type")+ }+ if (json.has("source-layer")) when (layer) {+ is CircleLayer -> layer.sourceLayer = json.getString("source-layer")+ is FillLayer -> layer.sourceLayer = json.getString("source-layer")+ is LineLayer -> layer.sourceLayer = json.getString("source-layer")+ is SymbolLayer -> layer.sourceLayer = json.getString("source-layer")+ else -> {}+ }+ val props = ArrayList<PropertyValue<*>>()+ json.optJSONObject("layout")?.let { o -> o.keys().forEach { k -> props += LayoutPropertyValue(k, value(k, o.get(k))) } }+ json.optJSONObject("paint")?.let { o -> o.keys().forEach { k -> props += PaintPropertyValue(k, value(k, o.get(k))) } }+ layer.setProperties(*props.toTypedArray())+ json.optJSONArray("filter")?.let { f ->+ val e = Expression.Converter.convert(f.toString())+ when (layer) {+ is CircleLayer -> layer.setFilter(e); is FillLayer -> layer.setFilter(e); is LineLayer -> layer.setFilter(e)+ is SymbolLayer -> layer.setFilter(e); is HeatmapLayer -> layer.setFilter(e); is FillExtrusionLayer -> layer.setFilter(e)+ }+ }+ if (json.has("minzoom")) layer.minZoom = json.getDouble("minzoom").toFloat()+ style.addLayer(layer)+ }++ override fun setPaint(layer: String, name: String, value: String) {+ style()?.getLayer(layer)?.setProperties(PaintPropertyValue(name, value))+ }++ // ---- camera ----++ override val camera: MapEngine.Camera get() {+ val c = map?.cameraPosition ?: return MapEngine.Camera(0.0, 0.0, 0.0, 0.0, 0.0)+ return MapEngine.Camera(c.target?.latitude ?: 0.0, c.target?.longitude ?: 0.0, c.zoom, c.bearing, c.tilt)+ }++ override fun jumpTo(lat: Double, lon: Double, zoom: Double?) {+ val m = map ?: return+ m.cameraPosition = CameraPosition.Builder(m.cameraPosition).target(LatLng(lat, lon)).apply { zoom?.let { zoom(it) } }.build()+ }++ override fun zoomTo(zoom: Double) { map?.moveCamera(CameraUpdateFactory.zoomTo(zoom)) }++ override fun easeTo(lat: Double?, lon: Double?, zoom: Double?, bearing: Double?, tilt: Double?, flat: Boolean, ms: Long) {+ val m = map ?: return+ val b = CameraPosition.Builder(m.cameraPosition)+ if (lat != null && lon != null) b.target(LatLng(lat, lon))+ zoom?.let { b.zoom(it) }; bearing?.let { b.bearing(it) }; tilt?.let { b.tilt(it) }+ if (flat) b.padding(0.0, 0.0, 0.0, 0.0)+ m.animateCamera(CameraUpdateFactory.newCameraPosition(b.build()), ms.toInt().coerceAtLeast(1))+ }++ override fun fit(points: List<Pair<Double, Double>>, paddingPx: Int) {+ val m = map ?: return+ if (points.isEmpty()) return+ if (points.size == 1) { jumpTo(points[0].first, points[0].second); return }+ val b = LatLngBounds.Builder().apply { points.forEach { include(LatLng(it.first, it.second)) } }.build()+ m.moveCamera(CameraUpdateFactory.newLatLngBounds(b, paddingPx))+ }++ override fun visibleBox(): MapEngine.Box? {+ val v = runCatching { map?.projection?.visibleRegion?.latLngBounds }.getOrNull() ?: return null+ return MapEngine.Box(v.latitudeNorth, v.longitudeEast, v.latitudeSouth, v.longitudeWest)+ }++ override fun toLatLon(x: Float, y: Float): Pair<Double, Double>? =+ map?.projection?.fromScreenLocation(PointF(x, y))?.let { it.latitude to it.longitude }++ override fun setMinZoom(zoom: Double) { map?.setMinZoomPreference(zoom) }++ override fun query(box: RectF, layers: List<Pair<String, String>>, result: (List<List<String>>) -> Unit) {+ val m = map ?: return result(layers.map { emptyList() })+ result(layers.map { (layer, key) ->+ runCatching { m.queryRenderedFeatures(box, layer).mapNotNull { f -> if (f.hasProperty(key)) f.getStringProperty(key) else null } }+ .getOrDefault(emptyList())+ })+ }++ // ---- your position ----++ private fun component(): LocationComponent? =+ map?.let { runCatching { it.locationComponent }.getOrNull() }?.takeIf { it.isLocationComponentActivated }++ override val puckOn get() = component() != null++ @SuppressLint("MissingPermission") // checked first+ override fun startPuck(): Boolean {+ val m = map ?: return false+ val style = style() ?: return false+ if (!Permissions.granted(context, android.Manifest.permission.ACCESS_FINE_LOCATION)) return false+ val lc = m.locationComponent+ // Light / dark switch: the component moves to the new style by itself.+ if (!lc.isLocationComponentActivated) {+ val options = LocationComponentOptions.builder(context)+ .pulseEnabled(false)+ .accuracyAnimationEnabled(false)+ .trackingGesturesManagement(true) // a one-finger pan stops following; a pinch keeps it+ .build()+ // Fixes come from the screen, so slow ones can keep the last real heading before the map sees them.+ lc.activateLocationComponent(LocationComponentActivationOptions.builder(context, style)+ .useDefaultLocationEngine(false)+ .locationComponentOptions(options)+ .build())+ lc.isLocationComponentEnabled = true+ lc.renderMode = RenderMode.GPS+ lc.addOnCameraTrackingChangedListener(object : OnCameraTrackingChangedListener {+ override fun onCameraTrackingDismissed() { onFollowDismissed?.invoke() }+ override fun onCameraTrackingChanged(mode: Int) {}+ })+ }+ return true+ }++ override fun pushFix(fix: Location) { component()?.forceLocationUpdate(fix) }++ private var reapply: Runnable? = null++ override fun follow(mode: MapEngine.Follow, topPaddingPx: Double?, tilt: Double, zoom: Double?, ms: Long) {+ val lc = component() ?: return+ reapply?.let { view.removeCallbacks(it) }; reapply = null+ if (mode == MapEngine.Follow.NONE) { lc.cameraMode = CameraMode.NONE; return }+ // The component ignores padding / tilt / zoom while its camera mode is changing, so they go first,+ // and once more when the change is over (a mode switch no longer leaves the old angle or zoom).+ fun look(duration: Long) {+ topPaddingPx?.let { lc.paddingWhileTracking(doubleArrayOf(0.0, it, 0.0, 0.0), duration) }+ lc.tiltWhileTracking(tilt, duration)+ zoom?.let { lc.zoomWhileTracking(it, duration) }+ }+ 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) }+ val m = map+ if (mode == MapEngine.Follow.NORTH && m != null && m.cameraPosition.bearing != 0.0) m.animateCamera(CameraUpdateFactory.bearingTo(0.0), 600)+ }++ override fun placeBranding(topPx: Int) {}+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt b/app/src/main/java/com/rfsentinel/app/ui/MapShared.ktnew file mode 100644index 0000000..df5802a--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt@@ -0,0 +1,239 @@+package com.rfsentinel.app.ui++import android.content.Intent+import android.widget.Toast+import androidx.appcompat.app.AlertDialog+import androidx.appcompat.app.AppCompatActivity+import com.rfsentinel.app.service.DeviceRegistry+import java.util.Locale++/*+ * What the map ([MapFragment] / [RfMap]) and its saved-trace view share: which devices go on+ * the map and how they're described, the dialogs that open when something is tapped, and the+ * shapes drawn around things.+ */++/** One device to draw, from the live registry or a saved trip. */+internal data class MapPin(+ val mac: String, val lat: Double, val lon: Double, val label: String, val flagged: Boolean,+ val color: Int, val details: String,+ /** Pinpointed (see [com.rfsentinel.app.detect.Locator]): the circle it is very likely in. */+ val radiusM: Double? = null,+ val whereNote: String = "Position = where your phone was when this device's signal was strongest (approximate)."+)++internal object MapPins {++ /** The live devices [filter] shows, with a position (pinpointed, broadcast or where heard strongest). */+ fun live(context: android.content.Context, devices: List<DeviceRegistry.Snapshot>, filter: DeviceFilter): List<MapPin> =+ devices.mapNotNull { s ->+ val pos = s.place ?: return@mapNotNull null+ val flagged = DeviceColors.isFlagged(s)+ val located = s.located?.takeIf { flagged && s.broadcast == null }+ if (!filter.matches(s) || filter == DeviceFilter.RADIO) return@mapNotNull null+ val best = s.best+ MapPin(+ s.mac, pos.lat, pos.lon,+ best?.label ?: s.name ?: s.deviceType,+ flagged,+ DeviceColors.forDevice(context, s),+ buildString {+ append(s.mac)+ s.vendor?.let { append("\n").append(it) }+ if (best != null) append("\n${best.category.title} · ${best.tier.label} ${best.confidence}%\n${best.evidence}")+ if (located != null) append("\nPinpointed ${com.rfsentinel.app.detect.Locator.describe(located)}")+ append("\nStrongest signal: ${s.bestRssi} dBm")+ },+ radiusM = located?.radiusM,+ whereNote = if (s.broadcast != null)+ "Position = the vehicle's own GPS, broadcast over V2X (exact, not an estimate)."+ else if (located != null)+ "Position = pinpointed from the signal at the many spots you passed: very likely inside the circle " ++ "(${located.radiusM.toInt()} m). The more sides you pass it from, the smaller the circle."+ else if (flagged)+ "Position = where your phone was when this device's signal was strongest (approximate). " ++ "Drive or walk past it from another side - around the block - to pinpoint it."+ else "Position = where your phone was when this device's signal was strongest (approximate)."+ )+ }+}++internal object MapDialogs {++ /** One device, or a list to pick from when several were heard at the same spot. */+ fun showPins(a: AppCompatActivity, list: List<MapPin>) {+ if (list.isEmpty()) return+ if (list.size == 1) { showPin(a, list[0]); return }+ val sorted = list.sortedByDescending { it.flagged }+ AlertDialog.Builder(a)+ .setTitle("${list.size} devices here")+ .setItems(sorted.map { (if (it.flagged) "⚠ " else "") + it.label }.toTypedArray()) { _, i -> showPin(a, sorted[i]) }+ .setNegativeButton("Close", null)+ .show()+ }++ fun showPin(a: AppCompatActivity, p: MapPin) {+ AlertDialog.Builder(a)+ .setTitle(p.label)+ .setMessage(p.details + "\n\n" + p.whereNote)+ .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(a, p.mac) }+ .setNegativeButton("Close", null)+ .show()+ }++ fun showWaze(a: AppCompatActivity, w: com.rfsentinel.app.online.WazePolice.Shown) {+ AlertDialog.Builder(a)+ .setTitle(w.hit.label)+ .setMessage("${w.hit.tier.label} ${w.hit.confidence}%\n${com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend)}\n${w.hit.evidence}")+ .setNegativeButton("Close", null)+ .show()+ }++ /** [me] = your position (lat, lon) for the distance, when known. */+ fun showAircraft(a: AppCompatActivity, p: com.rfsentinel.app.online.PoliceAircraft.Plane, hit: com.rfsentinel.app.detect.Hit?,+ me: Pair<Double, Double>?) {+ val text = buildString {+ hit?.let { append(it.evidence).append("\n\n") }+ p.registration?.let { append("Registration: $it\n") }+ p.callsign?.let { append("Callsign: $it\n") }+ p.type?.let { append("Type: $it\n") }+ p.owner?.let { append("Owner / operator: $it\n") }+ p.altitudeFt?.let { append(if (it <= 0) "On the ground\n" else "Altitude: $it ft\n") }+ p.speedKt?.let { append(String.format(Locale.US, "Speed: %.0f kt (%.0f km/h)\n", it, it * 1.852)) }+ p.trackDeg?.let { append(String.format(Locale.US, "Heading: %.0f°\n", it)) }+ me?.let { append(String.format(Locale.US, "Distance: %.1f km\n",+ DeviceRegistry.metersBetween(it.first, it.second, p.lat, p.lon) / 1000)) }+ append("ICAO address: ${p.hex.uppercase()}\nSource: community ADS-B (adsb.fi / adsb.lol)")+ }+ AlertDialog.Builder(a)+ .setTitle(hit?.label ?: (p.registration ?: p.callsign ?: "Aircraft"))+ .setMessage(text)+ .setPositiveButton("OK", null)+ .show()+ }++ fun droneDetails(s: DeviceRegistry.Snapshot, r: com.rfsentinel.app.detect.RemoteId.Info) = buildString {+ r.uasId?.let { append("ID: $it\n") }+ r.uaType?.let { append("Type: $it\n") }+ r.status?.let { append("Status: $it\n") }+ r.heightM?.let { append(String.format(Locale.US, "Height: %.0f m\n", it)) }+ r.altitudeGeoM?.let { append(String.format(Locale.US, "Altitude (GPS): %.0f m\n", it)) }+ r.speedMs?.let { append(String.format(Locale.US, "Speed: %.0f km/h\n", it * 3.6)) }+ r.directionDeg?.let { append("Heading: $it°\n") }+ r.operatorId?.let { append("Operator ID: $it\n") }+ r.selfIdDescription?.let { append("Description: $it\n") }+ append("Radio: ${s.mac} · ${s.rssi} dBm")+ }++ fun showDrone(a: AppCompatActivity, mac: String, text: String) {+ AlertDialog.Builder(a)+ .setTitle("Drone (Remote ID)")+ .setMessage(text + "\n\nPositions are broadcast by the drone itself (ASTM F3411 Remote ID).")+ .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(a, mac) }+ .setNegativeButton("Close", null)+ .show()+ }++ fun showCctv(a: AppCompatActivity, c: com.rfsentinel.app.alpr.CctvCamera) {+ val text = buildString {+ append(when (c.zone) {+ "public" -> "Watches a public space (street, square, station...).\n"+ "outdoor" -> "A private camera that watches outside (an entrance, a car park...).\n"+ "indoor" -> "Inside a building or shop.\n"+ else -> "Whether it watches public space isn't mapped.\n"+ })+ c.area?.let { append("Watches: $it\n") }+ c.operator?.let { append("Operator: $it\n") }+ c.mount?.let { append("Mounted on: $it\n") }+ c.height?.let { append("Height: ${"%.0f".format(it)} m\n") }+ c.direction?.let { append("Faces: $it°" + (c.angle?.let { ang -> ", $ang° wide" } ?: "") + "\n") }+ append("OSM: ${c.osmId}\n\n")+ append("Mapped by OpenStreetMap volunteers. Most of these cameras are wired and give off no Bluetooth or WiFi " ++ "signal, so the scan can't detect them - this layer shows the ones that have been mapped. " ++ "The shaded area is an estimate of what it sees.\n\nMap data © OpenStreetMap contributors (ODbL).")+ }+ AlertDialog.Builder(a)+ .setTitle(com.rfsentinel.app.alpr.Cctv.title(c))+ .setMessage(text)+ .setPositiveButton("Close", null)+ .setNeutralButton("Open in OpenStreetMap") { _, _ ->+ runCatching { a.startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${c.osmId}"))) }+ }+ .show()+ }++ /** [onChanged] after its alerts were turned off or on again (redraw it faded / normal). */+ fun showKnownCamera(a: AppCompatActivity, cam: com.rfsentinel.app.alpr.KnownCamera, onChanged: () -> Unit) {+ val ignored = com.rfsentinel.app.alpr.IgnoredCameras.contains(a, cam.osmId)+ val text = buildString {+ if (ignored) append("Alerts for this camera are off.\n\n")+ append(when (cam.type) {+ com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> "A license-plate reader mapped in OpenStreetMap.\n\n"+ com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> "A speed camera mapped in OpenStreetMap.\n\n"+ com.rfsentinel.app.alpr.KnownCamera.Kind.RED_LIGHT -> "A red-light camera mapped in OpenStreetMap.\n\n"+ })+ cam.brand?.let { append("Maker: $it\n") }+ cam.operator?.let { append("Operator: $it\n") }+ cam.direction?.let { append("Faces: $it°\n") }+ append("OSM: ${cam.osmId}\n\n")+ append("These cameras send their data over cellular or wire and have no Bluetooth/WiFi signature, so they can't be detected by radio - this map is the only warning. Mobile speed cameras move and are rarely mapped.\n\nMap data © OpenStreetMap contributors (ODbL).")+ }+ AlertDialog.Builder(a)+ .setTitle(cam.label)+ .setMessage(text)+ // Kept until turned back on here (or cleared in Settings).+ .setPositiveButton(if (ignored) "Alert again" else "Ignore alerts") { _, _ ->+ com.rfsentinel.app.alpr.IgnoredCameras.set(a, cam.osmId, !ignored)+ Toast.makeText(a, if (ignored) "You'll be warned about this camera again"+ else "No more alerts for this camera (tap it again to undo)", Toast.LENGTH_SHORT).show()+ onChanged()+ }+ .setNegativeButton("Close", null)+ .setNeutralButton("Open in OpenStreetMap") { _, _ ->+ runCatching { a.startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${cam.osmId}"))) }+ }+ .show()+ }++ fun showTower(a: AppCompatActivity, t: com.rfsentinel.app.service.CellTowerStore.Tower) {+ val net = listOfNotNull(t.operator, "${t.mcc ?: "?"}-${t.mnc ?: "?"}").joinToString(" · ")+ val dateFmt = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.MEDIUM, java.text.DateFormat.SHORT)+ AlertDialog.Builder(a)+ .setTitle(t.ratLabel)+ .setMessage("$net\nArea ${t.area ?: "?"} · Cell ${t.cellId}" ++ (t.bestDbm?.let { "\nStrongest signal $it dBm" } ?: "") ++ "\nSeen ${t.timesSeen}×, last ${dateFmt.format(java.util.Date(t.lastSeen))}" ++ "\n\nPlaced where your phone heard it strongest: an estimate, not the tower's exact position.")+ .setPositiveButton("All towers") { _, _ -> a.startActivity(Intent(a, CellTowersActivity::class.java)) }+ .setNegativeButton("Close", null)+ .show()+ }+}++/** Shapes on the map, as (lat, lon) rings (closed: the last point repeats the first). */+internal object MapGeo {+ private const val EARTH_M = 6_371_000.0++ /** The point [distM] metres from ([lat], [lon]) towards [bearingDeg] (clockwise from north). */+ fun offset(lat: Double, lon: Double, distM: Double, bearingDeg: Double): Pair<Double, Double> {+ val d = distM / EARTH_M+ val b = Math.toRadians(bearingDeg)+ val la = Math.toRadians(lat); val lo = Math.toRadians(lon)+ val la2 = kotlin.math.asin(kotlin.math.sin(la) * kotlin.math.cos(d) + kotlin.math.cos(la) * kotlin.math.sin(d) * kotlin.math.cos(b))+ val lo2 = lo + kotlin.math.atan2(kotlin.math.sin(b) * kotlin.math.sin(d) * kotlin.math.cos(la),+ kotlin.math.cos(d) - kotlin.math.sin(la) * kotlin.math.sin(la2))+ return Math.toDegrees(la2) to Math.toDegrees(lo2)+ }++ /** A circle of [radiusM] around a point. */+ fun circle(lat: Double, lon: Double, radiusM: Double, n: Int = 48): List<Pair<Double, Double>> =+ (0..n).map { offset(lat, lon, radiusM, 360.0 * (it % n) / n) }++ /** A wedge from a point: [sweepDeg] wide around [dirDeg], [rangeM] long (a CCTV camera's view). */+ fun wedge(lat: Double, lon: Double, dirDeg: Double, sweepDeg: Double, rangeM: Double): List<Pair<Double, Double>> {+ if (sweepDeg >= 359.0) return circle(lat, lon, rangeM)+ val steps = (sweepDeg / 6).toInt().coerceAtLeast(4)+ val arc = (0..steps).map { offset(lat, lon, rangeM, dirDeg - sweepDeg / 2 + sweepDeg * it / steps) }+ return listOf(lat to lon) + arc + listOf(lat to lon)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapStart.kt b/app/src/main/java/com/rfsentinel/app/ui/MapStart.ktindex 1f9e86c..deec03c 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapStart.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapStart.kt@@ -33,6 +33,23 @@ object MapStart {return null}+ /**+ * The levels here (and the zoom saved in Prefs) are the classic raster map's; the vector map+ * shows the same scale one level lower (its tiles are 512 pixels).+ */+ const val VECTOR_SHIFT = 1.0++ /** Where the vector map's camera first looks (its zoom level). */+ data class Camera(val lat: Double, val lon: Double, val zoom: Double, val fresh: Boolean)++ /** [pick] as the map's camera: your area at street zoom, else a world view when nothing is known. */+ fun camera(fixes: List<Fix?>, saved: Pair<Double, Double>?, savedZoom: Double?, now: Long): Camera =+ pick(fixes, saved, savedZoom, now)?.let { Camera(it.lat, it.lon, it.zoom - VECTOR_SHIFT, it.fresh) }+ ?: Camera(30.0, 0.0, WORLD_ZOOM - VECTOR_SHIFT, fresh = false)++ /** The vector map's zoom as it is saved (the classic levels, so a saved view means the same scale). */+ fun savedZoom(vectorZoom: Double) = vectorZoom + VECTOR_SHIFT+/** (0, 0) is what a missing position looks like; it is never a real place to start from. */private fun isOrigin(lat: Double, lon: Double) = abs(lat) < 1e-4 && abs(lon) < 1e-4}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.ktnew file mode 100644index 0000000..4ee64d8--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt@@ -0,0 +1,326 @@+package com.rfsentinel.app.ui++import android.content.Context+import android.graphics.Bitmap+import android.graphics.RectF+import android.location.Location+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.view.Gravity+import com.mapbox.android.gestures.MoveGestureDetector+import com.mapbox.android.gestures.StandardScaleGestureDetector+import com.mapbox.bindgen.Value+import com.mapbox.common.Cancelable+import com.mapbox.common.MapboxOptions+import com.mapbox.common.TelemetryUtils+import com.mapbox.geojson.Point+import com.mapbox.maps.CameraBoundsOptions+import com.mapbox.maps.CameraOptions+import com.mapbox.maps.EdgeInsets+import com.mapbox.maps.MapInitOptions+import com.mapbox.maps.MapView+import com.mapbox.maps.RenderedQueryGeometry+import com.mapbox.maps.RenderedQueryOptions+import com.mapbox.maps.ScreenBox+import com.mapbox.maps.ScreenCoordinate+import com.mapbox.maps.Style+import com.mapbox.maps.extension.style.sources.generated.GeoJsonSource+import com.mapbox.maps.extension.style.sources.getSourceAs+import com.mapbox.maps.plugin.Plugin+import com.mapbox.maps.plugin.PuckBearing+import com.mapbox.maps.plugin.animation.MapAnimationOptions+import com.mapbox.maps.plugin.animation.easeTo+import com.mapbox.maps.plugin.attribution.attribution+import com.mapbox.maps.plugin.compass.compass+import com.mapbox.maps.plugin.gestures.OnMoveListener+import com.mapbox.maps.plugin.gestures.OnScaleListener+import com.mapbox.maps.plugin.gestures.gestures+import com.mapbox.maps.plugin.locationcomponent.LocationConsumer+import com.mapbox.maps.plugin.locationcomponent.LocationProvider+import com.mapbox.maps.plugin.locationcomponent.createDefault2DPuck+import com.mapbox.maps.plugin.locationcomponent.location+import com.mapbox.maps.plugin.logo.logo+import com.mapbox.maps.plugin.scalebar.scalebar+import com.mapbox.maps.plugin.viewport.ViewportStatus+import com.mapbox.maps.plugin.viewport.data.DefaultViewportTransitionOptions+import com.mapbox.maps.plugin.viewport.data.FollowPuckViewportStateBearing+import com.mapbox.maps.plugin.viewport.data.FollowPuckViewportStateOptions+import com.mapbox.maps.plugin.viewport.data.ViewportOptions+import com.mapbox.maps.plugin.viewport.state.FollowPuckViewportState+import com.mapbox.maps.plugin.viewport.viewport+import com.mapbox.maps.toCameraOptions+import com.rfsentinel.app.BuildConfig+import com.rfsentinel.app.util.Permissions+import org.json.JSONObject+import java.util.concurrent.CopyOnWriteArraySet++/**+ * [MapEngine] on Mapbox's own SDK and its Standard map (day / night light, 3D buildings). Needs the+ * app's Mapbox token; Mapbox's own usage telemetry is switched off. Mapbox's logo and info button+ * stay on the map, as its terms require.+ */+internal class MapboxEngine(private val context: Context) : MapEngine {++ override val provider = MapEngine.Provider.MAPBOX+ override val credit = "© Mapbox © OpenStreetMap contributors"+ override val labelFont = listOf("Open Sans Regular", "Arial Unicode MS Regular")++ // Mapbox's documented way to turn its usage telemetry off (the library marks it internal).+ @android.annotation.SuppressLint("RestrictedApi")+ private fun telemetryOff() = runCatching { TelemetryUtils.setEventsCollectionState(false) { } }++ init {+ MapboxOptions.accessToken = BuildConfig.MAPBOX_TOKEN+ telemetryOff() // before any map exists+ }++ // The screen forwards the lifecycle, as for MapLibre (no automatic lifecycle plugin).+ override val view = MapView(context, MapInitOptions(context,+ plugins = MapInitOptions.defaultPluginList.filter { it.id != Plugin.MAPBOX_LIFECYCLE_PLUGIN_ID }))+ private val map = view.mapboxMap+ private val main = Handler(Looper.getMainLooper())+ private var style: Style? = null+ private var dark = false+ private val subscriptions = ArrayList<Cancelable>()+ private var destroyed = false++ override var onCameraMove: (() -> Unit)? = null+ override var onIdle: (() -> Unit)? = null+ override var onClick: ((Float, Float) -> Unit)? = null+ override var onUserGesture: (() -> Unit)? = null+ override var onFollowDismissed: (() -> Unit)? = null++ override fun onCreate(state: Bundle?) {}+ override fun onStart() { if (!destroyed) view.onStart() }+ override fun onResume() { if (!destroyed) view.onResume() }+ override fun onPause() {}+ override fun onStop() { if (!destroyed) view.onStop() }+ override fun onLowMemory() { if (!destroyed) view.onLowMemory() }+ override fun onSaveInstanceState(out: Bundle) {}+ override fun onDestroy() {+ if (destroyed) return+ destroyed = true+ subscriptions.forEach { runCatching { it.cancel() } }; subscriptions.clear()+ style = null+ view.onDestroy()+ }++ override fun whenReady(ready: () -> Unit) {+ view.compass.enabled = false // the map button shows (and sets) north up+ view.scalebar.enabled = false // the app's own scale+ view.viewport.options = ViewportOptions.Builder().transitionsToIdleUponUserInteraction(false).build()+ subscriptions += map.subscribeCameraChanged { onCameraMove?.invoke() }+ subscriptions += map.subscribeMapIdle { onIdle?.invoke() }+ view.gestures.addOnMapClickListener { point ->+ val p = map.pixelForCoordinate(point)+ onClick?.invoke(p.x.toFloat(), p.y.toFloat())+ false+ }+ view.gestures.addOnMoveListener(object : OnMoveListener {+ override fun onMoveBegin(detector: MoveGestureDetector) {+ onUserGesture?.invoke()+ // One finger: you're looking elsewhere - stop following (a pinch keeps it).+ if (following() && detector.pointersCount <= 1) { view.viewport.idle(); followMode = MapEngine.Follow.NONE; onFollowDismissed?.invoke() }+ }+ override fun onMove(detector: MoveGestureDetector) = false+ override fun onMoveEnd(detector: MoveGestureDetector) {}+ })+ view.gestures.addOnScaleListener(object : OnScaleListener {+ override fun onScaleBegin(detector: StandardScaleGestureDetector) {+ // Your zoom from now on: following no longer sets one.+ followState?.let { s -> if (following()) s.options = s.options.toBuilder().zoom(null).build() }+ onUserGesture?.invoke()+ }+ override fun onScale(detector: StandardScaleGestureDetector) {}+ override fun onScaleEnd(detector: StandardScaleGestureDetector) {}+ })+ ready()+ }++ // ---- style ----++ override fun setStyle(dark: Boolean, loaded: (Boolean) -> Unit) {+ this.dark = dark+ val current = style+ if (current != null && current.isValid()) {+ // The Standard map turns night by its light, without reloading (your view stays as it is).+ lightPreset(current)+ loaded(false)+ return+ }+ map.loadStyle(Style.STANDARD) { s ->+ if (destroyed) return@loadStyle+ style = s+ lightPreset(s)+ loaded(true)+ }+ }++ private fun lightPreset(s: Style) {+ runCatching { s.setStyleImportConfigProperty("basemap", "lightPreset", Value.valueOf(if (dark) "night" else "day")) }+ }++ private fun live(): Style? = style?.takeIf { !destroyed && it.isValid() }+ override val styleLoaded get() = live() != null+ override fun hasSource(id: String) = live()?.styleSourceExists(id) == true+ override fun addImage(id: String, bitmap: Bitmap) { live()?.addImage(id, bitmap) }++ override fun addSource(id: String) {+ val s = live() ?: return+ s.addStyleSource(id, json("""{"type":"geojson","data":${GeoJson.EMPTY}}""")).error?.let { throw IllegalStateException(it) }+ }++ override fun setData(source: String, geoJson: String) { live()?.getSourceAs<GeoJsonSource>(source)?.data(geoJson) }++ override fun addLayer(json: JSONObject) {+ val s = live() ?: return+ s.addStyleLayer(json(json.toString()), null).error?.let { throw IllegalStateException(it) }+ }++ override fun setPaint(layer: String, name: String, value: String) {+ live()?.setStyleLayerProperty(layer, name, Value.valueOf(value))+ }++ private fun json(text: String): Value = Value.fromJson(text).let { it.value ?: throw IllegalArgumentException(it.error) }++ // ---- camera ----++ override val camera: MapEngine.Camera get() {+ val c = map.cameraState+ return MapEngine.Camera(c.center.latitude(), c.center.longitude(), c.zoom, c.bearing, c.pitch)+ }++ override fun jumpTo(lat: Double, lon: Double, zoom: Double?) {+ map.setCamera(CameraOptions.Builder().center(Point.fromLngLat(lon, lat)).zoom(zoom).build())+ }++ override fun zoomTo(zoom: Double) { map.setCamera(CameraOptions.Builder().zoom(zoom).build()) }++ override fun easeTo(lat: Double?, lon: Double?, zoom: Double?, bearing: Double?, tilt: Double?, flat: Boolean, ms: Long) {+ val b = CameraOptions.Builder()+ if (lat != null && lon != null) b.center(Point.fromLngLat(lon, lat))+ b.zoom(zoom).bearing(bearing).pitch(tilt)+ if (flat) b.padding(EdgeInsets(0.0, 0.0, 0.0, 0.0))+ map.easeTo(b.build(), MapAnimationOptions.mapAnimationOptions { duration(ms) })+ }++ override fun fit(points: List<Pair<Double, Double>>, paddingPx: Int) {+ if (points.isEmpty()) return+ if (points.size == 1) { jumpTo(points[0].first, points[0].second); return }+ val p = paddingPx.toDouble()+ val cam = map.cameraForCoordinates(points.map { Point.fromLngLat(it.second, it.first) },+ CameraOptions.Builder().bearing(0.0).pitch(0.0).build(), EdgeInsets(p, p, p, p), null, null)+ map.setCamera(cam)+ }++ override fun visibleBox(): MapEngine.Box? = runCatching {+ val b = map.coordinateBoundsForCamera(map.cameraState.toCameraOptions())+ MapEngine.Box(b.north(), b.east(), b.south(), b.west())+ }.getOrNull()++ override fun toLatLon(x: Float, y: Float): Pair<Double, Double>? =+ runCatching { map.coordinateForPixel(ScreenCoordinate(x.toDouble(), y.toDouble())) }.getOrNull()?.let { it.latitude() to it.longitude() }++ override fun setMinZoom(zoom: Double) { map.setBounds(CameraBoundsOptions.Builder().minZoom(zoom).build()) }++ override fun query(box: RectF, layers: List<Pair<String, String>>, result: (List<List<String>>) -> Unit) {+ // Asynchronous here: every layer is asked, the answer comes once all have replied.+ val answers = arrayOfNulls<List<String>>(layers.size)+ var left = layers.size+ if (left == 0) return result(emptyList())+ val geometry = RenderedQueryGeometry(ScreenBox(ScreenCoordinate(box.left.toDouble(), box.top.toDouble()),+ ScreenCoordinate(box.right.toDouble(), box.bottom.toDouble())))+ layers.forEachIndexed { i, (layer, key) ->+ map.queryRenderedFeatures(geometry, RenderedQueryOptions(listOf(layer), null)) { found ->+ val ids = found.value?.mapNotNull { f ->+ val feature = f.queriedFeature.feature+ if (feature.hasProperty(key)) feature.getStringProperty(key) else null+ } ?: emptyList()+ main.post {+ answers[i] = ids+ if (--left == 0 && !destroyed) result(answers.map { it ?: emptyList() })+ }+ }+ }+ }++ // ---- your position ----++ /** Your fixes, from the screen's own GPS (as on MapLibre: the screen keeps the heading steady). */+ private val fixes = object : LocationProvider {+ val consumers = CopyOnWriteArraySet<LocationConsumer>()+ var last: Location? = null+ override fun registerLocationConsumer(locationConsumer: LocationConsumer) {+ consumers += locationConsumer+ last?.let { send(locationConsumer, it) }+ }+ override fun unRegisterLocationConsumer(locationConsumer: LocationConsumer) { consumers -= locationConsumer }+ fun send(c: LocationConsumer, fix: Location) {+ c.onLocationUpdated(Point.fromLngLat(fix.longitude, fix.latitude))+ if (fix.hasBearing()) c.onBearingUpdated(fix.bearing.toDouble())+ }+ }+ private var puck = false+ override val puckOn get() = puck && !destroyed++ override fun startPuck(): Boolean {+ if (destroyed) return false+ if (!Permissions.granted(context, android.Manifest.permission.ACCESS_FINE_LOCATION)) return false+ if (!puck) {+ view.location.apply {+ setLocationProvider(fixes)+ locationPuck = createDefault2DPuck(withBearing = true)+ puckBearing = PuckBearing.COURSE+ puckBearingEnabled = true+ enabled = true+ }+ puck = true+ }+ return true+ }++ override fun pushFix(fix: Location) {+ fixes.last = fix+ fixes.consumers.forEach { fixes.send(it, fix) }+ }++ private var followState: FollowPuckViewportState? = null+ private var followMode = MapEngine.Follow.NONE+ private fun following() = followMode != MapEngine.Follow.NONE++ override fun follow(mode: MapEngine.Follow, topPaddingPx: Double?, tilt: Double, zoom: Double?, ms: Long) {+ if (!puckOn) return+ val vp = view.viewport+ followMode = mode+ if (mode == MapEngine.Follow.NONE) { vp.idle(); return }+ val options = FollowPuckViewportStateOptions.Builder()+ .padding(EdgeInsets(topPaddingPx ?: (followState?.options?.padding?.top ?: 0.0), 0.0, 0.0, 0.0))+ .pitch(tilt)+ .zoom(zoom)+ .bearing(if (mode == MapEngine.Follow.HEADING) FollowPuckViewportStateBearing.SyncWithLocationPuck+ else FollowPuckViewportStateBearing.Constant(0.0))+ .build()+ val state = followState ?: vp.makeFollowPuckViewportState(options).also { followState = it }+ state.options = options+ val status = vp.status+ if (status is ViewportStatus.State && status.state === state) return+ val transition = if (ms <= 0) vp.makeImmediateViewportTransition()+ else vp.makeDefaultViewportTransition(DefaultViewportTransitionOptions.Builder().maxDurationMs(ms).build())+ vp.transitionTo(state, transition, null)+ }++ private var brandingTop = -1++ override fun placeBranding(topPx: Int) {+ if (topPx == brandingTop) return // only when it moved: setting it again asks for another layout pass+ brandingTop = topPx+ val d = context.resources.displayMetrics.density+ view.logo.position = Gravity.TOP or Gravity.START+ view.logo.marginTop = topPx.toFloat()+ view.logo.marginLeft = 8 * d+ view.attribution.position = Gravity.TOP or Gravity.START+ view.attribution.marginTop = topPx.toFloat()+ view.attribution.marginLeft = 96 * d+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/NightLabels.kt b/app/src/main/java/com/rfsentinel/app/ui/NightLabels.ktnew file mode 100644index 0000000..c046167--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/NightLabels.kt@@ -0,0 +1,29 @@+package com.rfsentinel.app.ui++/**+ * Map details the OpenFreeMap night style doesn't draw but the light map does (one-way arrows, river and+ * lake names, path names, highway shields, airports): the light map's own layer definitions (same+ * tiles, icons and zoom levels), with night colours. Shops and landmarks are added in code.+ */+internal object NightLabels {++ private const val NAME = """["case",["has","name:nonlatin"],["concat",["get","name:latin"]," ",["get","name:nonlatin"]],["coalesce",["get","name_en"],["get","name"]]]"""+ private const val NAME_LINES = """["case",["has","name:nonlatin"],["concat",["get","name:latin"],"\n",["get","name:nonlatin"]],["coalesce",["get","name_en"],["get","name"]]]"""+ private const val PAINT = """"paint":{"text-color":"#D3DCEC","text-halo-color":"#1C2436","text-halo-width":1.6}"""+ private const val LINE = """"symbol-placement":"line","text-rotation-alignment":"map""""+ private const val LINES = """["match",["geometry-type"],["LineString","MultiLineString"],true,false]"""+ private const val SHIELD_LAYOUT = """"icon-rotation-alignment":"viewport","icon-size":1,"symbol-spacing":200,"text-field":["to-string",["get","ref"]],"text-font":["Noto Sans Regular"],"text-rotation-alignment":"viewport","text-size":10"""++ val layers: List<String> = listOf(+ """{"id":"night-oneway","type":"symbol","source":"openmaptiles","source-layer":"transportation","minzoom":16,"filter":["==",["get","oneway"],1],"layout":{"icon-image":"arrow","symbol-placement":"line"}}""",+ """{"id":"night-oneway-back","type":"symbol","source":"openmaptiles","source-layer":"transportation","minzoom":16,"filter":["==",["get","oneway"],-1],"layout":{"icon-image":"arrow","icon-rotate":180,"symbol-placement":"line"}}""",+ """{"id":"night-waterway-label","type":"symbol","source":"openmaptiles","source-layer":"waterway","minzoom":10,"filter":$LINES,"layout":{"symbol-placement":"line","symbol-spacing":350,"text-field":$NAME,"text-font":["Noto Sans Italic"],"text-letter-spacing":0.2,"text-max-width":5,"text-size":14},$PAINT}""",+ """{"id":"night-water-point-label","type":"symbol","source":"openmaptiles","source-layer":"water_name","filter":["match",["geometry-type"],["MultiPoint","Point"],true,false],"layout":{"text-field":$NAME_LINES,"text-font":["Noto Sans Italic"],"text-letter-spacing":0.2,"text-max-width":5,"text-size":["interpolate",["linear"],["zoom"],0,10,8,14]},$PAINT}""",+ """{"id":"night-path-name","type":"symbol","source":"openmaptiles","source-layer":"transportation_name","minzoom":15.5,"filter":["==",["get","class"],"path"],"layout":{$LINE,"text-field":$NAME,"text-font":["Noto Sans Regular"],"text-size":["interpolate",["linear"],["zoom"],13,12,14,13]},$PAINT}""",+ """{"id":"night-airport","type":"symbol","source":"openmaptiles","source-layer":"aerodrome_label","minzoom":10,"filter":["all",["has","iata"]],"layout":{"icon-image":"airport_11","icon-size":1,"text-anchor":"top","text-field":$NAME_LINES,"text-font":["Noto Sans Regular"],"text-max-width":9,"text-offset":[0,0.6],"text-optional":true,"text-padding":2,"text-size":12},$PAINT}""",+ // Shields keep the light map's look: dark text on the light badge (not recoloured at night).+ """{"id":"night-shield-other","type":"symbol","source":"openmaptiles","source-layer":"transportation_name","minzoom":8,"filter":["all",["<=",["get","ref_length"],6],$LINES,["match",["get","network"],["us-highway","us-interstate","us-state"],false,true]],"layout":{"icon-image":["concat","road_",["get","ref_length"]],"symbol-placement":["step",["zoom"],"point",11,"line"],$SHIELD_LAYOUT}}""",+ """{"id":"night-shield-interstate","type":"symbol","source":"openmaptiles","source-layer":"transportation_name","minzoom":7,"filter":["all",["<=",["get","ref_length"],6],$LINES,["match",["get","network"],["us-interstate"],true,false]],"layout":{"icon-image":["concat",["get","network"],"_",["get","ref_length"]],"symbol-placement":["step",["zoom"],"point",7,"line",8,"line"],$SHIELD_LAYOUT}}""",+ """{"id":"night-shield-us","type":"symbol","source":"openmaptiles","source-layer":"transportation_name","minzoom":9,"filter":["all",["<=",["get","ref_length"],6],$LINES,["match",["get","network"],["us-highway","us-state"],true,false]],"layout":{"icon-image":["concat",["get","network"],"_",["get","ref_length"]],"symbol-placement":["step",["zoom"],"point",11,"line"],$SHIELD_LAYOUT}}"""+ )+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/PointsOverlay.kt b/app/src/main/java/com/rfsentinel/app/ui/PointsOverlay.ktdeleted file mode 100644index 4dc85f1..0000000--- a/app/src/main/java/com/rfsentinel/app/ui/PointsOverlay.kt+++ /dev/null@@ -1,84 +0,0 @@-package com.rfsentinel.app.ui--import android.graphics.Bitmap-import android.graphics.Canvas-import android.graphics.Paint-import android.view.MotionEvent-import org.osmdroid.util.GeoPoint-import org.osmdroid.views.MapView-import org.osmdroid.views.overlay.Overlay--/**- * Draws many points straight onto the map canvas, each centred exactly on its- * coordinate and re-projected on every frame, so points stay pinned to the map- * while it pans, zooms or rotates (no per-point Marker objects lagging behind,- * no fanning out). Idea from Wardrive Go's markers overlay (GPL-3.0), written- * for RF Sentinel's point styles.- *- * A tap reports every point under the finger, nearest first, so points heard from- * the same spot can be picked from a list instead of being spread apart.- */-class PointsOverlay<T>(- private val density: Float,- private val onTap: (List<T>) -> Unit-) : Overlay() {-- /** One point: a filled dot with a ring, or an [icon] bitmap centred on the coordinate. */- class Point<T>(- val lat: Double,- val lon: Double,- val payload: T,- val color: Int = 0,- val sizeDp: Float = 16f,- val ringColor: Int = 0xFFFFFFFF.toInt(),- val icon: Bitmap? = null,- val alpha: Int = 255- )-- @Volatile var points: List<Point<T>> = emptyList()-- private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }- private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }- private val bitmapPaint = Paint(Paint.FILTER_BITMAP_FLAG)- private val px = android.graphics.Point()- private val tapRadius = 22f * density-- override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) {- if (shadow) return- val proj = mapView.projection- val margin = 40 * density- val w = mapView.width; val h = mapView.height- for (p in points) {- proj.toPixels(GeoPoint(p.lat, p.lon), px)- // Rotation and scaling are applied to the canvas by osmdroid; cull generously.- val x = px.x.toFloat(); val y = px.y.toFloat()- if (x < -w - margin || y < -h - margin || x > 2 * w + margin || y > 2 * h + margin) continue- val icon = p.icon- if (icon != null) {- bitmapPaint.alpha = p.alpha- canvas.drawBitmap(icon, x - icon.width / 2f, y - icon.height / 2f, bitmapPaint)- } else {- val r = p.sizeDp * density / 2- ring.color = p.ringColor; ring.alpha = p.alpha- canvas.drawCircle(x, y, r, ring)- fill.color = p.color; fill.alpha = p.alpha- canvas.drawCircle(x, y, r - 2 * density, fill)- }- }- }-- override fun onSingleTapConfirmed(e: MotionEvent, mapView: MapView): Boolean {- val proj = mapView.projection- val hits = ArrayList<Pair<Float, T>>()- for (p in points) {- proj.toPixels(GeoPoint(p.lat, p.lon), px)- val r = maxOf(tapRadius, (p.icon?.width ?: 0) / 2f, p.sizeDp * density / 2)- val dx = e.x - px.x; val dy = e.y - px.y- val d2 = dx * dx + dy * dy- if (d2 <= r * r) hits += d2 to p.payload- }- if (hits.isEmpty()) return false- onTap(hits.sortedBy { it.first }.map { it.second })- return true- }-}diff --git a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt b/app/src/main/java/com/rfsentinel/app/ui/RfMap.ktnew file mode 100644index 0000000..ff13a97--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt@@ -0,0 +1,424 @@+package com.rfsentinel.app.ui++import android.graphics.RectF+import androidx.appcompat.app.AppCompatActivity+import androidx.lifecycle.lifecycleScope+import com.rfsentinel.app.alpr.AlprStore+import com.rfsentinel.app.alpr.Cctv+import com.rfsentinel.app.alpr.CctvStore+import com.rfsentinel.app.alpr.KnownCamera+import com.rfsentinel.app.online.PoliceAircraft+import com.rfsentinel.app.online.WazePolice+import com.rfsentinel.app.service.CellTowerStore+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.service.TripRecorder+import com.rfsentinel.app.util.Prefs+import kotlinx.coroutines.launch+import org.json.JSONArray+import org.json.JSONObject++/**+ * RF Sentinel's map on its [MapEngine] (OpenFreeMap or Mapbox): the light or night style, and every+ * layer drawn on it - devices and their pinpoint circles, plate / speed / red-light cameras, CCTV+ * with their view, cell towers, drones, police aircraft, Waze reports and the trace - with the same+ * details on a tap as before. The screen around it ([MapFragment]) owns the buttons, the camera+ * and your position; this owns what is drawn.+ */+internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine) {++ companion object {+ const val TRACE_COLOR = "#E0622D"+ const val PAST_TRACE_COLOR = "#1F5FBF"+ private const val DRONE_COLOR = "#1F5FBF"+ /** Vector zoom levels sit ~1 below the old raster map's for the same scale (512-pixel tiles). */+ const val CAMERAS_MIN_ZOOM = 8.0+ private const val CCTV_MIN_ZOOM = 11.0+ private const val CCTV_CONE_ZOOM = 14.0++ private const val PRECISION = "rf-precision"; private const val CONES = "rf-cctv-cones"+ private const val TRACE = "rf-trace"; private const val DRONE_LINES = "rf-drone-lines"+ private const val TOWERS = "rf-towers"; private const val CCTV = "rf-cctv"; private const val CAMERAS = "rf-cameras"+ private const val DEVICES = "rf-devices"; private const val DOTS = "rf-device-dots"; private const val LABELS = "rf-device-labels"+ private const val WAZE = "rf-waze"; private const val DRONE_OPS = "rf-drone-ops"; private const val DRONES = "rf-drones"+ private const val AIRCRAFT = "rf-aircraft"++ /**+ * North, east, south, west of a box grown by [fraction] on every side, clamped to valid+ * latitudes and longitudes (a view of the whole world would otherwise pass the poles).+ */+ internal fun grownBox(north: Double, east: Double, south: Double, west: Double, fraction: Double): List<Double> {+ val dLat = (north - south) * fraction; val dLon = (east - west) * fraction+ return listOf((north + dLat).coerceIn(-85.0, 85.0), (east + dLon).coerceIn(-180.0, 180.0),+ (south - dLat).coerceIn(-85.0, 85.0), (west - dLon).coerceIn(-180.0, 180.0))+ }++ private fun hex(argb: Int) = String.format("#%06X", argb and 0xFFFFFF)++ /** Map style JSON: an object (null values left out) and an array / expression. */+ internal fun o(vararg kv: Pair<String, Any?>) = JSONObject().apply { for ((k, v) in kv) if (v != null) put(k, v) }+ internal fun a(vararg v: Any) = JSONArray().apply { v.forEach { put(it) } }+ }++ /** A saved trace is shown (no live layers; its own pins and route). */+ var tripMode = false+ var filter = DeviceFilter.ALL+ var isDark = false; private set+ /** What the CCTV layer is doing, for the status line (null while the layer is off). */+ var cctvLine: String? = null; private set+ /** Cell towers with a position (the Cells chip's count). */+ var towerCount = 0; private set+ /** After a camera download or an ignore changed what's on the map. */+ var onStaticChanged: (() -> Unit)? = null++ // What's on the map now, to find what a tap hit.+ private var pins: Map<String, MapPin> = emptyMap()+ private var wazeShown: Map<String, WazePolice.Shown> = emptyMap()+ private var planes: Map<String, PoliceAircraft.Seen> = emptyMap()+ private var drones: Map<String, DeviceRegistry.Snapshot> = emptyMap()+ private var cameras: Map<String, KnownCamera> = emptyMap()+ private var cctvs: Map<String, com.rfsentinel.app.alpr.CctvCamera> = emptyMap()+ private var towers: Map<String, CellTowerStore.Tower> = emptyMap()+ /** The area the camera, CCTV and tower layers were drawn for (redrawn when the view leaves it). */+ private var staticBox: MapEngine.Box? = null+ private var staticAt = 0L+ private var lastCameraFetch = 0L+ private var lastCctvFetch = 0L++ /** Loads the light or night style; [onLoaded] once its layers are in. */+ fun loadStyle(dark: Boolean, onLoaded: () -> Unit) {+ isDark = dark+ map.setStyle(dark) { fresh ->+ if (activity.isFinishing || activity.isDestroyed) return@setStyle+ if (fresh || !map.hasSource(DEVICES)) safe("style") {+ addImages()+ addLayers(dark)+ } else safe("style") {+ // The same map turned night (Mapbox): the labels' colours follow.+ val (ink, halo) = labelColors(dark)+ map.setPaint(LABELS, "text-color", ink); map.setPaint(LABELS, "text-halo-color", halo)+ }+ staticBox = null+ safe("loaded") { onLoaded() }+ }+ }++ /**+ * Runs [block] and keeps whatever it throws here: map callbacks run inside the map engine,+ * where an exception aborts the whole app instead of failing one drawing.+ */+ inline fun safe(what: String, block: () -> Unit) {+ try { block() } catch (e: Exception) { android.util.Log.w("RfMap", "$what failed", e) }+ }++ /** The same icons as before. */+ private fun addImages() {+ val dp = activity.resources.displayMetrics.density+ KnownCamera.Kind.entries.forEach { map.addImage("rf-cam-${it.name}", MapIcons.cameraIcon(dp, it)) }+ map.addImage("rf-cctv-public", MapIcons.cctvIcon(dp, false))+ map.addImage("rf-cctv-private", MapIcons.cctvIcon(dp, true))+ map.addImage("rf-plane-police", MapIcons.planeIcon(dp, true))+ map.addImage("rf-plane", MapIcons.planeIcon(dp, false))+ map.addImage("rf-tower", MapIcons.towerIcon(dp))+ map.addImage("rf-drone", droneArrow(dp))+ }++ /** Every layer, as map style JSON (the same on both engines). */+ private fun addLayers(dark: Boolean) {+ listOf(PRECISION, CONES, TRACE, DRONE_LINES, TOWERS, CCTV, CAMERAS, DEVICES, WAZE, DRONE_OPS, DRONES, AIRCRAFT)+ .forEach { map.addSource(it) }+ fun get(k: String) = a("get", k)+ val color = a("to-color", get("color"))+ val flagged = a("==", get("flagged"), true)+ val font = JSONArray(map.labelFont)+ val (ink, halo) = labelColors(dark)+ val overlap = arrayOf<Pair<String, Any?>>("icon-allow-overlap" to true, "icon-ignore-placement" to true)+ fun layer(id: String, type: String, source: String = id, minzoom: Double? = null, filter: JSONArray? = null,+ layout: JSONObject? = null, paint: JSONObject? = null) =+ o("id" to id, "type" to type, "source" to source, "minzoom" to minzoom, "filter" to filter, "layout" to layout, "paint" to paint)+ listOf(+ // Pinpointed devices: the circle each is very likely in, in its colour.+ layer("$PRECISION-fill", "fill", PRECISION, paint = o("fill-color" to color, "fill-opacity" to 0.18)),+ layer("$PRECISION-line", "line", PRECISION, paint = o("line-color" to color, "line-width" to 1.5, "line-opacity" to 0.7)),+ // What each CCTV camera watches (zoomed in).+ layer("$CONES-fill", "fill", CONES, minzoom = CCTV_CONE_ZOOM, paint = o("fill-color" to color, "fill-opacity" to get("opacity"))),+ layer(TRACE, "line", layout = o("line-cap" to "round", "line-join" to "round"),+ paint = o("line-color" to color, "line-width" to 5.0)),+ layer(DRONE_LINES, "line", paint = o("line-color" to DRONE_COLOR, "line-width" to 2.5, "line-dasharray" to a(4.0, 2.5))),+ layer(TOWERS, "symbol", layout = o("icon-image" to "rf-tower", *overlap)),+ layer(CCTV, "symbol", minzoom = CCTV_MIN_ZOOM, layout = o("icon-image" to get("icon"), *overlap)),+ // Plate, speed and red-light cameras; the ones whose alerts you turned off, faded.+ layer(CAMERAS, "symbol", minzoom = CAMERAS_MIN_ZOOM, layout = o("icon-image" to get("icon"), *overlap),+ paint = o("icon-opacity" to get("opacity"))),+ // Devices: flagged ones bigger and on top, in the same colours as the list.+ layer(DOTS, "circle", DEVICES, layout = o("circle-sort-key" to a("case", flagged, 1.0, 0.0)),+ paint = o("circle-color" to color, "circle-radius" to a("case", flagged, 8.0, 5.0),+ "circle-stroke-color" to "#FFFFFF", "circle-stroke-width" to 1.5)),+ layer(LABELS, "symbol", DEVICES, filter = flagged,+ layout = o("text-field" to get("label"), "text-font" to font, "text-size" to 12.0, "text-anchor" to "top",+ "text-offset" to a(0.0, 1.1), "text-optional" to true),+ paint = o("text-color" to ink, "text-halo-color" to halo, "text-halo-width" to 1.5)),+ // Waze reports: blue police, red accident, orange hazard, brown closure, purple jam.+ layer(WAZE, "circle", paint = o("circle-color" to color, "circle-radius" to 9.0,+ "circle-stroke-color" to "#FFFFFF", "circle-stroke-width" to 2.0)),+ // A drone's operator / take-off point, and the drone pointing its way.+ layer(DRONE_OPS, "circle", paint = o("circle-color" to "#F5E100", "circle-radius" to 7.0,+ "circle-stroke-color" to DRONE_COLOR, "circle-stroke-width" to 2.0)),+ layer(DRONES, "symbol", layout = o("icon-image" to "rf-drone", "icon-rotate" to get("dir"),+ "icon-rotation-alignment" to "map", *overlap)),+ // Aircraft: police / government ones bold purple with their agency and altitude, others small and grey.+ layer(AIRCRAFT, "symbol", layout = o("icon-image" to get("icon"), "icon-rotate" to get("track"),+ "icon-rotation-alignment" to "map",+ "icon-size" to a("interpolate", a("linear"), a("zoom"), 9, 0.5, 12, 1.0, 16, 2.0),+ *overlap, "symbol-sort-key" to a("case", flagged, 1.0, 0.0),+ "text-field" to get("label"), "text-font" to font, "text-size" to 12.0, "text-anchor" to "top",+ "text-offset" to a(0.0, 1.6), "text-optional" to true),+ paint = o("text-color" to "#FFFFFF", "text-halo-color" to hex(MapIcons.POLICE_AIRCRAFT_COLOR), "text-halo-width" to 3.0))+ ).forEach { map.addLayer(it) }+ }++ /** Device labels: text and halo colours on the light or night map. */+ private fun labelColors(dark: Boolean) = if (dark) "#FFFFFF" to "#1B1F27" else "#1B1F27" to "#FFFFFF"++ private fun ready() = map.styleLoaded++ private fun set(source: String, features: List<JSONObject>) {+ map.setData(source, GeoJson.collection(features))+ }++ /** Devices (and their pinpoint circles); returns what was drawn. */+ fun drawPins(shown: List<MapPin>) {+ if (!ready()) return+ pins = shown.associateBy { it.mac }+ set(DEVICES, shown.map { p ->+ GeoJson.feature(GeoJson.point(p.lat, p.lon), "mac" to p.mac, "label" to p.label.take(32),+ "color" to hex(p.color), "flagged" to p.flagged)+ })+ set(PRECISION, shown.filter { it.radiusM != null }.map { p ->+ GeoJson.feature(GeoJson.polygon(MapGeo.circle(p.lat, p.lon, p.radiusM!!)), "color" to hex(p.color))+ })+ }++ /** A route: the trace being recorded (orange) or a saved one (blue). */+ fun drawTrace(points: List<Pair<Double, Double>>, color: String) {+ if (!ready()) return+ set(TRACE, if (points.size < 2) emptyList() else listOf(GeoJson.feature(GeoJson.line(points), "color" to color)))+ }++ /**+ * Fast-changing live layers, every few seconds: devices, Waze, drones, aircraft, the trace.+ * Returns the devices drawn.+ */+ fun drawLive(devices: List<DeviceRegistry.Snapshot>): List<MapPin> {+ if (!ready()) return emptyList()+ val shown = MapPins.live(activity, devices, filter)+ drawPins(shown)++ val waze = if (filter == DeviceFilter.ALL || filter == DeviceFilter.WAZE) WazePolice.latest else emptyList()+ wazeShown = waze.associateBy { it.report.id }+ set(WAZE, waze.map { w ->+ GeoJson.feature(GeoJson.point(w.report.lat, w.report.lon), "id" to w.report.id, "color" to hex(w.report.type.color))+ })++ val flying = devices.filter { it.remoteId?.hasPosition == true }+ drones = flying.associateBy { it.mac }+ set(DRONES, flying.map { s ->+ val r = s.remoteId!!+ GeoJson.feature(GeoJson.point(r.latitude!!, r.longitude!!), "mac" to s.mac, "dir" to (r.directionDeg ?: 0).toDouble())+ })+ val withOperator = flying.filter { it.remoteId!!.hasOperatorPosition }+ set(DRONE_OPS, withOperator.map { s ->+ val r = s.remoteId!!+ GeoJson.feature(GeoJson.point(r.operatorLatitude!!, r.operatorLongitude!!), "mac" to s.mac)+ })+ set(DRONE_LINES, withOperator.map { s ->+ val r = s.remoteId!!+ GeoJson.feature(GeoJson.line(listOf(r.operatorLatitude!! to r.operatorLongitude!!, r.latitude!! to r.longitude!!)))+ })++ val fresh = System.currentTimeMillis() - PoliceAircraft.latestAt <= 3 * 60_000L+ val air = if (fresh) PoliceAircraft.latest else emptyList()+ planes = air.associateBy { it.plane.hex }+ set(AIRCRAFT, air.map { (p, hit) ->+ GeoJson.feature(GeoJson.point(p.lat, p.lon),+ "hex" to p.hex,+ "icon" to if (hit != null) "rf-plane-police" else "rf-plane",+ "track" to (p.trackDeg ?: 0.0),+ "flagged" to (hit != null),+ "label" to if (hit == null) "" else listOfNotNull(+ hit.label.substringAfter(": ", hit.label).take(28), p.altitudeFt?.takeIf { it > 0 }?.let { "$it ft" }+ ).joinToString(" · "))+ })++ val trace = if (TripRecorder.isRecording) TripRecorder.livePoints() else emptyList()+ drawTrace(trace.map { it.lat to it.lon }, TRACE_COLOR)+ return shown+ }++ /**+ * Cameras, CCTV and cell towers: many, and they don't move - drawn for the area in view (and+ * around it), again once the view leaves that area or every 15 s for new downloads.+ */+ fun maybeRedrawStatic(force: Boolean = false) {+ if (!ready()) return+ if (tripMode) { clearStatic(); return }+ towerCount = CellTowerStore.all(activity).count { it.bestLat != null }+ if (map.camera.zoom < CAMERAS_MIN_ZOOM) {+ if (force) clearStatic()+ updateCctvLine(null)+ return+ }+ val view = map.visibleBox() ?: return+ val now = System.currentTimeMillis()+ val box = staticBox+ if (!force && box != null && box.contains(view) && now - staticAt < 15_000) return+ val (n, e, so, w) = grownBox(view.north, view.east, view.south, view.west, 0.5)+ val big = MapEngine.Box(n, e, so, w)+ staticBox = big; staticAt = now+ fun inside(lat: Double, lon: Double) = big.contains(lat, lon)++ val cams = if (Prefs.showKnownAlpr(activity)) AlprStore.cameras.filter { inside(it.lat, it.lon) }.take(1500) else emptyList()+ cameras = cams.associateBy { it.osmId }+ set(CAMERAS, cams.map { c ->+ GeoJson.feature(GeoJson.point(c.lat, c.lon), "id" to c.osmId, "icon" to "rf-cam-${c.type.name}",+ "opacity" to if (com.rfsentinel.app.alpr.IgnoredCameras.contains(activity, c.osmId)) 0.35 else 1.0)+ })++ val showCctv = Prefs.showCctv(activity)+ val private = Prefs.cctvPrivate(activity)+ val cctv = if (showCctv && map.camera.zoom >= CCTV_MIN_ZOOM)+ CctvStore.cameras.filter { (private || !it.isPrivate) && inside(it.lat, it.lon) }.take(3000) else emptyList()+ cctvs = cctv.associateBy { it.osmId }+ set(CCTV, cctv.map { c ->+ GeoJson.feature(GeoJson.point(c.lat, c.lon), "id" to c.osmId, "icon" to if (c.isPrivate) "rf-cctv-private" else "rf-cctv-public")+ })+ set(CONES, cctv.mapNotNull { c ->+ val color = hex(if (c.isPrivate) MapIcons.CCTV_PRIVATE_COLOR else MapIcons.CCTV_PUBLIC_COLOR)+ val range = Cctv.viewRangeM(c)+ val dir = c.direction+ val ring = when {+ dir != null -> MapGeo.wedge(c.lat, c.lon, dir.toDouble(), Cctv.viewAngle(c).toDouble(), range)+ // No direction: only domes / panning cameras get a (fainter, smaller) all-round area.+ c.cameraType == "dome" || c.cameraType == "panning" -> MapGeo.circle(c.lat, c.lon, range * 0.6, 24)+ else -> return@mapNotNull null+ }+ GeoJson.feature(GeoJson.polygon(ring), "color" to color, "opacity" to if (dir != null) 0.2 else 0.1)+ })+ updateCctvLine(if (!showCctv) null else view)++ val showTowers = filter == DeviceFilter.CELLS || (filter == DeviceFilter.ALL && Prefs.showCellTowers(activity))+ val tw = if (showTowers) CellTowerStore.all(activity).filter { it.bestLat != null } else emptyList()+ towers = tw.associateBy { it.key }+ set(TOWERS, tw.map { t ->+ GeoJson.feature(GeoJson.point(t.bestLat!!, t.bestLon!!), "id" to t.key)+ })++ maybeFetchCameras(view)+ }++ private fun clearStatic() {+ listOf(CAMERAS, CCTV, CONES, TOWERS).forEach { set(it, emptyList()) }+ cameras = emptyMap(); cctvs = emptyMap(); towers = emptyMap(); staticBox = null+ }++ /** The CCTV layer's state for the status line, as before; [view] null = the layer is off. */+ private fun updateCctvLine(view: MapEngine.Box?) {+ if (!Prefs.showCctv(activity) || tripMode) { cctvLine = null; return }+ val store = CctvStore+ if (view == null) {+ cctvLine = store.progress?.let { "CCTV: downloading around you, $it" } ?: "CCTV: zoom in to see the cameras"+ return+ }+ val private = Prefs.cctvPrivate(activity)+ fun inView(c: com.rfsentinel.app.alpr.CctvCamera) = view.contains(c.lat, c.lon)+ val shown = cctvs.values.count { inView(it) }+ val hiddenPrivate = if (private) 0 else store.cameras.count { it.isPrivate && inView(it) }+ cctvLine = when {+ map.camera.zoom < CCTV_MIN_ZOOM -> store.progress?.let { "CCTV: downloading around you, $it" } ?: "CCTV: zoom in to see the cameras"+ store.progress != null -> "CCTV: downloading around you, ${store.progress}"+ store.isBusy -> "CCTV: downloading..."+ System.currentTimeMillis() - store.lastFailureAt < 60_000 -> "CCTV: map server busy - retrying"+ store.missingAreas > 0 && shown > 0 -> "CCTV: $shown in view - ${store.missingAreas} area(s) around you still missing (servers busy), retried next time"+ shown == 0 && store.needsDownload(view.south, view.west, view.north, view.east) -> "CCTV: downloading..."+ shown == 0 && hiddenPrivate > 0 -> "CCTV: only private ones here ($hiddenPrivate) - Settings > Known cameras > Include private"+ shown == 0 -> null // nothing to say: no banner+ else -> "CCTV: $shown in view" + if (hiddenPrivate > 0) " (+$hiddenPrivate private hidden)" else ""+ }+ }++ /**+ * Fetches the plate / speed cameras of the area in view when they aren't cached yet, and the CCTV+ * around you and in view; at most every 20 s so following you at speed doesn't hammer the servers.+ */+ private fun maybeFetchCameras(view: MapEngine.Box) {+ val now = System.currentTimeMillis()+ val span = AlprStore.MAX_SPAN_DEG+ val small = view.north - view.south <= span && view.east - view.west <= span+ if (Prefs.showCctv(activity) && now - lastCctvFetch > 20_000 && !CctvStore.isBusy) {+ lastCctvFetch = now+ val here = ScanForegroundService.lastFix+ if (here != null) CctvStore.ensureAround(activity, here.latitude, here.longitude, Prefs.cameraRadiusKm(activity).toDouble())+ if (!CctvStore.isBusy && small && map.camera.zoom >= CCTV_MIN_ZOOM) activity.lifecycleScope.launch {+ runCatching { CctvStore.autoDownload(activity, view.south, view.west, view.north, view.east) }+ safe("static") { maybeRedrawStatic(force = true); onStaticChanged?.invoke() }+ }+ }+ if (now - lastCameraFetch < 20_000) return+ if (!Prefs.autoCameras(activity) || !Prefs.showKnownAlpr(activity) || AlprStore.isBusy || !small) return+ lastCameraFetch = now+ activity.lifecycleScope.launch {+ val changed = runCatching {+ AlprStore.autoDownload(activity, view.south, view.west, view.north, view.east)+ }.getOrDefault(false)+ if (changed) safe("static") { maybeRedrawStatic(force = true); onStaticChanged?.invoke() }+ }+ }++ /** What's under the finger: the topmost kind of thing wins; several devices at one spot give a list. */+ fun onTap(x: Float, y: Float, me: Pair<Double, Double>?) {+ val r = 22f * activity.resources.displayMetrics.density+ val box = RectF(x - r, y - r, x + r, y + r)+ val asked = listOf(AIRCRAFT to "hex", WAZE to "id", DRONES to "mac", DRONE_OPS to "mac", DOTS to "mac",+ CAMERAS to "id", CCTV to "id", TOWERS to "id")+ map.query(box, asked) { found ->+ if (activity.isFinishing || activity.isDestroyed) return@query+ safe("tap") { showTapped(found, me) }+ }+ }++ private fun showTapped(found: List<List<String>>, me: Pair<Double, Double>?) {+ val (air, waze, drone, op, dots, cams, cctv, tower) = found+ air.firstNotNullOfOrNull { planes[it] }?.let { s -> MapDialogs.showAircraft(activity, s.plane, s.hit, me); return }+ waze.firstNotNullOfOrNull { wazeShown[it] }?.let { MapDialogs.showWaze(activity, it); return }+ (drone + op).firstNotNullOfOrNull { drones[it] }?.let { s ->+ MapDialogs.showDrone(activity, s.mac, MapDialogs.droneDetails(s, s.remoteId!!)); return+ }+ val here = dots.distinct().mapNotNull { pins[it] }+ if (here.isNotEmpty()) { MapDialogs.showPins(activity, here); return }+ cams.firstNotNullOfOrNull { cameras[it] }?.let { c -> MapDialogs.showKnownCamera(activity, c) { maybeRedrawStatic(force = true) }; return }+ cctv.firstNotNullOfOrNull { cctvs[it] }?.let { MapDialogs.showCctv(activity, it); return }+ tower.firstNotNullOfOrNull { towers[it] }?.let { MapDialogs.showTower(activity, it) }+ }++ private operator fun <T> List<T>.component6() = this[5]+ private operator fun <T> List<T>.component7() = this[6]+ private operator fun <T> List<T>.component8() = this[7]++ /** Opens what an aircraft / Waze link points at, when it's on the map now. */+ fun showAircraft(seen: PoliceAircraft.Seen, me: Pair<Double, Double>?) = MapDialogs.showAircraft(activity, seen.plane, seen.hit, me)++ /** A blue arrow pointing north, turned to the drone's heading by the layer. */+ private fun droneArrow(dp: Float): android.graphics.Bitmap {+ val size = (30 * dp).toInt()+ val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)+ val c = android.graphics.Canvas(bmp)+ val path = android.graphics.Path().apply {+ moveTo(size / 2f, 2 * dp); lineTo(size - 5 * dp, size - 4 * dp)+ lineTo(size / 2f, size * 0.68f); lineTo(5 * dp, size - 4 * dp); close()+ }+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)+ c.drawPath(path, paint.apply { color = android.graphics.Color.parseColor(DRONE_COLOR); style = android.graphics.Paint.Style.FILL })+ c.drawPath(path, paint.apply { color = android.graphics.Color.WHITE; style = android.graphics.Paint.Style.STROKE; strokeWidth = 2 * dp })+ return bmp+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/ScaleBarView.kt b/app/src/main/java/com/rfsentinel/app/ui/ScaleBarView.ktnew file mode 100644index 0000000..85aaebf--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/ScaleBarView.kt@@ -0,0 +1,58 @@+package com.rfsentinel.app.ui++import android.content.Context+import android.graphics.Canvas+import android.graphics.Paint+import android.util.AttributeSet+import android.view.View++/** The map's scale: a bar of a round distance (50 m, 200 m, 1 km...) no wider than [maxWidthDp]. */+class ScaleBarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {++ companion object {+ /** The roundest distance (1, 2 or 5 x 10^n metres) that fits in [maxMeters]. */+ internal fun niceMeters(maxMeters: Double): Double {+ if (maxMeters <= 0.0) return 0.0+ val p = Math.pow(10.0, kotlin.math.floor(kotlin.math.log10(maxMeters)))+ return listOf(5.0, 2.0, 1.0).map { it * p }.first { it <= maxMeters }+ }++ internal fun label(meters: Double): String =+ if (meters >= 1000) "${(meters / 1000).let { if (it % 1.0 == 0.0) it.toInt().toString() else "%.1f".format(it) }} km"+ else "${meters.toInt()} m"+ }++ private val dp = resources.displayMetrics.density+ private val maxWidthDp = 100f+ private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = 0xFF333333.toInt(); strokeWidth = 2 * dp; strokeCap = Paint.Cap.ROUND }+ private val halo = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = 0xCCFFFFFF.toInt(); strokeWidth = 5 * dp; strokeCap = Paint.Cap.ROUND }+ private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = 0xFF333333.toInt(); textSize = 11 * dp; isFakeBoldText = true }+ private val textHalo = Paint(text).apply { color = 0xCCFFFFFF.toInt(); style = Paint.Style.STROKE; strokeWidth = 3 * dp }+ private var barPx = 0f+ private var caption = ""++ /** Metres per screen pixel at the map's centre. */+ fun setMetersPerPixel(mpp: Double) {+ val meters = niceMeters(mpp * maxWidthDp * dp)+ val px = if (mpp > 0) (meters / mpp).toFloat() else 0f+ val cap = label(meters)+ if (px == barPx && cap == caption) return+ barPx = px; caption = cap+ invalidate()+ }++ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) =+ setMeasuredDimension(((maxWidthDp + 12) * dp).toInt(), (28 * dp).toInt())++ override fun onDraw(canvas: Canvas) {+ if (barPx <= 0f) return+ val x0 = 4 * dp; val y = height - 6 * dp+ for (p in listOf(halo, line)) {+ canvas.drawLine(x0, y, x0 + barPx, y, p)+ canvas.drawLine(x0, y, x0, y - 6 * dp, p)+ canvas.drawLine(x0 + barPx, y, x0 + barPx, y - 6 * dp, p)+ }+ canvas.drawText(caption, x0 + 3 * dp, y - 8 * dp, textHalo)+ canvas.drawText(caption, x0 + 3 * dp, y - 8 * dp, text)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.ktindex 8f0c839..85e5cf2 100644--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt@@ -266,7 +266,7 @@ class SetupActivity : AppCompatActivity() {Prefs.setCellChangeAlerts(this, it)}para("Extra hardware works on its own once plugged in while scanning: ESP32 boards (OUI-Spy, GhostESP, Marauder - also ESP32-C5 boards for 5 GHz, and a Flipper Zero with its ESP32 board) " +- "and USB WiFi adapters (RTL8811AU / 8821AU such as the ALFA AWUS036ACS, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070 or, experimental, AR9271 - ALFA AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH, AWUS036NHA), and an RTL-SDR dongle to hear two-way radios transmitting nearby (signal strength only, nothing decoded). An OUI-SPY board over Bluetooth is paired in Settings.", small = true)+ "and USB WiFi adapters (RTL8811AU / 8821AU such as the ALFA AWUS036ACS, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070 or, experimental, AR9271 and the WiFi 6E MT7921AU - ALFA AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH, AWUS036NHA, AWUS036AXML), and an RTL-SDR dongle to hear two-way radios transmitting nearby (signal strength only, nothing decoded). An OUI-SPY board over Bluetooth is paired in Settings.", small = true)}private fun permissions() {diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.ktindex e7de0a1..301839d 100644--- a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt@@ -221,11 +221,12 @@ class MonitorFrames {private const val MAX_PROBED = 16- /** Centre frequency of a 20 MHz WiFi channel, 0 when unknown. */+ /** Centre frequency of a 20 MHz WiFi channel, 0 when unknown; a 6 GHz channel comes as its MHz already. */fun frequencyOf(ch: Int): Int = when (ch) {in 1..13 -> 2407 + ch * 514 -> 2484in 32..177 -> 5000 + ch * 5+ in 5955..7115 -> chelse -> 0}diff --git a/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.ktnew file mode 100644index 0000000..62615cc--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt@@ -0,0 +1,665 @@+package com.rfsentinel.app.usb++/*+ * Receive-only monitor mode for MediaTek MT7921AU USB WiFi 6E adapters (e.g. ALFA+ * AWUS036AXML, Comfast CF-952AX, Netgear A8000 / A7500, TP-Link TXE50UH): 2.4, 5 and+ * 6 GHz, driven from userspace over Android's USB host API - no root, no kernel driver.+ * Loads MediaTek's ROM patch and RAM firmware (assets/usbwifi/WIFI_*MT7961*.bin, from+ * linux-firmware; licence in LICENCE.mediatek), puts the radio in sniffer mode, hops the+ * three bands (6 GHz on its 15 preferred scanning channels, where access points beacon)+ * and reports the access points and client devices it hears. It never transmits.+ *+ * Ported from mt76-usb-macos by Network Weather (https://github.com/Network-Weather/mt76-usb-macos,+ * BSD-3-Clause-Clear), a transcription of the MT7921 path of the Linux mt76 driver+ * (openwrt/mt76: Copyright (C) 2020-2023 MediaTek Inc., (C) 2018 Lorenzo Bianconi,+ * (C) 2016 Felix Fietkau; BSD-3-Clause-Clear). Changes here: Android USB host API instead+ * of IOKit, no USB port reset (Android apps can't; the WFSYS reset covers a re-run),+ * commands sent while receiving don't wait for their answer on the shared receive+ * endpoint (it's counted as it arrives), frames with a bad checksum are dropped (a+ * corrupted address would show up as a phantom device), and every transmit path+ * (frame injection, TX descriptors) was left out.+ */++import android.content.Context+import android.hardware.usb.UsbConstants+import android.hardware.usb.UsbDevice+import android.hardware.usb.UsbDeviceConnection+import android.hardware.usb.UsbEndpoint+import android.hardware.usb.UsbInterface+import android.hardware.usb.UsbManager++object Mt7921uMonitor {+ @Volatile var running = false; private set+ @Volatile private var stop = false++ private val frames = MonitorFrames()++ /** Band (0 = 2.4, 1 = 5, 2 = 6 GHz) and channel of each hop. 6 GHz: the preferred scanning channels. */+ internal val HOP: List<Pair<Int, Int>> =+ (1..13).map { 0 to it } ++ listOf(36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144,+ 149, 153, 157, 161, 165).map { 1 to it } ++ listOf(5, 21, 37, 53, 69, 85, 101, 117, 133, 149, 165, 181, 197, 213, 229).map { 2 to it }+ private const val DWELL_MS = 150L+ private val FRESH_MS get() = (HOP.size * DWELL_MS * 9 / 5).coerceAtLeast(3000L)+ private const val REPORT_MS = 10_000L++ // ---- USB vendor requests (mt76 usb.c) ----+ private const val TYPE_VENDOR = 0x40 or 0x1F // MT_USB_TYPE_VENDOR+ private const val TYPE_UHW_VENDOR = 0x40 or 0x1E // MT_USB_TYPE_UHW_VENDOR+ private const val DIR_IN = 0x80+ private const val VEND_DEV_MODE = 0x01; private const val VEND_WRITE = 0x02; private const val VEND_POWER_ON = 0x04+ private const val VEND_READ_EXT = 0x63; private const val VEND_WRITE_EXT = 0x66++ // ---- registers (mt792x_regs.h) ----+ private const val HW_CHIPID = 0x70010200; private const val HW_REV = 0x70010204+ private const val CHIP_ID_7961 = 0x7961+ private const val CONN_ON_MISC = 0x7C0600F0+ private const val TOP_MISC_FW_STATE = 0x7; private const val FW_PWR_ON = 1 shl 0; private const val FW_N9_RDY = 0x3+ private const val UDMA_TX_QSEL = 0x74000008; private const val FW_DL_EN = 1 shl 3+ private const val UDMA_WLCFG_0 = 0x74000018; private const val UDMA_WLCFG_1 = 0x7400000C+ private const val WL_RX_EN = 1 shl 22; private const val WL_TX_EN = 1 shl 23; private const val WL_RX_FLUSH = 1 shl 19+ private const val WL_RX_AGG_PKT_LMT = 0xFF; private const val WL_TX_TMOUT_LMT = 0x0FFFFF00+ private const val WL_RX_AGG_TO = 0xFF; private const val WL_RX_AGG_LMT = 0xFF00+ private const val WL_TX_TMOUT_FUNC_EN = 1 shl 16; private const val WL_RX_MPSZ_PAD0 = 1 shl 18; private const val TICK_1US_EN = 1 shl 20+ private const val USB_TX_TIMEOUT_LIMIT = 50000+ private const val WL_RX_BUSY = 1 shl 30; private const val WL_TX_BUSY = 1 shl 31+ private const val UDMA_CONN_INFRA_STATUS = 0x74000A20; private const val UDMA_CONN_WFSYS_INIT_DONE = 1 shl 22+ private const val UDMA_CONN_INFRA_STATUS_SEL = 0x74000A24+ private const val SSUSB_EPCTL_CSR_EP_RST_OPT = 0x74011800 + 0x090+ private const val UWFDMA0_GLO_CFG = 0x7C024000 + 0x208+ private const val GLO_TX_DMA_EN = 1 shl 0; private const val GLO_RX_DMA_EN = 1 shl 2; private const val GLO_RX_DMA_BUSY = 1 shl 3+ private const val GLO_FW_DWLD_BYPASS_DMASHDL = 1 shl 9; private const val GLO_OMIT_RX_INFO_PFET2 = 1 shl 21+ private const val GLO_OMIT_RX_INFO = 1 shl 27; private const val GLO_OMIT_TX_INFO = 1 shl 28+ private const val WFDMA_DUMMY_CR = 0x54000000 + 0x120; private const val WFDMA_NEED_REINIT = 1 shl 1+ private const val WFDMA_HOST_CONFIG = 0x7C027030; private const val HOST_CONFIG_USB_RXEVT_EP4_EN = 1 shl 6+ private const val DMA_SHDL = 0x7C026000+ private const val CBTOP_RGU_WF_SUBSYS_RST = 0x70002000 + 0x600; private const val WF_WHOLE_PATH = 1 shl 0+ private const val SWDEF_MODE = 0x41F200 + 0x3C++ // ---- MCU (mt76_connac_mcu.h, mt7921/mcu.c) ----+ internal const val CMD_TARGET_ADDRESS_LEN_REQ = 0x01; internal const val CMD_FW_START_REQ = 0x02+ internal const val CMD_NIC_POWER_CTRL = 0x04; internal const val CMD_PATCH_START_REQ = 0x05+ internal const val CMD_PATCH_FINISH_REQ = 0x07; internal const val CMD_PATCH_SEM_CONTROL = 0x10+ private const val CMD_FIELD_QUERY = 1 shl 16; private const val CMD_FIELD_CE = 1 shl 18; private const val CMD_FIELD_WA = 1 shl 19+ private const val EXT_CID = 0xED+ internal fun extCmd(id: Int) = EXT_CID or ((id shl 8) and 0xFF00)+ internal fun ceCmd(id: Int) = CMD_FIELD_CE or (id and 0xFF)+ internal const val EXT_CHANNEL_SWITCH = 0x08; internal const val EXT_EFUSE_BUFFER_MODE = 0x21+ internal const val CE_GET_NIC_CAPAB = 0x8A; internal const val CE_SET_RX_FILTER = 0x0A+ internal const val UNI_SNIFFER = 0x24+ private const val MCU_TXD_LEN = 64; private const val UNI_TXD_LEN = 48+ private const val MCU_PKT_ID = 0xA0; private const val Q_QUERY = 0; private const val Q_SET = 1; private const val Q_NA = 3+ private const val S2D_H2N = 0; private const val S2D_H2C = 2+ private const val UNI_EXT_ACK = 0x07+ private const val MCU_RXD_LEN = 36; private const val RXD_SEQ_OFFSET = 29; private const val RXD_STATUS_OFFSET = 32+ private const val PATCH_IS_DL = 1; private const val PATCH_NOT_DL_SEM_SUCCESS = 2+ private const val FW_SCATTER_MAX = 4096+ private const val PATCH_ADDR = 0x900000++ // Monitor filters (mt7921/main.c configure_filter, mt76_connac2 RFCR bits).+ /** Enable | pass FCS failures | control | other BSS - frames with a bad checksum are still dropped in [parseRx]. */+ internal const val MONITOR_FILTER = (1 shl 31) or (1 shl 2) or (1 shl 5) or (1 shl 6)+ internal const val FIF_BIT_CLR = 1 shl 1+ /** Every RFCR "drop" bit a monitor clears (not FCS failures). */+ internal const val MONITOR_DROP_CLEAR = (1 shl 0) or (1 shl 3) or (1 shl 4) or (1 shl 5) or (1 shl 6) or (1 shl 7) or+ (1 shl 8) or (1 shl 9) or (1 shl 10) or (1 shl 11) or (1 shl 13) or (1 shl 16) or (1 shl 17) or (1 shl 18) or+ (1 shl 19) or (1 shl 21)++ // ---- RX descriptor (mt76_connac2_mac.h) ----+ private const val PKT_TYPE_NORMAL = 2; private const val PKT_TYPE_RX_EVENT = 7; private const val PKT_FLAG_NORMAL_MCU = 1+ private const val RXD1_FCS_ERR = 1 shl 27+ private const val RXD2_HDR_TRANS = 1 shl 13; private const val RXD2_AMSDU_ERR = 1 shl 23; private const val RXD2_MAX_LEN_ERROR = 1 shl 24++ private lateinit var conn: UsbDeviceConnection+ private lateinit var epRx: UsbEndpoint+ private lateinit var epCmd: UsbEndpoint+ private lateinit var epData: UsbEndpoint+ private var seq = 0+ @Volatile private var ctlErrors = 0+ private var cmdsSent = 0; private var cmdsAnswered = 0++ fun abort() { stop = true }++ fun run(ctx: Context, device: UsbDevice, chipName: String, onStatus: (String) -> Unit,+ onFrame: (List<MonitorSighting>) -> Unit) {+ if (running) return+ running = true; stop = false; frames.clear(); ctlErrors = 0; seq = 0; cmdsSent = 0; cmdsAnswered = 0+ val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager+ val c = mgr.openDevice(device) ?: run { onStatus("$chipName: couldn't reopen adapter"); running = false; return }+ conn = c+ try {+ UsbWifi.log("=== MT7921AU bring-up (mt76 mt7921u) ===")+ // The WiFi function is the vendor-class interface with 2 bulk IN and 6 bulk OUT endpoints+ // (the others on these adapters are Bluetooth); roles by position, as mt76u_set_endpoints.+ val intf = wifiInterface(device) ?: run {+ UsbWifi.log("MT7921AU: no interface with class ff/ff/ff and 2 bulk IN + 6 bulk OUT endpoints")+ onStatus("$chipName: WiFi interface not found"); return+ }+ if (!c.claimInterface(intf, true)) UsbWifi.log("MT7921AU: couldn't claim the USB interface (continuing)")+ val (ins, outs) = bulkEndpoints(intf)+ epRx = ins[0]; epCmd = outs[0]; epData = outs[1]+ UsbWifi.log("MT7921AU: interface ${intf.id}, bulk IN [${ins.joinToString { "0x%02x".format(it.address) }}] " ++ "OUT [${outs.joinToString { "0x%02x".format(it.address) }}]")+ val t0 = System.currentTimeMillis()++ val chip = rr(HW_CHIPID) and 0xffff+ UsbWifi.log("MT7921AU: chip 0x%04x rev 0x%08x".format(chip, rr(HW_REV)))+ if (chip != CHIP_ID_7961) { onStatus("$chipName: not an MT7921 (chip %04x)".format(chip)); return }++ onStatus("$chipName · loading firmware…")+ val patch = ctx.assets.open("usbwifi/WIFI_MT7961_patch_mcu_1_2_hdr.bin").use { it.readBytes() }+ val ram = ctx.assets.open("usbwifi/WIFI_RAM_CODE_MT7961_1.bin").use { it.readBytes() }+ val err = bringUp(patch, ram)+ if (err != null) { onStatus("$chipName: $err (replug)"); return }++ onStatus("$chipName · starting monitor mode…")+ // Monitor: receive everything (other networks, control frames), sniffer on.+ mcuCmd(ceCmd(CE_SET_RX_FILTER), rxFilterPayload(MONITOR_FILTER, 0, 0), wait = false)+ mcuCmd(ceCmd(CE_SET_RX_FILTER), rxFilterPayload(0, FIF_BIT_CLR, MONITOR_DROP_CLEAR), wait = false)+ if (!mcuUni(UNI_SNIFFER, snifferEnablePayload(true), wait = true)) UsbWifi.log("MT7921AU: sniffer mode not acknowledged (continuing)")+ val (band0, ch0) = HOP[0]+ tune(band0, ch0, wait = true)+ UsbWifi.log("MT7921AU: started in %d ms - CONN_ON_MISC 0x%08x WLCFG_0 0x%08x, USB errors %d - monitor live ch %d".format(+ System.currentTimeMillis() - t0, rr(CONN_ON_MISC), rr(UDMA_WLCFG_0), ctlErrors, ch0))+ onStatus("$chipName · live · 2.4 + 5 + 6 GHz monitor")+ rxLoop(chipName, onFrame, onStatus)+ } catch (e: Exception) {+ UsbWifi.log("MT7921AU: bring-up error - ${UsbWifi.describe(e)}")+ onStatus("$chipName: error · ${e.message}")+ } finally {+ runCatching { c.close() }+ running = false+ }+ }++ private fun wifiInterface(d: UsbDevice): UsbInterface? = (0 until d.interfaceCount).map { d.getInterface(it) }.firstOrNull { i ->+ i.interfaceClass == 0xff && i.interfaceSubclass == 0xff && i.interfaceProtocol == 0xff &&+ bulkEndpoints(i).let { (ins, outs) -> ins.size >= 2 && outs.size >= 6 }+ }++ private fun bulkEndpoints(i: UsbInterface): Pair<List<UsbEndpoint>, List<UsbEndpoint>> {+ val ins = ArrayList<UsbEndpoint>(); val outs = ArrayList<UsbEndpoint>()+ for (k in 0 until i.endpointCount) {+ val ep = i.getEndpoint(k)+ if (ep.type != UsbConstants.USB_ENDPOINT_XFER_BULK) continue+ if (ep.direction == UsbConstants.USB_DIR_IN) ins += ep else outs += ep+ }+ return ins to outs+ }++ // ---- bring-up (mt7921u_probe .. __mt7921_init_hardware) ----++ /** Null when the firmware runs, else what failed. */+ private fun bringUp(patch: ByteArray, ram: ByteArray): String? {+ val misc = rr(CONN_ON_MISC)+ UsbWifi.log("MT7921AU: CONN_ON_MISC 0x%08x".format(misc))+ // Still running from an earlier session (no replug in between): reset the WiFi subsystem first.+ if (misc and FW_N9_RDY != 0) {+ val ok = wfsysReset()+ UsbWifi.log("MT7921AU: WFSYS reset ${if (ok) "done" else "not confirmed"}, CONN_ON_MISC 0x%08x".format(rr(CONN_ON_MISC)))+ }+ ctl(TYPE_VENDOR, VEND_POWER_ON, 0, 1, null, 0)+ if (!poll(CONN_ON_MISC, FW_PWR_ON, FW_PWR_ON, 500)) return "MCU didn't power on"+ if (!dmaInit()) return "DMA didn't start"+ wr(SWDEF_MODE, 0) // normal operating mode, set before the firmware download+ setBits(UDMA_TX_QSEL, FW_DL_EN)+ mcuCmd(CMD_NIC_POWER_CTRL, byteArrayOf(1, 0, 0, 0), wait = false)+ if (!poll(CONN_ON_MISC, TOP_MISC_FW_STATE, FW_PWR_ON, 1000)) UsbWifi.log("MT7921AU: MCU not reporting ready for download (continuing)")+ loadPatch(patch)?.let { return it }+ loadRam(ram)?.let { return it }+ if (!poll(CONN_ON_MISC, FW_N9_RDY, FW_N9_RDY, 1500)) return "firmware didn't start"+ clearBits(UDMA_TX_QSEL, FW_DL_EN)+ UsbWifi.log("MT7921AU: firmware running")+ // 5 and 6 GHz stay silent until the firmware has the chip's calibration data.+ if (mcuCmd(ceCmd(CE_GET_NIC_CAPAB), ByteArray(0), wait = true) == null) return "no answer to the capability query"+ if (mcuCmd(extCmd(EXT_EFUSE_BUFFER_MODE), byteArrayOf(0, 1, 0, 0), wait = true) == null) return "calibration not accepted"+ UsbWifi.log("MT7921AU: calibration (efuse) pushed")+ return null+ }++ private fun dmaInit(): Boolean {+ // WFDMA prefetch rings and DMA scheduler (mt792xu_dma_init / mt792x_wfdma_init).+ intArrayOf(0, 1, 2, 3, 4, 16, 17).zip(intArrayOf(0x080, 0x0C0, 0x100, 0x140, 0x180, 0x280, 0x2C0)).forEach { (idx, base) ->+ rmw(0x7C024000 + 0x600 + (idx shl 2), 0xFF or 0xFFFF0000.toInt(), 4 or ((base shl 16) and 0xFFFF0000.toInt()))+ }+ clearBits(UWFDMA0_GLO_CFG, GLO_OMIT_RX_INFO)+ setBits(UWFDMA0_GLO_CFG, GLO_OMIT_TX_INFO or GLO_OMIT_RX_INFO_PFET2 or GLO_FW_DWLD_BYPASS_DMASHDL or GLO_TX_DMA_EN or GLO_RX_DMA_EN)+ rmw(DMA_SHDL + 0x010, 0xFFFF0000.toInt(), 0xFFE00000.toInt())+ clearBits(DMA_SHDL + 0x00C, 1 shl 16)+ rmw(DMA_SHDL + 0x01C, 0x00000FFF or 0x0FFF0000, 1)+ for (i in 0 until 5) wr(DMA_SHDL + 0x020 + (i shl 2), 0x3 or (0xFFF shl 16))+ for (i in 5 until 16) wr(DMA_SHDL + 0x020 + (i shl 2), 0)+ wr(DMA_SHDL + 0x060, 0x32013201); wr(DMA_SHDL + 0x064, 0x32013201)+ wr(DMA_SHDL + 0x068, 0x55555444); wr(DMA_SHDL + 0x06C, 0x55555444)+ wr(DMA_SHDL + 0x070, 0x76540132); wr(DMA_SHDL + 0x074, 0xFEDCBA98.toInt())+ setBits(WFDMA_DUMMY_CR, WFDMA_NEED_REINIT)+ // USB DMA: one frame per transfer (no RX aggregation).+ clearBits(UDMA_WLCFG_0, WL_RX_FLUSH)+ setBits(UDMA_WLCFG_0, WL_RX_EN or WL_TX_EN or WL_RX_MPSZ_PAD0 or TICK_1US_EN)+ rmw(UDMA_WLCFG_1, WL_TX_TMOUT_LMT, (USB_TX_TIMEOUT_LIMIT shl 8) and WL_TX_TMOUT_LMT)+ setBits(UDMA_WLCFG_0, WL_TX_TMOUT_FUNC_EN)+ clearBits(UDMA_WLCFG_0, WL_RX_AGG_TO or WL_RX_AGG_LMT)+ clearBits(UDMA_WLCFG_1, WL_RX_AGG_PKT_LMT)+ // Firmware answers arrive on the frame endpoint (EP4) from here on.+ if (!poll(UWFDMA0_GLO_CFG, GLO_RX_DMA_BUSY, 0, 1000)) return false+ clearBits(UWFDMA0_GLO_CFG, GLO_RX_DMA_EN)+ setBits(WFDMA_HOST_CONFIG, HOST_CONFIG_USB_RXEVT_EP4_EN)+ setBits(UWFDMA0_GLO_CFG, GLO_RX_DMA_EN)+ epctlRstOpt(false)+ return true+ }++ private fun epctlRstOpt(reset: Boolean) {+ val mask = 0x3F0 or 0x700000+ uhwRmw(SSUSB_EPCTL_CSR_EP_RST_OPT, mask, if (reset) mask else 0)+ }++ /** mt792xu_wfsys_reset with the MT7921 descriptor. */+ private fun wfsysReset(): Boolean {+ setBits(UDMA_WLCFG_0, WL_RX_FLUSH)+ poll(UDMA_WLCFG_0, WL_RX_BUSY or WL_TX_BUSY, 0, 1000)+ epctlRstOpt(false)+ uhwRmw(CBTOP_RGU_WF_SUBSYS_RST, 0, WF_WHOLE_PATH)+ sleep(1)+ uhwRmw(CBTOP_RGU_WF_SUBSYS_RST, WF_WHOLE_PATH, 0)+ uhwWr(UDMA_CONN_INFRA_STATUS_SEL, 0)+ repeat(2) {+ uhwRr(UDMA_CONN_INFRA_STATUS)?.let { if (it and UDMA_CONN_WFSYS_INIT_DONE != 0) return true }+ sleep(100)+ }+ return false+ }++ // ---- firmware ----++ internal data class PatchSection(val type: Int, val offs: Int, val addr: Int, val len: Int, val secInfo: Int)+ internal data class RamRegion(val addr: Int, val len: Int, val featureSet: Int)++ /** ROM patch: a 96-byte header, then one 64-byte descriptor per section (big-endian). Null when malformed. */+ internal fun parsePatch(b: ByteArray): List<PatchSection>? {+ if (b.size < 96) return null+ val n = be32(b, 44)+ if (n !in 1..16 || 96 + n * 64 > b.size) return null+ return (0 until n).map { i ->+ val s = 96 + i * 64+ PatchSection(be32(b, s), be32(b, s + 4), be32(b, s + 12), be32(b, s + 16), be32(b, s + 20))+ }.takeIf { secs -> secs.all { it.offs >= 0 && it.len >= 0 && it.offs.toLong() + it.len <= b.size } }+ }++ /** RAM firmware: regions described in a trailer (36 bytes, preceded by 40 per region, little-endian). Null when malformed. */+ internal fun parseRam(b: ByteArray): List<RamRegion>? {+ if (b.size < 36) return null+ val t = b.size - 36+ val n = b[t + 2].toInt() and 0xff+ if (n !in 1..32 || 36 + n * 40 > b.size) return null+ val regions = (0 until n).map { i ->+ val r = t - (n - i) * 40+ RamRegion(le32(b, r + 16), le32(b, r + 20), b[r + 24].toInt() and 0xff)+ }+ val payload = b.size.toLong() - 36 - n * 40+ return regions.takeIf { rs -> rs.all { it.len >= 0 } && rs.sumOf { it.len.toLong() } <= payload }+ }++ private fun loadPatch(blob: ByteArray): String? {+ val sem = mcuCmd(CMD_PATCH_SEM_CONTROL, le32Bytes(1), wait = true)?.let { it[RXD_STATUS_OFFSET].toInt() and 0xff } ?: -1+ if (sem == PATCH_IS_DL) { UsbWifi.log("MT7921AU: ROM patch already applied"); return null }+ if (sem != PATCH_NOT_DL_SEM_SUCCESS) return "no ROM patch semaphore ($sem)"+ try {+ val secs = parsePatch(blob) ?: return "ROM patch file malformed"+ UsbWifi.log("MT7921AU: ROM patch '${asciiz(blob, 0, 16)}', ${secs.size} section(s)")+ for (s in secs) {+ if (s.type and 0xFFFF != 0x2) return "ROM patch section type 0x%x".format(s.type)+ if (!initDownload(s.addr, s.len, patchDataMode(s.secInfo))) return "ROM patch download refused"+ if (!sendScatter(blob, s.offs, s.len)) return "ROM patch upload failed"+ }+ val st = mcuCmd(CMD_PATCH_FINISH_REQ, ByteArray(4), wait = true)?.let { it[RXD_STATUS_OFFSET].toInt() and 0xff } ?: -1+ if (st != 0) return "ROM patch not started ($st)"+ UsbWifi.log("MT7921AU: ROM patch applied")+ return null+ } finally {+ mcuCmd(CMD_PATCH_SEM_CONTROL, le32Bytes(0), wait = true)+ }+ }++ private fun loadRam(blob: ByteArray): String? {+ val regions = parseRam(blob) ?: return "firmware file malformed"+ val t = blob.size - 36+ UsbWifi.log("MT7921AU: firmware '${asciiz(blob, t + 7, 10)}' built '${asciiz(blob, t + 17, 15)}', ${regions.size} region(s)")+ var override = 0+ var offset = 0+ for (r in regions) {+ if (r.featureSet and (1 shl 5) != 0) override = r.addr // FW_FEATURE_OVERRIDE_ADDR+ if (r.featureSet and (1 shl 6) != 0) { offset += r.len; continue } // FW_FEATURE_NON_DL+ if (!initDownload(r.addr, r.len, ramDataMode(r.featureSet))) return "firmware download refused"+ if (!sendScatter(blob, offset, r.len)) return "firmware upload failed"+ offset += r.len+ }+ val option = if (override != 0) 1 else 0 // FW_START_OVERRIDE+ return if (mcuCmd(CMD_FW_START_REQ, le32Bytes(option) + le32Bytes(override), wait = true) == null) "firmware start not acknowledged" else null+ }++ internal fun patchDataMode(secInfo: Int): Int {+ var mode = 1 shl 31 // DL_MODE_NEED_RSP+ if (secInfo == -1) return mode // PATCH_SEC_NOT_SUPPORT+ when ((secInfo ushr 24) and 0xff) {+ 1 -> mode = mode or 1 or (((secInfo and 0x0F) shl 1) and 0x6) or (1 shl 3) // AES: encrypt, key index, reset IV+ 2 -> mode = mode or 1 or (1 shl 6) or (1 shl 3) // scramble+ }+ return mode+ }++ internal fun ramDataMode(featureSet: Int): Int {+ var mode = 1 shl 31+ if (featureSet and 1 != 0) mode = mode or 1 or (1 shl 3)+ if (featureSet and (1 shl 4) != 0) mode = mode or (1 shl 6)+ return mode or (((featureSet and 0x6) shr 1) shl 1)+ }++ private fun initDownload(addr: Int, len: Int, mode: Int): Boolean =+ mcuCmd(if (addr == PATCH_ADDR) CMD_PATCH_START_REQ else CMD_TARGET_ADDRESS_LEN_REQ,+ le32Bytes(addr) + le32Bytes(len) + le32Bytes(mode), wait = true) != null++ private fun sendScatter(blob: ByteArray, from: Int, len: Int): Boolean {+ var off = 0+ while (off < len) {+ val n = minOf(FW_SCATTER_MAX, len - off)+ val f = scatterFrame(blob, from + off, n)+ if (conn.bulkTransfer(epData, f, f.size, 3000) < 0) { UsbWifi.log("MT7921AU: upload failed at $off of $len B"); return false }+ off += n+ }+ return true+ }++ // ---- MCU commands ----++ private fun nextSeq(): Int { seq = (seq + 1) and 0xF; if (seq == 0) seq = 1; return seq }++ /** Sends [cmd] (a plain command id, or an EXT / CE command word); with [wait], its answer or null. */+ private fun mcuCmd(cmd: Int, payload: ByteArray, wait: Boolean): ByteArray? {+ val s = nextSeq()+ val f = cmdFrame(cmd, payload, s)+ cmdsSent+++ if (conn.bulkTransfer(epCmd, f, f.size, 3000) < 0) { ctlErrors++; return null }+ return if (wait) mcuWait(s) else EMPTY+ }++ private fun mcuUni(cid: Int, payload: ByteArray, wait: Boolean): Boolean {+ val s = nextSeq()+ val f = uniFrame(cid, payload, s)+ cmdsSent+++ if (conn.bulkTransfer(epCmd, f, f.size, 3000) < 0) { ctlErrors++; return false }+ return !wait || mcuWait(s) != null+ }++ private val EMPTY = ByteArray(0)++ /** The firmware's answer to [s], read off the receive endpoint (frames arriving meanwhile are skipped). */+ private fun mcuWait(s: Int, timeoutMs: Long = 3000): ByteArray? {+ val buf = ByteArray(16384)+ val end = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < end) {+ val n = conn.bulkTransfer(epRx, buf, buf.size, 500)+ if (n < MCU_RXD_LEN) continue+ if (eventSeq(buf, n) == s) { cmdsAnswered++; return buf.copyOf(n) }+ }+ UsbWifi.log("MT7921AU: no answer to command seq $s")+ return null+ }++ /** Frame on the wire: | le32 length | 64-byte MCU TXD | payload | padding to 4 + 4 zero bytes |. */+ internal fun cmdFrame(cmd: Int, payload: ByteArray, s: Int): ByteArray {+ val cid = cmd and 0xFF+ val ext = (cmd ushr 8) and 0xFF+ val setQuery = if (ext != 0 || cmd and CMD_FIELD_CE != 0) (if (cmd and CMD_FIELD_QUERY != 0) Q_QUERY else Q_SET) else Q_NA+ val s2d = if (cmd and CMD_FIELD_WA != 0) S2D_H2C else S2D_H2N+ val total = MCU_TXD_LEN + payload.size+ val f = ByteArray(padded(4 + total))+ putLe32(f, 0, total and 0xffff)+ txdHead(f, 4, total)+ putLe16(f, 4 + 34, (1 shl 15) or (0x20 shl 10)) // port MCU, queue RX_Q0+ f[4 + 36] = cid.toByte(); f[4 + 37] = MCU_PKT_ID.toByte(); f[4 + 38] = setQuery.toByte(); f[4 + 39] = s.toByte()+ f[4 + 41] = ext.toByte(); f[4 + 42] = s2d.toByte(); f[4 + 43] = (if (ext != 0) 1 else 0).toByte()+ System.arraycopy(payload, 0, f, 4 + MCU_TXD_LEN, payload.size)+ return f+ }++ /** A unified command: | le32 length | 48-byte UNI TXD | payload | padding |. */+ internal fun uniFrame(cid: Int, payload: ByteArray, s: Int): ByteArray {+ val total = UNI_TXD_LEN + payload.size+ val f = ByteArray(padded(4 + total))+ putLe32(f, 0, total and 0xffff)+ txdHead(f, 4, total)+ putLe16(f, 4 + 34, cid)+ f[4 + 37] = MCU_PKT_ID.toByte(); f[4 + 39] = s.toByte(); f[4 + 42] = S2D_H2N.toByte(); f[4 + 43] = UNI_EXT_ACK.toByte()+ System.arraycopy(payload, 0, f, 4 + UNI_TXD_LEN, payload.size)+ return f+ }++ /** A firmware chunk for the data endpoint: | le32 length | data | padding |. */+ internal fun scatterFrame(src: ByteArray, from: Int, len: Int): ByteArray {+ val f = ByteArray(padded(4 + len))+ putLe32(f, 0, len and 0xffff)+ System.arraycopy(src, from, f, 4, len)+ return f+ }++ /** TXD words 0-1 (length, command type, MCU port; long format, command header) and the inner length. */+ private fun txdHead(f: ByteArray, at: Int, total: Int) {+ putLe32(f, at, (total and 0xffff) or (2 shl 23) or (0x20 shl 25))+ putLe32(f, at + 4, (1 shl 31) or (1 shl 16))+ putLe16(f, at + 32, total - 32)+ }++ private fun padded(len: Int) = ((len + 3) and 3.inv()) + 4++ internal fun rxFilterPayload(fif: Int, bitOp: Int, bitmap: Int): ByteArray {+ val p = ByteArray(68)+ p[4] = (if (fif != 0) 1 else 2).toByte()+ putLe32(p, 8, fif); putLe32(p, 12, bitmap); p[16] = bitOp.toByte()+ return p+ }++ internal fun snifferEnablePayload(on: Boolean): ByteArray {+ val p = ByteArray(12)+ putLe16(p, 4, 0); putLe16(p, 6, 8); p[8] = (if (on) 1 else 0).toByte()+ return p+ }++ /** CHANNEL_SWITCH: 20 MHz on [ch] in [band] (0 = 2.4, 1 = 5, 2 = 6 GHz), two streams. */+ internal fun chanInfoPayload(band: Int, ch: Int): ByteArray {+ val p = ByteArray(76)+ p[0] = ch.toByte(); p[1] = ch.toByte(); p[2] = 0; p[3] = 2; p[4] = 2; p[10] = band.toByte()+ return p+ }++ /** Sniffer config TLV: same channel, 20 MHz, firmware drops frames with errors. */+ internal fun snifferConfigPayload(band: Int, ch: Int): ByteArray {+ val p = ByteArray(20)+ putLe16(p, 4, 1); putLe16(p, 6, 16)+ p[10] = (band + 1).toByte(); p[11] = 0; p[12] = ch.toByte(); p[13] = 0; p[14] = ch.toByte(); p[16] = 1+ return p+ }++ /** Hops: the answers are counted as they arrive on the receive endpoint ([wait] only before receiving starts). */+ private fun tune(band: Int, ch: Int, wait: Boolean) {+ mcuCmd(extCmd(EXT_CHANNEL_SWITCH), chanInfoPayload(band, ch), wait)+ mcuUni(UNI_SNIFFER, snifferConfigPayload(band, ch), wait)+ }++ // ---- receive ----++ /**+ * Where the 802.11 frame sits in a transfer, its signal in dBm (strongest antenna; null when the+ * descriptor has none) and the band (0 / 1 / 2) and channel it was received on.+ */+ internal data class Rx(val start: Int, val end: Int, val rssi: Int?, val band: Int, val channel: Int)++ /** The sequence number of a firmware answer (event) in this transfer, or null for anything else. */+ internal fun eventSeq(b: ByteArray, n: Int): Int? {+ if (n < MCU_RXD_LEN) return null+ val rxd0 = le32(b, 0)+ val type = (rxd0 ushr 27) and 0x1F+ val flag = (rxd0 ushr 16) and 0xF+ if (type != PKT_TYPE_RX_EVENT || flag == PKT_FLAG_NORMAL_MCU) return null+ return b[RXD_SEQ_OFFSET].toInt() and 0xff+ }++ /**+ * One transfer: | RXD (24) | optional groups 4, 1, 2, 3, 5 | header offset (2 x n) | 802.11 frame |,+ * ending at the RXD's own length. Null for anything but a received frame, a bad checksum or+ * a malformed descriptor ([onBad] says whether it was the checksum).+ */+ internal fun parseRx(b: ByteArray, n: Int, onBad: (Boolean) -> Unit = {}): Rx? {+ if (n < 24 || n > b.size) { onBad(false); return null }+ val rxd0 = le32(b, 0); val rxd1 = le32(b, 4); val rxd2 = le32(b, 8); val rxd3 = le32(b, 12)+ val type = (rxd0 ushr 27) and 0x1F+ val flag = (rxd0 ushr 16) and 0xF+ if (type != PKT_TYPE_NORMAL && !(type == PKT_TYPE_RX_EVENT && flag == PKT_FLAG_NORMAL_MCU)) return null+ if (rxd1 and RXD1_FCS_ERR != 0) { onBad(true); return null }+ if (rxd2 and (RXD2_AMSDU_ERR or RXD2_MAX_LEN_ERROR or RXD2_HDR_TRANS) != 0) { onBad(false); return null }+ val dmaLen = rxd0 and 0xffff+ val end = if (dmaLen in 1 until n) dmaLen else n+ // Groups in the order mt7921_mac_fill_rx reads them; group 5 needs group 3.+ val mask = (rxd1 ushr 11) and 31+ if (mask and 16 != 0 && mask and 4 == 0) { onBad(false); return null }+ var off = 24+ var g3 = -1; var g5 = -1+ for ((bit, size) in GROUPS) {+ if (mask and bit == 0) continue+ if (off + size > end) { onBad(false); return null }+ if (bit == 4) g3 = off+ if (bit == 16) g5 = off+ off += size+ }+ // Signal: RCPI per antenna (group 5 word 6, else group 3 word 1), to dBm as mt76's to_rssi;+ // an antenna that heard nothing reports 0 (or 255) and is left out.+ val rcpiWord = when { g5 >= 0 -> le32(b, g5 + 24); g3 >= 0 -> le32(b, g3 + 4); else -> null }+ val rssi = rcpiWord?.let { w ->+ (0 until 4).map { c -> (w ushr (8 * c)) and 0xff }.filter { it in 1..254 }+ .map { it / 2 - 110 }.filter { it < 0 }.maxOrNull()+ }+ val start = off + 2 * ((rxd2 ushr 14) and 0x3)+ if (end - start < 10) { onBad(false); return null }+ val chfreq = (rxd3 ushr 8) and 0xff+ val (band, ch) = when {+ chfreq > 180 -> 2 to (chfreq - 181) * 4 + 1+ chfreq > 14 -> 1 to chfreq+ else -> 0 to chfreq+ }+ return Rx(start, end, rssi, band, ch)+ }++ /** Optional RXD groups: bit in the group mask and size, in reading order (4, 1, 2, 3, 5). */+ private val GROUPS = listOf(8 to 16, 1 to 16, 2 to 8, 4 to 8, 16 to 72)++ /** The channel as [MonitorFrames] takes it: the number on 2.4 / 5 GHz, MHz on 6 GHz (its numbers overlap theirs). */+ internal fun monitorChannel(band: Int, ch: Int) = if (band == 2) 5950 + 5 * ch else ch++ private class RxState { var hopAt = 0L; var lastEmit = 0L; var lastRxAt = 0L; var lastCheck = 0L; var hopIdx = 0 }++ private fun rxLoop(chipName: String, onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {+ val st = RxState()+ val t0 = System.currentTimeMillis(); st.hopAt = t0; st.lastEmit = t0; st.lastRxAt = t0; st.lastCheck = t0+ val stats = BulkRx.Stats("MT7921AU")+ val total = BulkRx.run("MT7921AU", conn, epRx, 16, 16384, { stop }, onData@{ b, n ->+ stats.transfer(n)+ st.lastRxAt = System.currentTimeMillis()+ stats.sample("$n bytes, RXD", b, 0, 24)+ if (eventSeq(b, n) != null) { cmdsAnswered++; return@onData }+ val f = parseRx(b, n, onBad = { crc -> if (crc) stats.badChecksum++ else stats.malformed++ }) ?: return@onData+ val (hopBand, hopCh) = HOP[st.hopIdx]+ // The descriptor's channel, else the one tuned to.+ val ch = if (f.channel > 0) monitorChannel(f.band, f.channel) else monitorChannel(hopBand, hopCh)+ stats.frame(f.rssi)+ frames.frame(b, f.start, f.end, ch, f.rssi)+ }) { now ->+ stats.maybeLog(now) {+ val (aps, clients) = frames.live(now, REPORT_MS)+ val (band, ch) = HOP[st.hopIdx]+ "${listOf("2.4", "5", "6")[band]} GHz ch $ch, $aps access points, $clients devices, " ++ "firmware answered $cmdsAnswered of $cmdsSent commands, USB errors $ctlErrors"+ }+ if (now - st.lastCheck > 3000) {+ st.lastCheck = now+ // Nothing arriving for a while (not even command answers): put the sniffer back on.+ if (now - st.lastRxAt > 10_000) {+ UsbWifi.log("MT7921AU: receive stalled (${(now - st.lastRxAt) / 1000} s) - restarting the sniffer")+ runCatching { mcuUni(UNI_SNIFFER, snifferEnablePayload(true), wait = false) }+ st.lastRxAt = now+ }+ }+ if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }+ if (now - st.hopAt > DWELL_MS) {+ st.hopIdx = (st.hopIdx + 1) % HOP.size+ val (band, ch) = HOP[st.hopIdx]+ runCatching { tune(band, ch, wait = false) }+ val (aps, clients) = frames.live(now, REPORT_MS)+ onStatus("$chipName · live · $aps access points · $clients devices · ${listOf("2.4", "5", "6")[band]} GHz ch $ch")+ st.hopAt = now+ }+ }+ emit(onFrame)+ UsbWifi.log("MT7921AU: RX loop stopped ($total B)")+ }++ private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {+ val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)+ if (batch.isNotEmpty()) onFrame(batch)+ }++ // ---- register access (mt76 usb.c: 32-bit address split over wValue / wIndex) ----++ private fun ctl(type: Int, req: Int, value: Int, index: Int, data: ByteArray?, len: Int): Int {+ repeat(3) {+ val r = conn.controlTransfer(type, req, value, index, data, len, 1000)+ if (r >= 0) return r+ sleep(5)+ }+ ctlErrors+++ return -1+ }+ private fun rr(addr: Int): Int = rrChecked(addr) ?: -1+ private fun rrChecked(addr: Int): Int? {+ val b = ByteArray(4)+ return if (ctl(DIR_IN or TYPE_VENDOR, VEND_READ_EXT, (addr ushr 16) and 0xffff, addr and 0xffff, b, 4) == 4) le32(b, 0) else null+ }+ private fun wr(addr: Int, v: Int) {+ ctl(TYPE_VENDOR, VEND_WRITE_EXT, (addr ushr 16) and 0xffff, addr and 0xffff, le32Bytes(v), 4)+ }+ private fun uhwRr(addr: Int): Int? {+ val b = ByteArray(4)+ return if (ctl(DIR_IN or TYPE_UHW_VENDOR, VEND_DEV_MODE, (addr ushr 16) and 0xffff, addr and 0xffff, b, 4) == 4) le32(b, 0) else null+ }+ private fun uhwWr(addr: Int, v: Int) {+ ctl(TYPE_UHW_VENDOR, VEND_WRITE, (addr ushr 16) and 0xffff, addr and 0xffff, le32Bytes(v), 4)+ }+ /** Read-modify-write; skipped when the read fails (writing back garbage would be worse). */+ private fun rmw(addr: Int, mask: Int, v: Int) { rrChecked(addr)?.let { wr(addr, (it and mask.inv()) or v) } }+ private fun setBits(addr: Int, bits: Int) = rmw(addr, 0, bits)+ private fun clearBits(addr: Int, bits: Int) = rmw(addr, bits, 0)+ private fun uhwRmw(addr: Int, mask: Int, v: Int) { uhwRr(addr)?.let { uhwWr(addr, (it and mask.inv()) or v) } }++ private fun poll(addr: Int, mask: Int, expect: Int, ms: Int): Boolean {+ val end = System.currentTimeMillis() + ms+ while (true) {+ // A failed read never counts as the expected value.+ rrChecked(addr)?.let { if (it and mask == expect) return true }+ if (System.currentTimeMillis() > end) return false+ sleep(10)+ }+ }++ private fun le32Bytes(v: Int) = ByteArray(4).also { putLe32(it, 0, v) }+ private fun putLe32(b: ByteArray, i: Int, v: Int) { b[i] = v.toByte(); b[i + 1] = (v ushr 8).toByte(); b[i + 2] = (v ushr 16).toByte(); b[i + 3] = (v ushr 24).toByte() }+ private fun putLe16(b: ByteArray, i: Int, v: Int) { b[i] = v.toByte(); b[i + 1] = (v ushr 8).toByte() }+ private fun le32(b: ByteArray, i: Int) = (b[i].toInt() and 0xff) or ((b[i + 1].toInt() and 0xff) shl 8) or+ ((b[i + 2].toInt() and 0xff) shl 16) or ((b[i + 3].toInt() and 0xff) shl 24)+ private fun be32(b: ByteArray, i: Int) = ((b[i].toInt() and 0xff) shl 24) or ((b[i + 1].toInt() and 0xff) shl 16) or+ ((b[i + 2].toInt() and 0xff) shl 8) or (b[i + 3].toInt() and 0xff)+ private fun asciiz(b: ByteArray, off: Int, max: Int): String {+ val n = minOf(max, b.size - off).coerceAtLeast(0)+ return String(b, off, n, Charsets.US_ASCII).substringBefore('\u0000').trim()+ }+ private fun sleep(ms: Int) = try { Thread.sleep(ms.toLong()) } catch (_: InterruptedException) {}+}diff --git a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.mdindex e730e41..25606c4 100644--- a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md+++ b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md@@ -8,6 +8,7 @@ These drivers run USB WiFi adapters in receive-only monitor mode from userspace.- `Rt3070Monitor.kt` drives Ralink RT3070 adapters (e.g. ALFA AWUS036NH / AWUS036NEH), with Ralink's firmware in `assets/usbwifi/rt2870.bin`.- `Rtl8814auMonitor.kt` and `Rtl8814auTables.kt` drive Realtek RTL8814AU adapters (e.g. ALFA AWUS1900), 2.4 + 5 GHz.- `Mt7612uMonitor.kt` drives MediaTek MT7612U / MT7632U adapters (e.g. ALFA AWUS036ACM), 2.4 + 5 GHz, with MediaTek's firmware in `assets/usbwifi/mt7662*.bin`.+- `Mt7921uMonitor.kt` drives MediaTek MT7921AU WiFi 6E adapters (e.g. ALFA AWUS036AXML), 2.4 + 5 + 6 GHz - experimental - with MediaTek's ROM patch and firmware in `assets/usbwifi/WIFI_*MT7961*.bin`.- `Ar9271Monitor.kt` and `Ar9271Tables.kt` drive Atheros AR9271 adapters (e.g. ALFA AWUS036NHA) - experimental - with the open ath9k_htc firmware in `assets/usbwifi/htc_9271-1.4.0.fw`.- `BulkRx.kt` is the USB receive loop of the RTL8187, RT3070, RTL8814AU, MT7612U and AR9271 drivers.- The FREE-WiLi 2 (an ESP32-C5 WiFi board with a USB console) is read by `esp/EspReader.kt` / `esp/EspReports.kt` (FreeWiliReports), ported from Wardrive Go.@@ -26,17 +27,25 @@ These drivers run USB WiFi adapters in receive-only monitor mode from userspace.| RTL8814AU register tables | Realtek 8814au driver, as used by Wardrive Go | GPL-2.0 || AR9271 register tables | Linux `ath9k` (`ar9002_initvals.h`), as used by Wardrive Go | ISC || MT7612U firmware `mt7662.bin` and ROM patch `mt7662_rom_patch.bin` (unmodified, from linux-firmware) | Ralink, a MediaTek company | Redistributable binary, see `assets/usbwifi/LICENCE.ralink_a_mediatek_company_firmware` |+| MT7921AU userspace USB driver (WFSYS reset, USB / WFDMA setup, ROM patch and firmware download, MCU command framing, efuse calibration push, monitor filters and sniffer mode, channel switching, RX descriptor parsing) | [mt76-usb-macos](https://github.com/Network-Weather/mt76-usb-macos) by Network Weather (Copyright (c) 2026 Primatech Paper Co LLC d/b/a Network Weather), a transcription of the MT7921 path of the Linux mt76 driver ([openwrt/mt76](https://github.com/openwrt/mt76): Copyright (C) 2020-2023 MediaTek Inc., (C) 2018 Lorenzo Bianconi, (C) 2016 Felix Fietkau) | BSD-3-Clause-Clear |+| MT7921AU ROM patch `WIFI_MT7961_patch_mcu_1_2_hdr.bin` and firmware `WIFI_RAM_CODE_MT7961_1.bin` (unmodified, from linux-firmware commit e981caea6ed3) | MediaTek Inc. | Redistributable binary, see `assets/usbwifi/LICENCE.mediatek` || AR9271 firmware `htc_9271-1.4.0.fw` (unmodified, from linux-firmware; Wardrive Go ships a build that differs in 10 bytes) | [open-ath9k-htc-firmware](https://github.com/qca/open-ath9k-htc-firmware), Qualcomm Atheros and others | Free software, see `assets/usbwifi/LICENCE.open-ath9k-htc-firmware` || RTL-SDR driver (`sdr/RtlSdr.kt`: RTL2832U baseband, R820T / R828D tuner, RTL-SDR Blog V4 band switching) | [librtlsdr](https://github.com/osmocom/rtl-sdr) (osmocom: Steve Markgraf, Dimitri Stolnikov and others; R82xx code by Mauro Carvalho Chehab and Steve Markgraf; Blog V4 support by RTL-SDR Blog) | GPL-2.0-or-later |-| Integration into RF Sentinel; removal of handshake / PMKID capture (8821AU, RT3070) and of every transmit, beamforming and calibration-for-TX path (8822BU, RTL8187); RT3070 fixes checked against the kernel (eFuse addressing, EEPROM reads, DMA / frame-length setup, receive gain, external LNA, EEPROM BBP overrides); MT7612U: bad-checksum frames dropped, auto-responder off, kernel ROM-patch rule; AR9271: signal relative to the noise floor, FCS removed, packets spanning transfers reassembled, WMI answers matched, running firmware reused | RF Sentinel (CIS-C0) | GPL-3.0 |+| Integration into RF Sentinel; removal of handshake / PMKID capture (8821AU, RT3070) and of every transmit, beamforming and calibration-for-TX path (8822BU, RTL8187); RT3070 fixes checked against the kernel (eFuse addressing, EEPROM reads, DMA / frame-length setup, receive gain, external LNA, EEPROM BBP overrides); MT7612U: bad-checksum frames dropped, auto-responder off, kernel ROM-patch rule; AR9271: signal relative to the noise floor, FCS removed, packets spanning transfers reassembled, WMI answers matched, running firmware reused; MT7921AU: Android USB host API instead of IOKit, no port reset, commands while receiving answered on the shared endpoint without blocking, bad-checksum frames dropped, failed register reads never written back, every transmit path (injection, TX descriptors) left out | RF Sentinel (CIS-C0) | GPL-3.0 |RF Sentinel is distributed under the GNU GPL v3.0 (see `LICENSE`). The registervalues and firmware are hardware configuration data from Realtek's driver; creditand thanks to Realtek, the aircrack-ng rtl8812au maintainers, RocketGod for-Wardrive Go, OpenIPC for devourer, the Linux rtl8187 and rt2x00 authors, and-Kismet. The Ralink and MediaTek firmware is redistributed under its own licences+Wardrive Go, OpenIPC for devourer, Network Weather for mt76-usb-macos, MediaTek and+the mt76 authors, the Linux rtl8187 and rt2x00 authors, and Kismet. The Ralink and MediaTek firmware is redistributed under its own licences(binary only, unmodified, no reverse engineering), reproduced in`assets/usbwifi/LICENCE.ralink-firmware.txt` and-`assets/usbwifi/LICENCE.ralink_a_mediatek_company_firmware`; the ath9k_htc firmware+`assets/usbwifi/LICENCE.ralink_a_mediatek_company_firmware` and+`assets/usbwifi/LICENCE.mediatek` (MT7961: redistributed for use with MediaTek+chipsets, as separate files not covered by this app's GPL); the ath9k_htc firmwareis free software (`assets/usbwifi/LICENCE.open-ath9k-htc-firmware`, sources athttps://github.com/qca/open-ath9k-htc-firmware).++The MT7921AU driver's BSD-3-Clause-Clear licence (copyright notices, conditions and+disclaimer) is reproduced in full in `assets/usbwifi/LICENCE.mt76-usb-macos`, which ships+inside the app. No patent rights are granted by that licence.diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.ktindex 17c6527..538ecce 100644--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt@@ -32,6 +32,8 @@ object Rtl8821auMonitor {private val HOP_5 = intArrayOf(36, 40, 44, 48, 149, 153, 157, 161, 165)/** Settings > External hardware: also hop 5 GHz (experimental); read when the adapter starts. */@Volatile var scan5g = false+ /** The adapter's light blinks with traffic (Settings > External hardware); off = it stays dark. Changes apply live. */+ @Volatile var lightEnabled = trueprivate var HOP = HOP_24private const val DWELL_MS = 350L@@ -106,8 +108,8 @@ object Rtl8821auMonitor {UsbWifi.log("RTL8821AU: RCR=0x%08x BB(0x800)=0x%08x — monitor live ch ${HOP[0]}".format(r32(conn, Rtl8821auTables.REG_RCR), r32(conn, 0x800)))onStatus("RTL8821AU · live · 2.4 GHz monitor")- runCatching { led(conn, true) }- UsbWifi.log("RTL8821AU: light on, blinks with received traffic")+ runCatching { led(conn, lightEnabled) }+ UsbWifi.log(if (lightEnabled) "RTL8821AU: light on, blinks with received traffic" else "RTL8821AU: light off (Settings)")rxLoop(conn, rx, onFrame, onStatus)} catch (e: Exception) {@@ -120,6 +122,10 @@ object Rtl8821auMonitor {}}+ /** The light's next state: dark when switched off; else it flips while frames arrive and stays on when the air is quiet. */+ internal fun nextLight(enabled: Boolean, framesArrived: Boolean, on: Boolean): Boolean =+ if (!enabled) false else if (framesArrived) !on else true+/** Light on or off under software control; the band-switch bit and the rest of the byte are kept. */private fun led(conn: UsbDeviceConnection, on: Boolean) {val v = r8(conn, REG_LEDCFG2)@@ -174,7 +180,7 @@ object Rtl8821auMonitor {private class RxState {var total = 0L; var bufs = 0L; var lastLog = 0L; var hopAt = 0L; var lastEmit = 0L; var hopIdx = 0/** Good frames received, and how many there were at the light's last change. */- var frames = 0L; var ledFrames = 0L; var ledAt = 0L; var ledOn = true+ var frames = 0L; var ledFrames = 0L; var ledAt = 0L; var ledOn = lightEnabledfun start() { val t = System.currentTimeMillis(); lastLog = t; hopAt = t; lastEmit = t; ledAt = t }}@@ -186,9 +192,9 @@ object Rtl8821auMonitor {st.lastLog = now}if (now - st.lastEmit > 2000) { emitSightings(onFrame); st.lastEmit = now }- // Blinks while frames come in; steady on when the air is quiet (still running).+ // Blinks while frames come in; steady on when the air is quiet (still running); dark when switched off.if (now - st.ledAt >= BLINK_MS) {- val want = if (st.frames != st.ledFrames) !st.ledOn else true+ val want = nextLight(lightEnabled, st.frames != st.ledFrames, st.ledOn)if (want != st.ledOn && runCatching { led(conn, want) }.isSuccess) st.ledOn = wantst.ledFrames = st.frames; st.ledAt = now}diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.ktindex 10334a6..4b5c684 100644--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt@@ -43,7 +43,7 @@ object UsbWifi {private const val ACTION_PERMISSION = "com.rfsentinel.app.USB_WIFI_PERMISSION"/** Driver families. */- enum class Driver { RTL88XXAU, RTL88X2BU, RTL8187, RT3070, RTL8814AU, MT7612U, AR9271 }+ enum class Driver { RTL88XXAU, RTL88X2BU, RTL8187, RT3070, RTL8814AU, MT7612U, MT7921U, AR9271 }/** A supported adapter: the chip name shown to the user and the driver that runs it. */data class Chip(val name: String, val driver: Driver)@@ -56,12 +56,14 @@ object UsbWifi {private val AU14 = Chip("RTL8814AU", Driver.RTL8814AU)private val MT = Chip("MT7612U", Driver.MT7612U)private val ATH = Chip("AR9271", Driver.AR9271)+ private val MT21 = Chip("MT7921AU", Driver.MT7921U)/*** USB IDs with a working driver: vendor:product -> chip. 88x2bu and 8814au IDs from the* Linux rtw88 driver, RTL8187 IDs from rtl8187, RT3070 IDs from rt2800usb (the RT3070* driver checks the chip and declines other Ralink chips sharing an ID), MT76x2U IDs from- * mt76x2u, AR9271 IDs from ath9k_htc (not its AR7010 ones, which need other firmware).+ * mt76x2u, MT7921AU IDs from mt7921u (not its MT7902, which needs other firmware), AR9271 IDs+ * from ath9k_htc (not its AR7010 ones, which need other firmware).*/private val SUPPORTED: Map<Pair<Int, Int>, Chip> = mapOf((0x0bda to 0x0811) to AU, // ALFA AWUS036ACS and other 88xxau dongles@@ -102,6 +104,9 @@ object UsbWifi {(0x0471 to 0x2126) to MT, (0x0471 to 0x7600) to MT, (0x2c4e to 0x0103) to MT,(0x0846 to 0x9014) to MT, (0x0846 to 0x9053) to MT, // Netgear WNDA3100v3, A6210(0x045e to 0x02e6) to MT, (0x045e to 0x02fe) to MT, (0x2357 to 0x0137) to MT, // Xbox One wireless adapter, TP-Link+ (0x0e8d to 0x7961) to MT21, // ALFA AWUS036AXML and other MT7921AU (WiFi 6E) dongles+ (0x3574 to 0x6211) to MT21, (0x0846 to 0x9060) to MT21, (0x0846 to 0x9065) to MT21, // Comfast CF-952AX, Netgear A8000 / A7500+ (0x35bc to 0x0107) to MT21, // TP-Link TXE50UH(0x0cf3 to 0x9271) to ATH, // ALFA AWUS036NHA, TP-Link TL-WN722N v1(0x0cf3 to 0x1006) to ATH, (0x0846 to 0x9030) to ATH, (0x07b8 to 0x9271) to ATH, (0x07d1 to 0x3a10) to ATH,(0x13d3 to 0x3327) to ATH, (0x13d3 to 0x3328) to ATH, (0x13d3 to 0x3346) to ATH, (0x13d3 to 0x3348) to ATH,@@ -304,6 +309,7 @@ object UsbWifi {when (chip.driver) {Driver.RTL88XXAU -> {Rtl8821auMonitor.scan5g = com.rfsentinel.app.util.Prefs.rtl8821au5g(context)+ Rtl8821auMonitor.lightEnabled = com.rfsentinel.app.util.Prefs.usbAdapterLight(context)Rtl8821auMonitor.run(context, d, onStatus, onFrames)}Driver.RTL88X2BU -> Rtl8822buMonitor.run(context, d, chip.name, onStatus, onFrames)@@ -311,6 +317,7 @@ object UsbWifi {Driver.RT3070 -> Rt3070Monitor.run(context, d, chip.name, onStatus, onFrames)Driver.RTL8814AU -> Rtl8814auMonitor.run(context, d, chip.name, onStatus, onFrames)Driver.MT7612U -> Mt7612uMonitor.run(context, d, chip.name, onStatus, onFrames)+ Driver.MT7921U -> Mt7921uMonitor.run(context, d, chip.name, onStatus, onFrames)Driver.AR9271 -> Ar9271Monitor.run(context, d, "${chip.name} (experimental)", onStatus, onFrames)}}.onFailure { log("Driver stopped: ${describe(it)}"); status = "USB WiFi adapter error: ${it.message}" }@@ -326,6 +333,7 @@ object UsbWifi {Rt3070Monitor.abort()Rtl8814auMonitor.abort()Mt7612uMonitor.abort()+ Mt7921uMonitor.abort()Ar9271Monitor.abort()runningDevice = nullthread = nulldiff --git a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.ktindex 0188aa3..4236ddc 100644--- a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt+++ b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt@@ -73,66 +73,65 @@ object DeviceExport {return sb.toString()}- fun sessionJson(devices: List<DeviceRegistry.Snapshot>, flags: Flags): JsonArray {- val arr = JsonArray()- devices.forEach { s ->- val o = JsonObject()- o.addProperty("mac", s.mac)- o.addProperty("name", s.name)- o.addProperty("vendor", s.vendor)- o.addProperty("ieeeRegistrant", VendorDb.macVendor(s.mac))- o.addProperty("deviceType", s.deviceType)- o.addProperty("addressType", s.addressType.label)- o.addProperty("trackability", s.addressType.trackable)- o.add("radios", JsonArray().apply { s.sources.forEach { add(it.name) } })- o.addProperty("rssi", s.rssi)- o.addProperty("bestRssi", s.bestRssi)- o.addProperty("distanceMetersRough", Math.round(s.distanceM * 10) / 10.0)- o.addProperty("firstSeen", iso(s.firstSeen))- o.addProperty("lastSeen", iso(s.lastSeen))- o.addProperty("packets", s.sightings)- o.addProperty("following", s.following)- o.addProperty("whitelisted", flags.whitelisted(s.mac))- o.addProperty("favorite", flags.favorite(s.mac))- o.add("matches", JsonArray().apply {- s.hits.forEach { h ->+ fun sessionJson(devices: List<DeviceRegistry.Snapshot>, flags: Flags): JsonArray =+ JsonArray().apply { devices.forEach { add(sessionItem(it, flags)) } }++ private fun sessionItem(s: DeviceRegistry.Snapshot, flags: Flags): JsonObject {+ val o = JsonObject()+ o.addProperty("mac", s.mac)+ o.addProperty("name", s.name)+ o.addProperty("vendor", s.vendor)+ o.addProperty("ieeeRegistrant", VendorDb.macVendor(s.mac))+ o.addProperty("deviceType", s.deviceType)+ o.addProperty("addressType", s.addressType.label)+ o.addProperty("trackability", s.addressType.trackable)+ o.add("radios", JsonArray().apply { s.sources.forEach { add(it.name) } })+ o.addProperty("rssi", s.rssi)+ o.addProperty("bestRssi", s.bestRssi)+ o.addProperty("distanceMetersRough", Math.round(s.distanceM * 10) / 10.0)+ o.addProperty("firstSeen", iso(s.firstSeen))+ o.addProperty("lastSeen", iso(s.lastSeen))+ o.addProperty("packets", s.sightings)+ o.addProperty("following", s.following)+ o.addProperty("whitelisted", flags.whitelisted(s.mac))+ o.addProperty("favorite", flags.favorite(s.mac))+ o.add("matches", JsonArray().apply {+ s.hits.forEach { h ->+ add(JsonObject().apply {+ addProperty("category", h.category.name)+ addProperty("label", h.label)+ addProperty("confidence", h.confidence)+ addProperty("tier", h.tier.name)+ addProperty("evidence", h.evidence)+ addProperty("source", h.source)+ })+ }+ })+ o.add("facts", JsonObject().apply { s.facts.forEach { (k, v) -> addProperty(k, v) } })+ s.known?.let { k ->+ o.add("history", JsonObject().apply {+ addProperty("firstSeenEver", iso(k.firstSeen))+ addProperty("sessions", k.sessions)+ addProperty("detectCount", k.detectCount)+ })+ }+ s.remoteId?.let { o.add("remoteId", gson.toJsonTree(it)) }+ s.advert?.let { o.add("advertisement", advertJson(it)) }+ if (s.path.isNotEmpty()) {+ o.add("positions", JsonArray().apply {+ s.path.forEach { p ->add(JsonObject().apply {- addProperty("category", h.category.name)- addProperty("label", h.label)- addProperty("confidence", h.confidence)- addProperty("tier", h.tier.name)- addProperty("evidence", h.evidence)- addProperty("source", h.source)+ addProperty("time", iso(p.time)); addProperty("lat", p.lat); addProperty("lon", p.lon)})}})- o.add("facts", JsonObject().apply { s.facts.forEach { (k, v) -> addProperty(k, v) } })- s.known?.let { k ->- o.add("history", JsonObject().apply {- addProperty("firstSeenEver", iso(k.firstSeen))- addProperty("sessions", k.sessions)- addProperty("detectCount", k.detectCount)- })- }- s.remoteId?.let { o.add("remoteId", gson.toJsonTree(it)) }- s.advert?.let { o.add("advertisement", advertJson(it)) }- if (s.path.isNotEmpty()) {- o.add("positions", JsonArray().apply {- s.path.forEach { p ->- add(JsonObject().apply {- addProperty("time", iso(p.time)); addProperty("lat", p.lat); addProperty("lon", p.lon)- })- }- })- }- if (s.history.isNotEmpty()) {- o.add("rssiHistory", JsonArray().apply {- s.history.forEach { h -> add(JsonArray().apply { add(h.time); add(h.rssi) }) }- })- }- arr.add(o)}- return arr+ if (s.history.isNotEmpty()) {+ o.add("rssiHistory", JsonArray().apply {+ s.history.forEach { h -> add(JsonArray().apply { add(h.time); add(h.rssi) }) }+ })+ }+ return o}private fun advertJson(a: Advert): JsonObject = JsonObject().apply {@@ -194,36 +193,54 @@ object DeviceExport {return sb.toString()}- fun historyJson(rows: List<KnownDeviceEntity>): JsonArray = JsonArray().apply {- rows.forEach { r ->- add(JsonObject().apply {- addProperty("mac", r.mac); addProperty("name", r.name); addProperty("vendor", r.vendor)- addProperty("deviceType", r.deviceType); addProperty("firstSeen", iso(r.firstSeen))- addProperty("lastSeen", iso(r.lastSeen)); addProperty("sessions", r.sessions)- addProperty("detectCount", r.detectCount); addProperty("favorite", r.favorite); addProperty("note", r.note)- })- }+ fun historyJson(rows: List<KnownDeviceEntity>): JsonArray = JsonArray().apply { rows.forEach { add(historyItem(it)) } }++ private fun historyItem(r: KnownDeviceEntity) = JsonObject().apply {+ addProperty("mac", r.mac); addProperty("name", r.name); addProperty("vendor", r.vendor)+ addProperty("deviceType", r.deviceType); addProperty("firstSeen", iso(r.firstSeen))+ addProperty("lastSeen", iso(r.lastSeen)); addProperty("sessions", r.sessions)+ addProperty("detectCount", r.detectCount); addProperty("favorite", r.favorite); addProperty("note", r.note)}fun matchesJson(rows: List<DetectionEntity>): JsonArray = gson.toJsonTree(rows).asJsonArray- /** One file with everything: session, history, match log, watchlist entries. */- fun everythingJson(+ /**+ * One file with everything (session, history, match log, watchlist entries), written straight+ * to [out] one device at a time: a long history (100,000+ devices after some wardriving) built up+ * as one JSON tree and one string ran the app out of memory. [historyBatches] and [matchBatches]+ * give the next rows, empty when done.+ */+ suspend fun writeEverything(+ out: java.io.Writer,appVersion: String,session: List<DeviceRegistry.Snapshot>,flags: Flags,- history: List<KnownDeviceEntity>,- matches: List<DetectionEntity>,+ historyBatches: suspend () -> List<KnownDeviceEntity>,+ matchBatches: suspend () -> List<DetectionEntity>,watchlist: List<OuiEntry>- ): String {- val root = JsonObject()- root.addProperty("exportedBy", "RF Sentinel $appVersion")- root.addProperty("exportedAt", iso(System.currentTimeMillis()))- root.add("sessionDevices", sessionJson(session, flags))- root.add("deviceHistory", historyJson(history))- root.add("matchLog", matchesJson(matches))- root.add("watchlist", gson.toJsonTree(watchlist))- return gson.toJson(root)+ ) {+ val w = gson.newJsonWriter(out)+ w.beginObject()+ w.name("exportedBy").value("RF Sentinel $appVersion")+ w.name("exportedAt").value(iso(System.currentTimeMillis()))+ w.name("sessionDevices").beginArray()+ session.forEach { gson.toJson(sessionItem(it, flags), w) }+ w.endArray()+ w.name("deviceHistory").beginArray()+ while (true) { val rows = historyBatches(); if (rows.isEmpty()) break; rows.forEach { gson.toJson(historyItem(it), w) } }+ w.endArray()+ w.name("matchLog").beginArray()+ while (true) { val rows = matchBatches(); if (rows.isEmpty()) break; rows.forEach { gson.toJson(it, DetectionEntity::class.java, w) } }+ w.endArray()+ w.name("watchlist"); gson.toJson(gson.toJsonTree(watchlist), w)+ w.endObject()+ w.flush()+ }++ /** [rows] a batch of [size] at a time (for [writeEverything] from rows already in memory). */+ fun <T> batches(rows: List<T>, size: Int = 500): suspend () -> List<T> {+ var at = 0+ return { rows.subList(at.coerceAtMost(rows.size), (at + size).coerceAtMost(rows.size)).also { at += size } }}fun pretty(el: com.google.gson.JsonElement): String = gson.toJson(el)diff --git a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt b/app/src/main/java/com/rfsentinel/app/util/Exporter.ktindex 2d3e45f..1bab35b 100644--- a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt@@ -74,6 +74,7 @@ object Exporter {when (scope) {Scope.MATCHES -> exportLog(activity, format)Scope.WATCHLIST -> exportWatchlist(activity)+ Scope.EVERYTHING -> exportEverything(activity)else -> exportDevices(activity, scope, format)}}@@ -83,13 +84,63 @@ object Exporter {favorite = { com.rfsentinel.app.data.Favorites.contains(it) })- private fun exportDevices(activity: AppCompatActivity, scope: Scope, format: String) {+ /**+ * Runs an export; a failure (out of memory on a huge history, a full disk) says so instead of+ * taking the app down with it.+ */+ private fun launchExport(activity: AppCompatActivity, block: suspend () -> Unit) {activity.lifecycleScope.launch {+ try {+ block()+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Throwable) {+ android.util.Log.w("Exporter", "export failed", e)+ toast(activity, if (e is OutOfMemoryError) "Export failed: not enough memory for this much data"+ else "Export failed: ${e.message ?: e.javaClass.simpleName}")+ }+ }+ }++ /** Full snapshots include the raw advertisement, RSSI history and positions. */+ private fun sessionDevices() = com.rfsentinel.app.service.DeviceRegistry.snapshot()+ .mapNotNull { com.rfsentinel.app.service.DeviceRegistry.get(it.mac) }+ .sortedWith(compareByDescending<com.rfsentinel.app.service.DeviceRegistry.Snapshot> { it.best != null }.thenByDescending { it.rssi })++ /**+ * Everything in one JSON file, written to it as it's read: the device history and the match+ * log come from the database a batch at a time, so a long history fits in memory.+ */+ private fun exportEverything(activity: AppCompatActivity) = launchExport(activity) {+ val db = AppDatabase.getInstance(activity)+ val history = db.knownDeviceDao()+ val detections = db.detectionDao()+ val session = sessionDevices()+ shareWritten(activity, "rf_sentinel_full_export_${stamp()}.json", "application/json", "Export") { out ->+ // The order is fixed first, so devices heard meanwhile don't shift the batches.+ val macs = history.macsByLastSeen()+ var at = 0+ var before = Long.MAX_VALUE+ DeviceExport.writeEverything(+ out, com.rfsentinel.app.BuildConfig.VERSION_NAME, session, flags,+ historyBatches = {+ val chunk = macs.subList(at.coerceAtMost(macs.size), (at + BATCH).coerceAtMost(macs.size))+ at += BATCH+ val order = chunk.withIndex().associate { (i, m) -> m to i }+ if (chunk.isEmpty()) emptyList() else history.getAll(chunk).sortedBy { order[it.mac] ?: Int.MAX_VALUE }+ },+ matchBatches = { detections.pageBefore(before, BATCH).also { rows -> rows.lastOrNull()?.let { before = it.id } } },+ watchlist = OuiWatchlist.allEntries().filter { it.isCustom }+ )+ }+ }++ private const val BATCH = 500++ private fun exportDevices(activity: AppCompatActivity, scope: Scope, format: String) {+ launchExport(activity) {val db = AppDatabase.getInstance(activity)- // Full snapshots include the raw advertisement, RSSI history and positions.- val session = com.rfsentinel.app.service.DeviceRegistry.snapshot()- .mapNotNull { com.rfsentinel.app.service.DeviceRegistry.get(it.mac) }- .sortedWith(compareByDescending<com.rfsentinel.app.service.DeviceRegistry.Snapshot> { it.best != null }.thenByDescending { it.rssi })+ val session = sessionDevices()val (name, text, mime) = withContext(Dispatchers.Default) {when (scope) {Scope.SESSION -> {@@ -103,29 +154,20 @@ object Exporter {else -> Triple("nearby_devices", DeviceExport.pretty(DeviceExport.sessionJson(session, flags)), "application/json")}}- Scope.HISTORY -> {+ else -> {val rows = db.knownDeviceDao().all()if (rows.isEmpty()) return@withContext nullif (format == "csv") Triple("device_history", DeviceExport.historyCsv(rows), "text/csv")else Triple("device_history", DeviceExport.pretty(DeviceExport.historyJson(rows)), "application/json")}- else -> Triple(- "full_export",- DeviceExport.everythingJson(- com.rfsentinel.app.BuildConfig.VERSION_NAME, session, flags,- db.knownDeviceDao().all(), db.detectionDao().allForExport(),- OuiWatchlist.allEntries().filter { it.isCustom }- ),- "application/json"- )}} ?: run {toast(activity, if (scope == Scope.SESSION) "No devices heard yet - start scanning first" else "No device history yet")- return@launch+ return@launchExport}if (mime == "nogps") {toast(activity, "No GPS positions yet - turn on location while scanning (follower alerts or GPS tagging)")- return@launch+ return@launchExport}share(activity, "rf_sentinel_${name}_${stamp()}.$format", text, mime, "Export")}@@ -160,18 +202,18 @@ object Exporter {}private fun exportTrip(activity: AppCompatActivity, tripId: Long, format: String, onlyFlagged: Boolean) {- activity.lifecycleScope.launch {+ launchExport(activity) {// Make sure the latest buffered points are on disk before reading.if (com.rfsentinel.app.service.TripRecorder.activeTripId == tripId) {runCatching { com.rfsentinel.app.service.TripRecorder.flush(activity) }}val dao = AppDatabase.getInstance(activity).tripDao()- val trip = dao.get(tripId) ?: run { toast(activity, "Trace not found"); return@launch }+ val trip = dao.get(tripId) ?: run { toast(activity, "Trace not found"); return@launchExport }val points = dao.points(tripId)val devices = dao.devices(tripId)if (points.isEmpty() && devices.none { it.lat != null } && format != "csv") {toast(activity, "This trace has no GPS points yet")- return@launch+ return@launchExport}val (text, mime, ext) = withContext(Dispatchers.Default) {when (format) {@@ -187,7 +229,7 @@ object Exporter {}fun exportLog(activity: AppCompatActivity, format: String) {- activity.lifecycleScope.launch {+ launchExport(activity) {val rows = AppDatabase.getInstance(activity).detectionDao().allForExport()val usable = if (format == "csv" || format == "json") rows else rows.filter { it.latitude != null && it.longitude != null }if (usable.isEmpty()) {@@ -196,7 +238,7 @@ object Exporter {if (format == "csv" || format == "json") "No matches logged yet"else "No GPS-tagged matches yet - turn on GPS tagging in Settings")- return@launch+ return@launchExport}val text = when (format) {"gpx" -> gpx(usable)@@ -215,7 +257,7 @@ object Exporter {}private fun exportWatchlist(activity: AppCompatActivity) {- activity.lifecycleScope.launch {+ launchExport(activity) {val json = OuiWatchlist.exportCustomJson(activity)share(activity, "rf_sentinel_watchlist_${stamp()}.json", json, "application/json", "Export watchlist")}@@ -280,15 +322,24 @@ object Exporter {internal fun stamp() = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())- internal suspend fun share(context: Context, fileName: String, content: String, mime: String, title: String) {+ internal suspend fun share(context: Context, fileName: String, content: String, mime: String, title: String) =+ shareWritten(context, fileName, mime, title) { it.write(content) }++ /** Writes the export file with [write] (on a background thread), then offers it in the share sheet. */+ internal suspend fun shareWritten(context: Context, fileName: String, mime: String, title: String,+ write: suspend (java.io.Writer) -> Unit) {val uri: Uri? = withContext(Dispatchers.IO) {+ val dir = File(context.cacheDir, "exports").apply { mkdirs() }+ val file = File(dir, fileName)try {- val dir = File(context.cacheDir, "exports").apply { mkdirs() }- val file = File(dir, fileName)- file.writeText(content)+ file.bufferedWriter().use { write(it) }FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)} catch (e: Exception) {+ file.delete()null+ } catch (e: OutOfMemoryError) {+ file.delete() // no half-written file left behind+ throw e}}if (uri == null) {diff --git a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.ktindex c96bac7..7c3cd94 100644--- a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt+++ b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt@@ -142,7 +142,9 @@ object NotificationHelper {context: Context, key: String, hit: Hit,target: Class<out android.app.Activity> = com.rfsentinel.app.ui.MapActivity::class.java,/** Where the thing is (a camera); else where you were. */- lat: Double? = null, lon: Double? = null+ lat: Double? = null, lon: Double? = null,+ /** An internet alert's key ("air:..." aircraft, "waze:..." report): tapping opens the map on it ([lat] / [lon] where it was). */+ online: String? = null) {recordAlert(context, key, null, hit, null, false, lat, lon)val discreet = Prefs.discreetMode(context)@@ -151,7 +153,8 @@ object NotificationHelper {if (toCar(context, if (discreet) "New alert" else "${hit.label}. ${hit.evidence}", null)) returnval open = PendingIntent.getActivity(context, key.hashCode(),- Intent(context, target).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ (online?.let { com.rfsentinel.app.ui.MapActivity.onlineIntent(context, it, lat, lon) } ?: Intent(context, target))+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)val builder = NotificationCompat.Builder(context, CHANNEL_ALERTS)diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 6e45cc6..17363db 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -414,6 +414,9 @@ object Prefs {/** ALFA AWUS036ACS / RTL8811AU-8821AU: also hop 5 GHz (experimental, off by default). */fun rtl8821au5g(context: Context): Boolean = bool(context, "rtl8821au_5g", false)+ /** The USB adapter's own light (only adapters whose light the app can drive: RTL8811AU / 8821AU): on by default. */+ fun usbAdapterLight(context: Context): Boolean = bool(context, "usb_adapter_light", true)+ fun setUsbAdapterLight(context: Context, value: Boolean) = setBool(context, "usb_adapter_light", value)fun setRtl8821au5g(context: Context, value: Boolean) = setBool(context, "rtl8821au_5g", value)/** Hide trusted (whitelisted) devices from the live list and radar (off by default). */@@ -468,4 +471,23 @@ object Prefs {fun mapDark(context: Context): Boolean? =if (sp(context).contains("map_dark")) sp(context).getBoolean("map_dark", false) else nullfun setMapDark(context: Context, value: Boolean) = setBool(context, "map_dark", value)++ /**+ * How close the map follows you: the zoom (vector map's level) at street speed; the 3D driving view+ * pulls back from it as you speed up, the flat views sit half a level wider. 17 is close to Waze.+ */+ const val MAP_ZOOM_WAZE = 17.0+ fun mapDefaultZoom(context: Context): Double =+ sp(context).getFloat("map_default_zoom", MAP_ZOOM_WAZE.toFloat()).toDouble().coerceIn(14.5, 18.5)+ fun setMapDefaultZoom(context: Context, value: Double) = sp(context).edit().putFloat("map_default_zoom", value.toFloat()).apply()++ /** The 3D driving view's tilt (degrees) at street speed; it leans further back by up to 10 degrees on fast roads. */+ const val MAP_TILT_DEFAULT = 50.0+ fun map3dTilt(context: Context): Double =+ sp(context).getFloat("map_3d_tilt", MAP_TILT_DEFAULT.toFloat()).toDouble().coerceIn(30.0, 60.0)+ fun setMap3dTilt(context: Context, value: Double) = sp(context).edit().putFloat("map_3d_tilt", value.toFloat()).apply()++ /** The map's provider ("openfreemap", the default, or "mapbox"), Settings > Map. */+ fun mapProvider(context: Context): String? = sp(context).getString("map_provider", null)+ fun setMapProvider(context: Context, value: String) = sp(context).edit().putString("map_provider", value).apply()}diff --git a/app/src/main/java/com/rfsentinel/app/util/Voice.kt b/app/src/main/java/com/rfsentinel/app/util/Voice.ktindex 3134dc4..cc9a2f1 100644--- a/app/src/main/java/com/rfsentinel/app/util/Voice.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Voice.kt@@ -23,6 +23,10 @@ import java.util.Localeobject Voice {private const val GOOGLE_TTS = "com.google.android.tts"+ /** An utterance that hasn't started by then never will (the engine dropped it). */+ private const val START_TIMEOUT_MS = 5_000L+ /** An alert said again after a failure, if it's still this fresh. */+ private const val RETRY_MAX_AGE_MS = 30_000Lprivate val main = Handler(Looper.getMainLooper())private var tts: TextToSpeech? = null@@ -52,7 +56,7 @@ object Voice {val current = speakingif (current != null && queue.preempts(priority, current.priority)) {tts?.stop() // onDone/onStop isn't guaranteed after stop(): move on ourselves- speaking = null+ done()}pump()}@@ -62,13 +66,34 @@ object Voice {app = context.applicationContextqueue.clear()tts?.stop()- speaking = null+ done()nextAttrs = attrs- testText = text // bypasses the repeat filter: the button can be pressed again and again+ // Bypasses the repeat filter: the button can be pressed again and again.+ pending = VoiceQueue.Item(text, VoiceQueue.FOLLOWING + 1, System.currentTimeMillis())+ pendingTries = 0pump()}- private var testText: String? = null+ /** Said before the queue: the Test button, or an alert said again after the engine failed it. */+ private var pending: VoiceQueue.Item? = null+ private var pendingTries = 0+ /** The utterance being said, how many times it already failed, and whether it went to the boosted session. */+ private var utterance: String? = null+ private var tries = 0+ private var started = false+ private var boostedNow = false+ /** The boosted session failed twice in a row on this phone: speak without it (until the app restarts). */+ private var boostFailed = false++ /**+ * The engine went quiet on what's being said: it never started it, or never said it was done (the+ * speech service was updated or killed in the background). Without this, [speaking] stays set and+ * every alert after it waits forever, while the Test button, which clears it, still works.+ */+ private val watchdog = Runnable {+ val item = speaking ?: return@Runnable+ if (started) { done(); pump() } else failed(item)+ }private fun pump() {if (speaking != null) return@@ -76,24 +101,60 @@ object Voice {val engine = ttsif (engine == null || !ready) { if (engine == null) start(ctx); return }val now = System.currentTimeMillis()- val item = testText?.let { VoiceQueue.Item(it, VoiceQueue.FOLLOWING + 1, now) }?.also { testText = null }- ?: queue.next(now) ?: run { releaseFocus(); return }+ val retry = pending?.takeIf { now - it.time <= RETRY_MAX_AGE_MS }+ val retryTries = pendingTries+ pending = null+ val item = retry ?: queue.next(now) ?: run { releaseFocus(); return }val attrs = nextAttrs ?: return+ tries = if (retry != null) retryTries else 0speaking = itemspeakingAttrs = attrsholdFocus(ctx, attrs)engine.setAudioAttributes(attrs)engine.setSpeechRate(Prefs.voiceRate(ctx))+ val session = if (boostFailed) null else boostedSession(ctx)val params = Bundle().apply {putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1f)- boostedSession(ctx)?.let { putInt(TextToSpeech.Engine.KEY_PARAM_SESSION_ID, it) }- }- if (engine.speak(item.text, TextToSpeech.QUEUE_FLUSH, params, "rf-${System.nanoTime()}") != TextToSpeech.SUCCESS) {- speaking = null- releaseFocus()+ session?.let { putInt(TextToSpeech.Engine.KEY_PARAM_SESSION_ID, it) }}+ val id = "rf-${System.nanoTime()}"+ utterance = id+ started = false+ boostedNow = session != null+ main.removeCallbacks(watchdog)+ main.postDelayed(watchdog, START_TIMEOUT_MS)+ // Refused: no longer connected to the engine (updated or killed in the background).+ if (engine.speak(item.text, TextToSpeech.QUEUE_FLUSH, params, id) != TextToSpeech.SUCCESS) failed(item)+ }++ /** Nothing is being said any more. */+ private fun done() {+ main.removeCallbacks(watchdog)+ speaking = null+ utterance = null}+ /**+ * The engine didn't say [item]. Starts it afresh and says [item] again, up to twice; after two+ * failures in a row in the boosted session, speech goes without the boost (in case that's what+ * this phone can't play).+ */+ private fun failed(item: VoiceQueue.Item) {+ done()+ val n = tries + 1+ if (boostedNow && n >= 2) boostFailed = true+ if (n <= 2) { pending = item; pendingTries = n }+ val ctx = app ?: return+ runCatching { tts?.shutdown() }+ tts = null+ ready = false+ start(ctx)+ }++ /** Talking takes about this long, with room to spare. */+ private fun talkMs(text: String, ctx: Context) =+ 4_000L + (text.length * 120L / Prefs.voiceRate(ctx).coerceAtLeast(0.3f)).toLong()+/*** The audio session to speak in, with Android's loudness enhancer (a gain with a limiter, so it* gets louder without distorting) set to the chosen boost; null with no boost or no enhancer.@@ -128,11 +189,11 @@ object Voice {return}engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() {- override fun onStart(id: String?) {}- override fun onDone(id: String?) = finished()+ override fun onStart(id: String?) { main.post { onStarted(id) } }+ override fun onDone(id: String?) = finished(id)@Deprecated("Deprecated in Java")- override fun onError(id: String?) = finished()- override fun onError(id: String?, errorCode: Int) = finished()+ override fun onError(id: String?) = errored(id)+ override fun onError(id: String?, errorCode: Int) = errored(id)override fun onStop(id: String?, interrupted: Boolean) {}})voices = englishVoices(engine)@@ -141,14 +202,32 @@ object Voice {pump()}- private fun finished() {+ private fun onStarted(id: String?) {+ if (id == null || id != utterance) return+ started = true+ // Now it only has to finish.+ main.removeCallbacks(watchdog)+ app?.let { main.postDelayed(watchdog, talkMs(speaking?.text.orEmpty(), it)) }+ }++ /** Late callbacks of an utterance given up on are ignored. */+ private fun finished(id: String?) {main.post {- speaking = null+ if (id == null || id != utterance) return@post+ done()// A short breath between phrases, then the next (or give the audio back).main.postDelayed({ pump() }, 250)}}+ private fun errored(id: String?) {+ main.post {+ if (id == null || id != utterance) return@post+ val item = speaking ?: return@post+ if (started) { done(); main.postDelayed({ pump() }, 250) } else failed(item)+ }+ }+/** English voices, best first: installed (offline) before network, then by quality, US/GB first. */private fun englishVoices(engine: TextToSpeech): List<android.speech.tts.Voice> =runCatching { engine.voices.orEmpty() }.getOrDefault(emptySet())@@ -205,15 +284,16 @@ object Voice {/** Stops what's being said and drops what's queued (alerts muted); the engine stays ready. */fun silence() = main.post {queue.clear()- testText = null+ pending = nulltts?.stop()- speaking = null+ done()releaseFocus()}fun shutdown() = main.post {queue.clear()- speaking = null+ pending = null+ done()releaseFocus()tts?.shutdown()tts = nulldiff --git a/app/src/main/res/layout/activity_device_history.xml b/app/src/main/res/layout/activity_device_history.xmlnew file mode 100644index 0000000..c1e7254--- /dev/null+++ b/app/src/main/res/layout/activity_device_history.xml@@ -0,0 +1,73 @@+<?xml version="1.0" encoding="utf-8"?>+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:app="http://schemas.android.com/apk/res-auto"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:orientation="vertical"+ android:paddingStart="16dp"+ android:paddingTop="8dp"+ android:paddingEnd="16dp">++ <!-- MAC, name, vendor, type or your note. -->+ <com.google.android.material.textfield.TextInputLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:hint="Search MAC, name, vendor, type, note"+ app:endIconMode="clear_text"+ app:startIconDrawable="@drawable/ic_search">++ <com.google.android.material.textfield.TextInputEditText+ android:id="@+id/searchInput"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:imeOptions="actionSearch"+ android:importantForAutofill="no"+ android:inputType="text"+ android:maxLines="1" />+ </com.google.android.material.textfield.TextInputLayout>++ <HorizontalScrollView+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:scrollbars="none">++ <com.google.android.material.chip.ChipGroup+ android:id="@+id/filterChips"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ app:selectionRequired="true"+ app:singleLine="true"+ app:singleSelection="true" />+ </HorizontalScrollView>++ <FrameLayout+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_weight="1">++ <androidx.recyclerview.widget.RecyclerView+ android:id="@+id/recyclerView"+ android:layout_width="match_parent"+ android:layout_height="match_parent" />++ <TextView+ android:id="@+id/emptyText"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_gravity="center"+ android:gravity="center"+ android:padding="24dp"+ android:textColor="#888888"+ android:visibility="gone" />+ </FrameLayout>++ <!-- How long history is kept (Settings > Data). -->+ <TextView+ android:id="@+id/keptText"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:paddingTop="6dp"+ android:paddingBottom="8dp"+ android:textColor="#888888"+ android:textSize="12sp" />+</LinearLayout>diff --git a/app/src/main/res/layout/activity_history.xml b/app/src/main/res/layout/activity_history.xmlindex e40422e..3196eec 100644--- a/app/src/main/res/layout/activity_history.xml+++ b/app/src/main/res/layout/activity_history.xml@@ -69,11 +69,31 @@</LinearLayout></HorizontalScrollView>- <org.osmdroid.views.MapView- android:id="@+id/map"+ <FrameLayoutandroid:layout_width="match_parent"android:layout_height="0dp"- android:layout_weight="1" />+ android:layout_weight="1">++ <!-- The map engine's view goes in here (OpenFreeMap or Mapbox, Settings > Map). -->+ <FrameLayout+ android:id="@+id/map"+ android:layout_width="match_parent"+ android:layout_height="match_parent" />++ <!-- Map data credit (OpenFreeMap, OpenMapTiles, OpenStreetMap). -->+ <TextView+ android:id="@+id/mapCredit"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="bottom|start"+ android:layout_margin="4dp"+ android:background="#99FFFFFF"+ android:paddingStart="4dp"+ android:paddingEnd="4dp"+ android:text="© OpenFreeMap © OpenMapTiles © OpenStreetMap contributors"+ android:textColor="#333333"+ android:textSize="9sp" />+ </FrameLayout><LinearLayoutandroid:id="@+id/panel"diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xmlindex 81d5370..be5d294 100644--- a/app/src/main/res/layout/activity_map.xml+++ b/app/src/main/res/layout/activity_map.xml@@ -5,12 +5,21 @@android:layout_width="match_parent"android:layout_height="match_parent">- <org.osmdroid.views.MapView+ <!-- The map engine's view goes in here (OpenFreeMap or Mapbox, Settings > Map). -->+ <FrameLayoutandroid:id="@+id/map"android:layout_width="match_parent"android:layout_height="match_parent" />- <!-- 3D view: the map is tilted, so its own attribution can be off screen; this one stays. -->+ <!-- The map's scale, under the status card (moved there in code). -->+ <com.rfsentinel.app.ui.ScaleBarView+ android:id="@+id/scaleBar"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="top|start"+ android:layout_marginStart="8dp" />++ <!-- Map data credit (OpenFreeMap, OpenMapTiles, OpenStreetMap), under the scale. --><TextViewandroid:id="@+id/osmCredit"android:layout_width="wrap_content"@@ -20,10 +29,9 @@android:background="#99FFFFFF"android:paddingStart="4dp"android:paddingEnd="4dp"- android:text="© OpenStreetMap contributors"+ android:text="© OpenFreeMap © OpenMapTiles © OpenStreetMap contributors"android:textColor="#333333"- android:textSize="10sp"- android:visibility="gone" />+ android:textSize="9sp" /><!-- Status card, with the camera-download progress bar under it --><LinearLayout@@ -81,6 +89,19 @@app:fabSize="mini"app:tint="#FFFFFF" />+ <!-- Map settings (provider, layers...): Settings > Map. -->+ <com.google.android.material.floatingactionbutton.FloatingActionButton+ android:id="@+id/mapSettingsButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="end"+ android:layout_marginEnd="14dp"+ android:layout_marginBottom="8dp"+ android:contentDescription="Map settings"+ android:src="@drawable/ic_settings"+ app:fabSize="mini"+ app:tint="#FFFFFF" />+<!-- Light / dark map. --><com.google.android.material.floatingactionbutton.FloatingActionButtonandroid:id="@+id/themeButton"diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex 2293abb..1904479 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -447,6 +447,46 @@<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">+ <TextView android:id="@+id/mapZoomText" style="@style/SettingsLabel" android:text="Default zoom" />++ <com.google.android.material.slider.Slider+ android:id="@+id/mapZoomSlider"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:contentDescription="Default map zoom"+ android:stepSize="1"+ android:value="68"+ android:valueFrom="58"+ android:valueTo="74" />++ <Button+ android:id="@+id/mapZoomReset"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Waze-like zoom" />++ <TextView android:id="@+id/map3dTiltText" style="@style/SettingsLabel" android:text="3D view angle" />++ <com.google.android.material.slider.Slider+ android:id="@+id/map3dTiltSlider"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:contentDescription="3D driving view angle in degrees"+ android:stepSize="5"+ android:value="50"+ android:valueFrom="30"+ android:valueTo="60" />++ <TextView style="@style/SettingsLabel" android:text="Map provider" />++ <com.google.android.material.button.MaterialButton+ android:id="@+id/mapProviderButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="OpenFreeMap" />+<com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/mapKnownCamerasSwitch"android:layout_width="match_parent"@@ -676,6 +716,12 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:text="AWUS036ACS (RTL8811AU / 8821AU): also scan 5 GHz (experimental)" />++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/usbLightSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="AWUS036ACS (RTL8811AU / 8821AU): adapter light blinks with traffic" /></LinearLayout><!-- ================= RTL-SDR radio (filled in by SettingsActivity.setupRadioSection) ================= -->diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xmlindex fabb0c3..f931376 100644--- a/app/src/main/res/menu/menu_main.xml+++ b/app/src/main/res/menu/menu_main.xml@@ -19,6 +19,7 @@app:showAsAction="always" /><item android:id="@+id/action_waze_now" android:title="Check Waze now" app:showAsAction="never" /><item android:id="@+id/action_waze_status" android:title="Waze status" app:showAsAction="never" />+ <item android:id="@+id/action_device_history" android:title="Device history (search)" app:showAsAction="never" /><item android:id="@+id/action_match_log" android:title="Match history" app:showAsAction="never" /><item android:id="@+id/action_traces" android:title="Recorded traces" app:showAsAction="never" /><item android:id="@+id/action_history" android:title="History map & timeline" app:showAsAction="never" />diff --git a/app/src/test/java/com/rfsentinel/app/data/DeviceSearchTest.kt b/app/src/test/java/com/rfsentinel/app/data/DeviceSearchTest.ktnew file mode 100644index 0000000..d1d71ca--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/data/DeviceSearchTest.kt@@ -0,0 +1,21 @@+package com.rfsentinel.app.data++import org.junit.Assert.assertEquals+import org.junit.Test++/** Device history search: what's typed is matched literally, and a MAC is found with or without colons. */+class DeviceSearchTest {++ @Test+ fun typedTextIsMatchedLiterally() {+ assertEquals("%tile%", KnownDeviceDao.like("tile"))+ assertEquals("%50\\%\\_x%", KnownDeviceDao.like("50%_x"))+ assertEquals("%a\\\\b%", KnownDeviceDao.like("a\\b"))+ }++ @Test+ fun aMacWithoutColonsOrWithDashes() {+ assertEquals("%aabbcc%", KnownDeviceDao.likeHex("aa:bb:cc"))+ assertEquals("%aabbcc%", KnownDeviceDao.likeHex("aa-bb-cc"))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/AircraftFocusTest.kt b/app/src/test/java/com/rfsentinel/app/online/AircraftFocusTest.ktnew file mode 100644index 0000000..6eabb07--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/AircraftFocusTest.kt@@ -0,0 +1,57 @@+package com.rfsentinel.app.online++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.rfsentinel.app.ui.MapActivity+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** A police aircraft alert or log row opens the map on the aircraft: where it is now, else its last known position. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class AircraftFocusTest {++ private fun plane(hex: String, lat: Double) =+ PoliceAircraft.Seen(PoliceAircraft.Plane(hex, "POL1", null, null, null, lat, -70.0, 1500, 90.0, 45.0, false), null)++ @After+ fun clear() { PoliceAircraft.latest = emptyList(); PoliceAircraft.latestAt = 0L }++ @Test+ fun theLatestPositionWhileTheFeedIsFresh() {+ PoliceAircraft.latest = listOf(plane("a1b2c3", 45.1), plane("ffffff", 46.0))+ PoliceAircraft.latestAt = 1_000_000L+ assertEquals(45.1, PoliceAircraft.current("A1B2C3", now = 1_000_000L + 60_000L)!!.plane.lat, 1e-9)+ assertNull("gone from the feed", PoliceAircraft.current("000001", now = 1_000_000L))+ assertNull("feed older than 3 minutes", PoliceAircraft.current("a1b2c3", now = 1_000_000L + 4 * 60_000L))+ }++ @Test+ fun theMapIntentCarriesTheAircraftAndItsLastPosition() {+ val ctx = ApplicationProvider.getApplicationContext<Application>()+ val i = MapActivity.onlineIntent(ctx, "air:a1b2c3", 45.5, -73.5)!!+ assertEquals("a1b2c3", i.getStringExtra(MapActivity.EXTRA_AIRCRAFT))+ assertEquals(45.5, i.getDoubleExtra(MapActivity.EXTRA_CENTER_LAT, 0.0), 1e-9)+ assertEquals(-73.5, i.getDoubleExtra(MapActivity.EXTRA_CENTER_LON, 0.0), 1e-9)+ // No saved position: the map then needs the live feed.+ assertFalse(MapActivity.onlineIntent(ctx, "air:a1b2c3", null, null)!!.hasExtra(MapActivity.EXTRA_CENTER_LAT))+ }++ @Test+ fun wazeReportsOpenTheMapOnTheirSpot() {+ val ctx = ApplicationProvider.getApplicationContext<Application>()+ // Waze ids are case-sensitive: kept as they are.+ val i = MapActivity.onlineIntent(ctx, "waze:Ab12-Cd", 45.6, -73.6)!!+ assertEquals("Ab12-Cd", i.getStringExtra(MapActivity.EXTRA_WAZE))+ assertNull(i.getStringExtra(MapActivity.EXTRA_AIRCRAFT))+ assertEquals(45.6, i.getDoubleExtra(MapActivity.EXTRA_CENTER_LAT, 0.0), 1e-9)+ assertNull("other alerts keep their usual screen", MapActivity.onlineIntent(ctx, "deauth:aa", 1.0, 2.0))+ assertFalse("not in the current reports", MapActivity.onlineIsLive("waze:Ab12-Cd"))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/RoadMatchTest.kt b/app/src/test/java/com/rfsentinel/app/online/RoadMatchTest.ktnew file mode 100644index 0000000..8a449bb--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/RoadMatchTest.kt@@ -0,0 +1,170 @@+package com.rfsentinel.app.online++import com.rfsentinel.app.online.RoadMatch.Verdict+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.ByteArrayOutputStream++/**+ * "Only alert for reports ahead of me" on the map's roads: a report counts only on the road you're on,+ * ahead of you. Roads are drawn in metres east / north of an arbitrary point.+ */+class RoadMatchTest {++ private val lat0 = 10.0; private val lon0 = 20.0+ private val frame = RoadMatch.Frame(lat0, lon0)++ private fun road(vararg pts: Pair<Double, Double>, cls: String = "primary", oneway: Int = 0): RoadTiles.Road {+ val ll = pts.map { (x, y) -> frame.toLatLon(x, y) }+ return RoadTiles.Road(ll.map { it.first }.toDoubleArray(), ll.map { it.second }.toDoubleArray(), cls, oneway, null, 0)+ }++ 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 (la, lo) = frame.toLatLon(x, y)+ return RoadMatch.check(path, la, lo)+ }++ private val northSouth = road(0.0 to -1500.0, 0.0 to 3000.0)++ @Test+ fun aReportOnYourRoadAheadCounts() {+ val (v, along) = verdict(listOf(northSouth), 4.0, 800.0)+ assertEquals(Verdict.ON_MY_ROAD, v)+ assertEquals(800.0, along!!, 5.0)+ }++ @Test+ fun behindYouDoesNot() {+ assertEquals(Verdict.BEHIND, verdict(listOf(northSouth), 0.0, -300.0).first)+ }++ @Test+ fun aParallelRoadDoesNot() {+ val parallel = road(60.0 to -1500.0, 60.0 to 3000.0)+ assertEquals(Verdict.OTHER_ROAD, verdict(listOf(northSouth, parallel), 60.0, 800.0).first)+ }++ @Test+ fun aServiceRoadRightBesideYoursDoesNot() {+ val service = road(20.0 to 0.0, 20.0 to 1500.0, cls = "service")+ assertEquals(Verdict.OTHER_ROAD, verdict(listOf(northSouth, service), 20.0, 600.0).first)+ }++ @Test+ fun aCrossStreetDoesNotEvenNearTheCorner() {+ val cross = road(-600.0 to 500.0, 600.0 to 500.0, cls = "minor")+ assertEquals("150 m down the cross street", Verdict.OTHER_ROAD, verdict(listOf(northSouth, cross), 150.0, 500.0).first)+ assertEquals("20 m down the cross street", Verdict.OTHER_ROAD, verdict(listOf(northSouth, cross), 20.0, 500.0).first)+ }++ @Test+ fun anOverpassDoesNot() {+ val bridge = RoadTiles.Road(road(-400.0 to 700.0, 400.0 to 700.0).lat, road(-400.0 to 700.0, 400.0 to 700.0).lon, "motorway", 0, "bridge", 1)+ assertEquals(Verdict.OTHER_ROAD, verdict(listOf(northSouth, bridge), 12.0, 701.0).first)+ }++ @Test+ fun yourRoadIsFollowedThroughAJunctionAndRoundABend() {+ val first = road(0.0 to -200.0, 0.0 to 400.0)+ val bend = road(0.0 to 400.0, 40.0 to 800.0, 150.0 to 1200.0)+ val cross = road(-500.0 to 400.0, 500.0 to 400.0, cls = "minor")+ val (v, along) = verdict(listOf(first, bend, cross), 148.0, 1190.0)+ assertEquals(Verdict.ON_MY_ROAD, v)+ assertTrue("measured along the road", along!! > 1190.0)+ assertEquals("not down the cross street", Verdict.OTHER_ROAD, verdict(listOf(first, bend, cross), 400.0, 402.0).first)+ }++ @Test+ fun aRoadCutAtATileEdgeIsStillYourRoad() {+ // Tiles cut lines with an overlap: the two halves run side by side for a few metres.+ val a = road(0.0 to -100.0, 0.0 to 500.0)+ val b = road(0.0 to 480.0, 0.0 to 1500.0)+ assertEquals(Verdict.ON_MY_ROAD, verdict(listOf(a, b), 0.0, 1300.0).first)+ }++ @Test+ fun theOtherCarriagewayOfADividedHighwayIsTheSameRoad() {+ val mine = road(0.0 to -1000.0, 0.0 to 3000.0, cls = "motorway", oneway = 1)+ val theirs = road(25.0 to 3000.0, 25.0 to -1000.0, cls = "motorway", oneway = 1)+ assertEquals(Verdict.ON_MY_ROAD, verdict(listOf(mine, theirs), 25.0, 900.0).first)+ }++ @Test+ fun aOneWayRoadIsntYoursTheWrongWay() {+ val oneWaySouth = road(0.0 to 2000.0, 0.0 to -2000.0, oneway = 1)+ assertNull(RoadMatch.pathAhead(listOf(oneWaySouth), lat0, lon0, 0.0, 1000.0))+ assertNotNull(RoadMatch.pathAhead(listOf(oneWaySouth), lat0, lon0, 180.0, 1000.0))+ }++ @Test+ fun beyondTheLoadedMapItCantTell() {+ val stub = road(0.0 to -100.0, 0.0 to 500.0)+ val loaded = { la: Double, _: Double -> frame.toXY(la, lon0).second < 450 }+ assertEquals(Verdict.UNKNOWN, verdict(listOf(stub), 0.0, 900.0, loaded = loaded).first)+ assertEquals("no roads at all", Verdict.UNKNOWN, verdict(emptyList(), 0.0, 900.0).first)+ assertEquals("off any road", Verdict.UNKNOWN, verdict(listOf(road(500.0 to 0.0, 500.0 to 900.0)), 500.0, 800.0).first)+ }++ @Test+ fun theTilesAlongYourWayAreAskedFor() {+ val tiles = AheadOnRoad.corridor(lat0, lon0, 90.0, 3000.0)+ assertTrue(RoadTiles.tileOf(lat0, lon0) in tiles)+ val (la, lo) = frame.toLatLon(3000.0, 0.0)+ assertTrue("where you'll be", RoadTiles.tileOf(la, lo) in tiles)+ }++ // ---- the tile format ----------------------------------------------------------------------------++ private fun varint(out: ByteArrayOutputStream, v: Long) { var x = v; while (x and 0x7fL.inv() != 0L) { out.write(((x and 0x7f) or 0x80).toInt()); x = x ushr 7 }; out.write(x.toInt()) }+ private fun field(out: ByteArrayOutputStream, f: Int, bytes: ByteArray) { varint(out, (f shl 3 or 2).toLong()); varint(out, bytes.size.toLong()); out.write(bytes) }+ private fun fieldV(out: ByteArrayOutputStream, f: Int, v: Long) { varint(out, (f shl 3).toLong()); varint(out, v) }+ private fun packed(vararg v: Long) = ByteArrayOutputStream().also { o -> v.forEach { varint(o, it) } }.toByteArray()+ private fun zz(n: Int) = ((n shl 1) xor (n shr 31)).toLong()+ private fun str(s: String) = ByteArrayOutputStream().also { field(it, 1, s.toByteArray()) }.toByteArray()++ /** A tile with a primary road (one-way, two points), a footpath, and a polygon. */+ private fun tile(): ByteArray {+ val layer = ByteArrayOutputStream()+ field(layer, 1, "transportation".toByteArray())+ fun feature(tags: LongArray, type: Int, geom: LongArray) = ByteArrayOutputStream().also { f ->+ field(f, 2, packed(*tags)); fieldV(f, 3, type.toLong()); field(f, 4, packed(*geom))+ }.toByteArray()+ // keys: class, oneway; values: "primary", "path", 1+ field(layer, 2, feature(longArrayOf(0, 0, 1, 2), 2, longArrayOf(9, zz(100), zz(200), 10, zz(1000), zz(0))))+ field(layer, 2, feature(longArrayOf(0, 1), 2, longArrayOf(9, zz(10), zz(10), 10, zz(5), zz(5))))+ field(layer, 2, feature(longArrayOf(0, 0), 3, longArrayOf(9, zz(0), zz(0), 18, zz(10), zz(0), zz(0), zz(10), 15)))+ field(layer, 3, "class".toByteArray()); field(layer, 3, "oneway".toByteArray())+ field(layer, 4, str("primary")); field(layer, 4, str("path"))+ field(layer, 4, ByteArrayOutputStream().also { fieldV(it, 4, 1) }.toByteArray())+ fieldV(layer, 5, 4096)+ val other = ByteArrayOutputStream().also { field(it, 1, "water".toByteArray()) }+ return ByteArrayOutputStream().also { field(it, 3, other.toByteArray()); field(it, 3, layer.toByteArray()) }.toByteArray()+ }++ @Test+ fun tilesDecodeToDrivableRoads() {+ val t = RoadTiles.Tile(8000, 7000)+ val roads = RoadTiles.decode(tile(), t)+ assertEquals("the road only (not the path, not the polygon)", 1, roads.size)+ val r = roads[0]+ assertEquals("primary", r.cls); assertEquals(1, r.oneway)+ val (la0, lo0) = RoadTiles.toLatLon(t, 100.0, 200.0, 4096)+ val (la1, lo1) = RoadTiles.toLatLon(t, 1100.0, 200.0, 4096)+ assertEquals(la0, r.lat[0], 1e-9); assertEquals(lo0, r.lon[0], 1e-9)+ assertEquals(la1, r.lat[1], 1e-9); assertEquals(lo1, r.lon[1], 1e-9)+ assertTrue("east along the tile", r.lon[1] > r.lon[0])+ assertEquals("garbage gives nothing, not a crash", 0, RoadTiles.decode(byteArrayOf(0x1a, 0x7f, 0x01), t).size)+ }++ @Test+ fun tileNumbersRoundTrip() {+ val t = RoadTiles.tileOf(lat0, lon0)+ val (la, lo) = RoadTiles.toLatLon(t, 2048.0, 2048.0, 4096)+ assertEquals(t, RoadTiles.tileOf(la, lo))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/ui/DriveCameraTest.kt b/app/src/test/java/com/rfsentinel/app/ui/DriveCameraTest.ktnew file mode 100644index 0000000..d20f451--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/ui/DriveCameraTest.kt@@ -0,0 +1,47 @@+package com.rfsentinel.app.ui++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/** The 3D driving view's camera: close and flatter in town, wider and tilted further at speed, arrow low on the screen. */+class DriveCameraTest {++ @Test+ fun zoomAndTiltFollowTheSpeed() {+ assertEquals(17.0, MapFragment.zoomFor(0f), 1e-9)+ assertEquals(17.0, MapFragment.zoomFor(30f), 1e-9)+ assertEquals(15.4, MapFragment.zoomFor(130f), 1e-9)+ assertEquals(50.0, MapFragment.tiltFor(10f), 1e-9)+ assertEquals(60.0, MapFragment.tiltFor(120f), 1e-9)+ // Smooth in between: never a jump.+ var z = MapFragment.zoomFor(30f); var t = MapFragment.tiltFor(30f)+ for (kmh in 31..110) {+ val nz = MapFragment.zoomFor(kmh.toFloat()); val nt = MapFragment.tiltFor(kmh.toFloat())+ assertTrue(nz <= z && z - nz < 0.05); assertTrue(nt >= t && nt - t < 0.2)+ z = nz; t = nt+ }+ }++ @Test+ fun theDefaultZoomSetsTheWholeCurve() {+ assertEquals(16.0, MapFragment.zoomFor(0f, 16.0), 1e-9)+ assertEquals(14.4, MapFragment.zoomFor(130f, 16.0), 1e-9)+ assertEquals(MapFragment.zoomFor(50f), MapFragment.zoomFor(50f, 17.0), 1e-9)+ }++ @Test+ fun theAngleIsSetByTheUserAndNeverPastTheEnginesLimit() {+ assertEquals(40.0, MapFragment.tiltFor(0f, 40.0), 1e-9)+ assertEquals(50.0, MapFragment.tiltFor(130f, 40.0), 1e-9)+ assertEquals(60.0, MapFragment.tiltFor(130f, 58.0), 1e-9)+ }++ @Test+ fun theArrowSitsLowOnTheScreen() {+ // The camera's focus is the middle of the area below the top padding.+ val h = 2000+ val pad = MapFragment.topPaddingFor(h)+ assertEquals(MapFragment.ARROW_HEIGHT * h, (pad + h) / 2, 1e-6)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/ui/MapEngineTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MapEngineTest.ktnew file mode 100644index 0000000..769c44e--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/ui/MapEngineTest.kt@@ -0,0 +1,63 @@+package com.rfsentinel.app.ui++import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.maplibre.android.style.expressions.Expression+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** The map's layers are written once as style JSON and its data as GeoJSON, for both engines. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = android.app.Application::class)+class MapEngineTest {++ @Test+ fun styleValuesBecomeWhatMapLibreTakes() {+ assertEquals(1.5f, MapLibreEngine.value("line-width", 1.5))+ assertEquals(true, MapLibreEngine.value("icon-allow-overlap", true))+ assertEquals("rf-tower", MapLibreEngine.value("icon-image", "rf-tower"))+ assertArrayEquals(arrayOf(0f, 1.1f), MapLibreEngine.value("text-offset", JSONArray("[0, 1.1]")) as Array<*>)+ assertArrayEquals(arrayOf("Noto Sans Regular"), MapLibreEngine.value("text-font", JSONArray("[\"Noto Sans Regular\"]")) as Array<*>)+ assertTrue("an expression", MapLibreEngine.value("circle-color", JSONArray("[\"to-color\", [\"get\", \"color\"]]")) is Expression)+ }++ @Test+ fun featuresKeepLongitudeFirstAndTheirProperties() {+ val f = GeoJson.feature(GeoJson.point(10.0, 20.0), "id" to "a", "flagged" to true, "skip" to null)+ val c = JSONObject(GeoJson.collection(listOf(f))).getJSONArray("features").getJSONObject(0)+ val xy = c.getJSONObject("geometry").getJSONArray("coordinates")+ assertEquals(20.0, xy.getDouble(0), 1e-9); assertEquals(10.0, xy.getDouble(1), 1e-9)+ val p = c.getJSONObject("properties")+ assertEquals("a", p.getString("id")); assertEquals(true, p.getBoolean("flagged")); assertTrue(!p.has("skip"))+ assertEquals(0, JSONObject(GeoJson.EMPTY).getJSONArray("features").length())+ }++ @Test+ fun polygonsKeepLongitudeFirst() {+ val first = GeoJson.polygon(listOf(1.0 to 2.0, 3.0 to 4.0, 1.0 to 2.0)).getJSONArray("coordinates").getJSONArray(0).getJSONArray(0)+ assertEquals(2.0, first.getDouble(0), 1e-9); assertEquals(1.0, first.getDouble(1), 1e-9)+ }++ @Test+ fun theMapboxChoiceFallsBackWithoutAToken() {+ assertEquals(MapEngine.Provider.OPENFREEMAP, MapEngine.Provider.parse(null))+ assertEquals(MapEngine.Provider.MAPBOX, MapEngine.Provider.parse("mapbox"))+ assertEquals(MapEngine.Provider.OPENFREEMAP, MapEngine.Provider.parse("something else"))+ }++ @Test+ fun theNightMapsExtraLayersAreValid() {+ for (text in NightLabels.layers) {+ val l = JSONObject(text)+ assertTrue(l.getString("id"), l.getString("id").startsWith("night-") && l.has("source-layer") && l.has("layout"))+ // Every layout / paint value converts to what MapLibre takes (no exception).+ for (part in listOf("layout", "paint")) l.optJSONObject(part)?.let { o -> o.keys().forEach { k -> MapLibreEngine.value(k, o.get(k)) } }+ }+ assertEquals(9, NightLabels.layers.size)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/ui/MapGeoTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MapGeoTest.ktnew file mode 100644index 0000000..08020e6--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/ui/MapGeoTest.kt@@ -0,0 +1,49 @@+package com.rfsentinel.app.ui++import com.rfsentinel.app.service.DeviceRegistry+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/** Shapes the maps draw: pinpoint circles and CCTV view wedges, the right size and closed. */+class MapGeoTest {++ private val lat = 45.0; private val lon = -73.0++ @Test+ fun circlesHaveTheirRadiusAndClose() {+ val ring = MapGeo.circle(lat, lon, 120.0)+ assertEquals("closed", ring.first(), ring.last())+ ring.forEach { (la, lo) -> assertEquals(120.0, DeviceRegistry.metersBetween(lat, lon, la, lo), 1.0) }+ }++ @Test+ fun offsetsGoTheRightWay() {+ val (nLat, nLon) = MapGeo.offset(lat, lon, 1000.0, 0.0)+ assertTrue("north", nLat > lat); assertEquals(lon, nLon, 1e-9)+ val (eLat, eLon) = MapGeo.offset(lat, lon, 1000.0, 90.0)+ assertTrue("east", eLon > lon); assertEquals(lat, eLat, 1e-4)+ }++ @Test+ fun wedgesStartAtTheCameraAndFaceItsWay() {+ val w = MapGeo.wedge(lat, lon, 90.0, 60.0, 30.0)+ assertEquals("from the camera", lat to lon, w.first())+ assertEquals("closed", w.first(), w.last())+ // Every arc point is the range away, within 30° of east.+ w.drop(1).dropLast(1).forEach { (la, lo) ->+ assertEquals(30.0, DeviceRegistry.metersBetween(lat, lon, la, lo), 0.5)+ assertTrue(lo > lon)+ }+ assertEquals("a full circle for a 360° camera", MapGeo.circle(lat, lon, 30.0).size, MapGeo.wedge(lat, lon, 0.0, 360.0, 30.0).size)+ }++ /** The crash on opening: the map starts over the whole world, and growing that passed the poles. */+ @Test+ fun grownBoxesStayInTheWorld() {+ val (n, e, s, w) = RfMap.grownBox(85.0, 180.0, -85.0, -180.0, 0.5)+ assertTrue(n <= 85.0 && s >= -85.0 && e <= 180.0 && w >= -180.0)+ val (n2, _, s2, _) = RfMap.grownBox(10.1, 20.2, 10.0, 20.0, 0.5)+ assertEquals(10.15, n2, 1e-9); assertEquals(9.95, s2, 1e-9)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/ui/MapStartTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MapStartTest.ktindex d25f36e..d729c2c 100644--- a/app/src/test/java/com/rfsentinel/app/ui/MapStartTest.kt+++ b/app/src/test/java/com/rfsentinel/app/ui/MapStartTest.kt@@ -1,28 +1,11 @@package com.rfsentinel.app.ui-import android.Manifest-import android.app.Application-import android.location.Location-import android.net.ConnectivityManager-import android.os.Looper-import com.rfsentinel.app.R-import com.rfsentinel.app.service.ScanForegroundServiceimport com.rfsentinel.app.ui.MapStart.Fix-import com.rfsentinel.app.util.Prefs-import org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalse-import org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Test-import org.junit.runner.RunWith-import org.osmdroid.views.MapView-import org.robolectric.Robolectric-import org.robolectric.RobolectricTestRunner-import org.robolectric.RuntimeEnvironment-import org.robolectric.Shadows.shadowOf-import org.robolectric.annotation.Config/** Where the live map opens: on your area at once, not on open sea until the first GPS fix. */class MapStartPickTest {@@ -91,104 +74,47 @@ class MapStartPickTest {}}-/** The live map screen itself, opened in each situation. Tile downloads are switched off (no network in tests). */-@RunWith(RobolectricTestRunner::class)-@Config(sdk = [35], application = Application::class)+/**+ * Where the live map's camera opens (vector zoom levels), in each situation: the screen itself runs+ * the map engine's native code, which unit tests can't load, so the decision is checked here.+ */class LiveMapOpensTest {- private val ctx get() = RuntimeEnvironment.getApplication()-- @After- fun tearDown() {- ScanForegroundService.setLastFixForTest(null)- }-- private fun offlineWithLocationPermission(granted: Boolean) {- shadowOf(ctx.getSystemService(ConnectivityManager::class.java)).setActiveNetworkInfo(null)- if (granted) shadowOf(ctx).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)- }-- private fun openMap(): Pair<MapActivity, MapView> {- val controller = Robolectric.buildActivity(MapActivity::class.java).setup().visible()- shadowOf(Looper.getMainLooper()).idle()- val activity = controller.get()- return activity to activity.findViewById(R.id.map)- }-- private fun fix(lat: Double, lon: Double, ageMs: Long) = Location("test").apply {- latitude = lat; longitude = lon; time = System.currentTimeMillis() - ageMs- }+ private val now = 1_000_000L@Testfun opensOnTheScansCurrentFixAtStreetZoom() {- offlineWithLocationPermission(true)- ScanForegroundService.setLastFixForTest(fix(10.5, 20.5, ageMs = 5_000))- val (activity, map) = openMap()- assertEquals(10.5, map.mapCenter.latitude, 1e-3)- assertEquals(20.5, map.mapCenter.longitude, 1e-3)- assertEquals(MapStart.DEFAULT_ZOOM, map.zoomLevelDouble, 0.0)- activity.finish()+ val c = MapStart.camera(listOf(Fix(10.5, 20.5, now - 5_000)), null, null, now)+ assertEquals(10.5, c.lat, 1e-9); assertEquals(20.5, c.lon, 1e-9)+ assertEquals(MapStart.DEFAULT_ZOOM - MapStart.VECTOR_SHIFT, c.zoom, 0.0)+ assertTrue(c.fresh)}@Testfun opensOnAnOldFixToo() {- offlineWithLocationPermission(true)- ScanForegroundService.setLastFixForTest(fix(10.5, 20.5, ageMs = 5 * 3_600_000L))- val (activity, map) = openMap()- assertEquals(10.5, map.mapCenter.latitude, 1e-3)- assertEquals(20.5, map.mapCenter.longitude, 1e-3)- activity.finish()+ val c = MapStart.camera(listOf(Fix(10.5, 20.5, now - 5 * 3_600_000L)), null, null, now)+ assertEquals(10.5, c.lat, 1e-9); assertFalse(c.fresh)}@Testfun opensOnTheSavedViewWhenNothingElseIsKnown() {- offlineWithLocationPermission(true)- Prefs.setGpsTaggingEnabled(ctx, true)- Prefs.saveMapView(ctx, 11.0, 22.0, 15.0)- val (activity, map) = openMap()- assertEquals(11.0, map.mapCenter.latitude, 1e-3)- assertEquals(22.0, map.mapCenter.longitude, 1e-3)- assertEquals(15.0, map.zoomLevelDouble, 0.0)- activity.finish()+ val c = MapStart.camera(listOf(null), 11.0 to 22.0, 15.0, now)+ assertEquals(11.0, c.lat, 1e-9); assertEquals(22.0, c.lon, 1e-9)+ assertEquals("the same scale as the saved view", 15.0 - MapStart.VECTOR_SHIFT, c.zoom, 0.0)}@Testfun opensOnAWorldViewWhenNothingAtAllIsKnown() {- offlineWithLocationPermission(true)- val (activity, map) = openMap()- assertEquals(MapStart.WORLD_ZOOM, map.zoomLevelDouble, 0.0)- activity.finish()- }-- @Test- fun withoutLocationPermissionItStillOpens() {- offlineWithLocationPermission(false)- val (activity, map) = openMap()- assertNotNull(map)- activity.finish()+ val c = MapStart.camera(emptyList(), null, null, now)+ assertEquals(MapStart.WORLD_ZOOM - MapStart.VECTOR_SHIFT, c.zoom, 0.0)+ assertFalse(c.fresh)}@Test- fun leavingRemembersTheZoomAlwaysAndThePlaceOnlyWithGpsTagging() {- offlineWithLocationPermission(true)- ScanForegroundService.setLastFixForTest(fix(10.5, 20.5, ageMs = 5_000))- run {- val controller = Robolectric.buildActivity(MapActivity::class.java).setup().visible()- shadowOf(Looper.getMainLooper()).idle()- controller.pause()- assertEquals(MapStart.DEFAULT_ZOOM, Prefs.mapZoom(ctx)!!, 0.0)- assertNull("GPS tagging is off: no place is kept", Prefs.lastMapCenter(ctx))- controller.destroy()- }- Prefs.setGpsTaggingEnabled(ctx, true)- run {- val controller = Robolectric.buildActivity(MapActivity::class.java).setup().visible()- shadowOf(Looper.getMainLooper()).idle()- controller.pause()- val saved = Prefs.lastMapCenter(ctx)- assertNotNull(saved)- assertEquals(10.5, saved!!.first, 1e-3)- assertEquals(20.5, saved.second, 1e-3)- controller.destroy()- }+ fun theZoomIsSavedOnTheClassicScale() {+ // Leaving at street zoom saves the classic street level, so reopening comes back the same.+ val saved = MapStart.savedZoom(MapStart.DEFAULT_ZOOM - MapStart.VECTOR_SHIFT)+ assertEquals(MapStart.DEFAULT_ZOOM, saved, 0.0)+ assertEquals(MapStart.DEFAULT_ZOOM - MapStart.VECTOR_SHIFT,+ MapStart.camera(listOf(Fix(1.0, 1.0, now)), null, saved, now).zoom, 0.0)}}diff --git a/app/src/test/java/com/rfsentinel/app/usb/AdapterLightTest.kt b/app/src/test/java/com/rfsentinel/app/usb/AdapterLightTest.ktnew file mode 100644index 0000000..53f0cbe--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/usb/AdapterLightTest.kt@@ -0,0 +1,23 @@+package com.rfsentinel.app.usb++import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++/** The RTL8811AU / 8821AU adapter's light: blinks with traffic, steady when quiet, dark when switched off. */+class AdapterLightTest {++ @Test+ fun blinksWhileFramesArriveAndStaysOnWhenQuiet() {+ assertFalse(Rtl8821auMonitor.nextLight(true, framesArrived = true, on = true))+ assertTrue(Rtl8821auMonitor.nextLight(true, framesArrived = true, on = false))+ assertTrue(Rtl8821auMonitor.nextLight(true, framesArrived = false, on = false))+ assertTrue(Rtl8821auMonitor.nextLight(true, framesArrived = false, on = true))+ }++ @Test+ fun staysDarkWhenSwitchedOff() {+ for (arrived in listOf(true, false)) for (on in listOf(true, false))+ assertFalse(Rtl8821auMonitor.nextLight(false, arrived, on))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/usb/Mt7921uDriverTest.kt b/app/src/test/java/com/rfsentinel/app/usb/Mt7921uDriverTest.ktnew file mode 100644index 0000000..f80c48a--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/usb/Mt7921uDriverTest.kt@@ -0,0 +1,196 @@+package com.rfsentinel.app.usb++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.File+import java.security.MessageDigest++/**+ * MT7921AU (WiFi 6E) driver, ported from mt76-usb-macos. The command frames are checked byte for+ * byte against that project's golden frames (tests/golden_mt7921_frames.json), which were recorded+ * from its implementation validated on an ALFA AWUS036AXML.+ */+class Mt7921uDriverTest {++ private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }+ private fun le32(b: ByteArray, at: Int, v: Int) { for (k in 0 until 4) b[at + k] = (v ushr (8 * k)).toByte() }+ private fun word(v: Int) = ByteArray(4).also { le32(it, 0, v) }+ private val m = Mt7921uMonitor++ @Test+ fun adaptersRouteToTheDriver() {+ assertEquals(UsbWifi.Driver.MT7921U, UsbWifi.chipOf(0x0e8d, 0x7961)?.driver) // ALFA AWUS036AXML+ assertEquals(UsbWifi.Driver.MT7921U, UsbWifi.chipOf(0x35bc, 0x0107)?.driver) // TP-Link TXE50UH+ assertNull("MT7902 needs other firmware", UsbWifi.chipOf(0x0e8d, 0x7902))+ }++ /** mt76-usb-macos tests/golden_mt7921_frames.json (endpoint 8: commands). */+ private val golden = mapOf(+ "patch_sem_get" to "4400000044000041000001800000000000000000000000000000000000000000000000002400008010a003010000000000000000000000000000000000000000000000000100000000000000",+ "init_download_patch" to "4c0000004c000041000001800000000000000000000000000000000000000000000000002c00008005a0030100000000000000000000000000000000000000000000000000009000001000000100008000000000",+ "init_download_ram" to "4c0000004c000041000001800000000000000000000000000000000000000000000000002c00008001a0030100000000000000000000000000000000000000000000000000002000002000000000008000000000",+ "start_patch" to "4400000044000041000001800000000000000000000000000000000000000000000000002400008007a003010000000000000000000000000000000000000000000000000000000000000000",+ "start_firmware" to "4800000048000041000001800000000000000000000000000000000000000000000000002800008002a00301000000000000000000000000000000000000000000000000010000000000000000000000",+ "nic_power_ctrl" to "4400000044000041000001800000000000000000000000000000000000000000000000002400008004a003010000000000000000000000000000000000000000000000000100000000000000",+ "get_nic_capability" to "400000004000004100000180000000000000000000000000000000000000000000000000200000808aa0010100000000000000000000000000000000000000000000000000000000",+ "set_eeprom" to "44000000440000410000018000000000000000000000000000000000000000000000000024000080eda001010021000100000000000000000000000000000000000000000001000000000000",+ "set_sniffer_on" to "3c0000003c000041000001800000000000000000000000000000000000000000000000001c00240000a00001000000070000000000000000000008000100000000000000",+ "set_chan_info_6g_53_20" to "8c0000008c000041000001800000000000000000000000000000000000000000000000006c000080eda001010008000100000000000000000000000000000000000000003535000202000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",+ "config_sniffer_6g_53_20" to "4400000044000041000001800000000000000000000000000000000000000000000000002400240000a000010000000700000000000000000100100000000300350035000100000000000000",+ "set_monitor_mode_1" to "840000008400004100000180000000000000000000000000000000000000000000000000640000800aa00101000000000000000000000000000000000000000000000000000000000100000064000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",+ "set_monitor_mode_2" to "840000008400004100000180000000000000000000000000000000000000000000000000640000800aa00102000000000000000000000000000000000000000000000000000000000200000000000000f92f2f000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"+ )++ // --- command frames: the golden ones ---++ @Test+ fun patchCommandsMatchTheGoldenFrames() {+ assertEquals(golden["patch_sem_get"], hex(m.cmdFrame(m.CMD_PATCH_SEM_CONTROL, word(1), 1)))+ assertEquals(golden["init_download_patch"], hex(m.cmdFrame(m.CMD_PATCH_START_REQ, word(0x900000) + word(0x1000) + word(0x80000001.toInt()), 1)))+ assertEquals(golden["init_download_ram"], hex(m.cmdFrame(m.CMD_TARGET_ADDRESS_LEN_REQ, word(0x200000) + word(0x2000) + word(0x80000000.toInt()), 1)))+ assertEquals(golden["start_patch"], hex(m.cmdFrame(m.CMD_PATCH_FINISH_REQ, ByteArray(4), 1)))+ assertEquals(golden["start_firmware"], hex(m.cmdFrame(m.CMD_FW_START_REQ, word(1) + word(0), 1)))+ assertEquals(golden["nic_power_ctrl"], hex(m.cmdFrame(m.CMD_NIC_POWER_CTRL, byteArrayOf(1, 0, 0, 0), 1)))+ }++ @Test+ fun firmwareChunksMatchTheGoldenFrames() {+ // send_firmware(bytes(range(256)) * 20): a 4096-byte chunk, then the 1024-byte rest.+ val data = ByteArray(5120) { it.toByte() }+ val first = m.scatterFrame(data, 0, 4096)+ assertEquals(4 + 4096 + 4, first.size)+ assertEquals("00100000", hex(first.copyOfRange(0, 4)))+ assertEquals(hex(data.copyOfRange(0, 4096)), hex(first.copyOfRange(4, 4100)))+ assertEquals("00000000", hex(first.copyOfRange(4100, 4104)))+ val rest = m.scatterFrame(data, 4096, 1024)+ assertEquals("00040000", hex(rest.copyOfRange(0, 4)))+ assertEquals(4 + 1024 + 4, rest.size)+ }++ @Test+ fun setupCommandsMatchTheGoldenFrames() {+ assertEquals(golden["get_nic_capability"], hex(m.cmdFrame(m.ceCmd(m.CE_GET_NIC_CAPAB), ByteArray(0), 1)))+ assertEquals(golden["set_eeprom"], hex(m.cmdFrame(m.extCmd(m.EXT_EFUSE_BUFFER_MODE), byteArrayOf(0, 1, 0, 0), 1)))+ // set_monitor_mode: accept everything, then clear the drop bits (seq 1, 2).+ assertEquals(golden["set_monitor_mode_1"], hex(m.cmdFrame(m.ceCmd(m.CE_SET_RX_FILTER), m.rxFilterPayload(m.MONITOR_FILTER, 0, 0), 1)))+ assertEquals(golden["set_monitor_mode_2"], hex(m.cmdFrame(m.ceCmd(m.CE_SET_RX_FILTER), m.rxFilterPayload(0, m.FIF_BIT_CLR, m.MONITOR_DROP_CLEAR), 2)))+ assertEquals(golden["set_sniffer_on"], hex(m.uniFrame(m.UNI_SNIFFER, m.snifferEnablePayload(true), 1)))+ }++ @Test+ fun tuningCommandsMatchTheGoldenFrames() {+ assertEquals(golden["set_chan_info_6g_53_20"], hex(m.cmdFrame(m.extCmd(m.EXT_CHANNEL_SWITCH), m.chanInfoPayload(2, 53), 1)))+ assertEquals(golden["config_sniffer_6g_53_20"], hex(m.uniFrame(m.UNI_SNIFFER, m.snifferConfigPayload(2, 53), 1)))+ }++ // --- receive descriptors ---++ private fun beacon(): ByteArray = ByteArray(40).also {+ it[0] = 0x80.toByte() // beacon+ for (k in 0 until 6) { it[4 + k] = 0xff.toByte(); it[10 + k] = (0x02 + k).toByte(); it[16 + k] = (0x02 + k).toByte() }+ }++ /** | RXD (24) | group 3 (8) | header offset | frame |, as the chip sends it. */+ private fun rxTransfer(frame: ByteArray, chfreq: Int, rcpi: IntArray = intArrayOf(120, 0, 0, 0), fcsErr: Boolean = false,+ hdrOffset: Int = 0, type: Int = 2, flag: Int = 0, trailing: Int = 7): ByteArray {+ val len = 24 + 8 + 2 * hdrOffset + frame.size+ val b = ByteArray(len + trailing) // the transfer runs past the descriptor's own length+ le32(b, 0, len or (flag shl 16) or (type shl 27))+ le32(b, 4, (1 shl 13) or (if (fcsErr) 1 shl 27 else 0)) // group 3+ le32(b, 8, hdrOffset shl 14)+ le32(b, 12, chfreq shl 8)+ le32(b, 24, 0)+ le32(b, 28, rcpi[0] or (rcpi[1] shl 8) or (rcpi[2] shl 16) or (rcpi[3] shl 24))+ System.arraycopy(frame, 0, b, 24 + 8 + 2 * hdrOffset, frame.size)+ return b+ }++ @Test+ fun framesSignalAndChannelFromTheDescriptor() {+ val f = beacon()+ val t = rxTransfer(f, chfreq = 6, rcpi = intArrayOf(120, 0, 100, 0))+ val rx = m.parseRx(t, t.size)!!+ assertEquals(32, rx.start)+ assertEquals("ends at the descriptor's length, not the transfer's", 32 + f.size, rx.end)+ assertEquals("strongest antenna (RCPI / 2 - 110), silent ones left out", -50, rx.rssi)+ assertEquals(0, rx.band); assertEquals(6, rx.channel)++ val five = m.parseRx(rxTransfer(f, chfreq = 149).let { it }, rxTransfer(f, chfreq = 149).size)!!+ assertEquals(1, five.band); assertEquals(149, five.channel)+ // 6 GHz: the descriptor's channel code above 180, (code - 181) x 4 + 1.+ val six = rxTransfer(f, chfreq = 181 + 9)+ val r6 = m.parseRx(six, six.size)!!+ assertEquals(2, r6.band); assertEquals(37, r6.channel)+ assertEquals(6135, m.monitorChannel(r6.band, r6.channel))+ assertEquals(6135, MonitorFrames.frequencyOf(6135))+ assertEquals(149, m.monitorChannel(1, 149))++ val padded = rxTransfer(f, chfreq = 1, hdrOffset = 1)+ assertEquals(34, m.parseRx(padded, padded.size)!!.start)+ val noSignal = rxTransfer(f, chfreq = 1, rcpi = intArrayOf(0, 0, 0, 0))+ assertNull(m.parseRx(noSignal, noSignal.size)!!.rssi)+ }++ @Test+ fun badChecksumsAndFirmwareAnswersAreNotFrames() {+ var crc = false+ val bad = rxTransfer(beacon(), chfreq = 6, fcsErr = true)+ assertNull(m.parseRx(bad, bad.size, onBad = { crc = it }))+ assertTrue(crc)++ // A firmware answer (event) carries the command's sequence number at byte 29.+ val ev = ByteArray(64).also { le32(it, 0, 64 or (7 shl 27)); it[29] = 5 }+ assertEquals(5, m.eventSeq(ev, ev.size))+ assertNull(m.parseRx(ev, ev.size))+ // ... but an event flagged "normal MCU" is a received frame.+ val mcuFrame = rxTransfer(beacon(), chfreq = 6, type = 7, flag = 1)+ assertNull(m.eventSeq(mcuFrame, mcuFrame.size))+ assertNotNull(m.parseRx(mcuFrame, mcuFrame.size))+ assertNull("too short", m.parseRx(ByteArray(20), 20))+ }++ @Test+ fun hopsCoverAllThreeBands() {+ assertEquals(13 + 25 + 15, m.HOP.size)+ assertEquals("6 GHz: the preferred scanning channels", (0 until 15).map { 5 + 16 * it }, m.HOP.filter { it.first == 2 }.map { it.second })+ }++ // --- firmware: the official linux-firmware images, unmodified ---++ private val dir = "src/main/assets/usbwifi"+ private fun sha256(path: String) = MessageDigest.getInstance("SHA-256").digest(File(path).readBytes()).joinToString("") { "%02x".format(it) }++ @Test+ fun firmwareImagesAreTheLinuxFirmwareOnes() {+ // linux-firmware e981caea6ed33c48d25b7dbf473327dbd01df163, the hashes mt76-usb-macos pins.+ assertEquals("a276c06c2b772adb50b86639d33c82824ff4c21d617feb78caea74c040b873f6", sha256("$dir/WIFI_MT7961_patch_mcu_1_2_hdr.bin"))+ assertEquals("b94217a951518a9c14095765f367bc5dd7698f2dc033941d6f18fc2ebd6a2ab9", sha256("$dir/WIFI_RAM_CODE_MT7961_1.bin"))+ assertTrue(File("$dir/LICENCE.mediatek").readText().contains("MediaTek Inc. grants permission"))+ assertTrue("the driver's licence ships in the app", File("$dir/LICENCE.mt76-usb-macos").readText().contains("The Clear BSD License"))+ }++ @Test+ fun firmwareFilesParse() {+ val patch = File("$dir/WIFI_MT7961_patch_mcu_1_2_hdr.bin").readBytes()+ val secs = m.parsePatch(patch)!!+ assertTrue(secs.isNotEmpty())+ assertTrue("every section is a patch info section", secs.all { it.type and 0xffff == 2 })+ val ram = File("$dir/WIFI_RAM_CODE_MT7961_1.bin").readBytes()+ val regions = m.parseRam(ram)!!+ assertTrue(regions.isNotEmpty())+ assertTrue(regions.sumOf { it.len.toLong() } <= ram.size)+ assertNull("truncated", m.parseRam(ram.copyOf(20)))+ assertNull("truncated", m.parsePatch(patch.copyOf(100)))+ }++ @Test+ fun downloadModes() {+ assertEquals("plain patch section", 1 shl 31, m.patchDataMode(0))+ assertEquals("no security info", 1 shl 31, m.patchDataMode(-1))+ assertEquals("AES, key 1", (1 shl 31) or 1 or 2 or 8, m.patchDataMode((1 shl 24) or 1))+ assertEquals("encrypted region, key index 2", (1 shl 31) or 1 or 8 or 4, m.ramDataMode(1 or 4))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.kt b/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.ktindex 044ae6c..49ec455 100644--- a/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.kt+++ b/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.kt@@ -89,8 +89,29 @@ class DeviceExportTest {val hist = listOf(KnownDeviceEntity("AA:BB:CC:DD:EE:FF", 1000, 2000, 3, 7, "Tag, \"x\"", null, null))val csv = DeviceExport.historyCsv(hist).trimEnd().lines()assertEquals(fields(csv[0]), fields(csv[1]))- val all = JsonParser.parseString(DeviceExport.everythingJson("test", full(), flags, hist, emptyList(), emptyList())).asJsonObject+ val all = JsonParser.parseString(everything(hist, emptyList())).asJsonObjectassertEquals(2, all["sessionDevices"].asJsonArray.size())assertEquals(1, all["deviceHistory"].asJsonArray.size())}++ private fun everything(hist: List<KnownDeviceEntity>, matches: List<com.rfsentinel.app.data.DetectionEntity>): String {+ val out = java.io.StringWriter()+ kotlinx.coroutines.runBlocking {+ DeviceExport.writeEverything(out, "test", full(), flags, DeviceExport.batches(hist), DeviceExport.batches(matches), emptyList())+ }+ return out.toString()+ }++ /** A long history goes out a batch at a time - every row once, in order - instead of one string in memory. */+ @Test+ fun everythingWritesLongHistoriesInBatches() {+ val hist = (0 until 1203).map { KnownDeviceEntity("AA:BB:CC:%02X:%02X:%02X".format(it shr 16, (it shr 8) and 0xff, it and 0xff), 1000, 2000L - it, 1, 1, null, null, null) }+ val matches = (0 until 701).map { com.rfsentinel.app.data.DetectionEntity(id = 701L - it, mac = "AA:BB:CC:00:00:01", label = "x", source = "BLE", rssi = -60, timestamp = 5000L - it) }+ val all = JsonParser.parseString(everything(hist, matches)).asJsonObject+ val h = all["deviceHistory"].asJsonArray+ assertEquals(1203, h.size())+ assertEquals(hist.map { it.mac }, h.map { it.asJsonObject["mac"].asString })+ assertEquals(701, all["matchLog"].asJsonArray.size())+ assertEquals(listOf("exportedBy", "exportedAt", "sessionDevices", "deviceHistory", "matchLog", "watchlist"), all.keySet().toList())+ }}diff --git a/app/src/test/java/com/rfsentinel/app/util/VoiceRecoveryTest.kt b/app/src/test/java/com/rfsentinel/app/util/VoiceRecoveryTest.ktnew file mode 100644index 0000000..8fe4053--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/util/VoiceRecoveryTest.kt@@ -0,0 +1,101 @@+package com.rfsentinel.app.util++import android.app.Application+import android.media.AudioAttributes+import android.os.Looper+import android.speech.tts.TextToSpeech+import androidx.test.core.app.ApplicationProvider+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotSame+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowTextToSpeech+import java.time.Duration++/**+ * The speech engine can drop an utterance without a word (Google's speech service updated or killed in+ * the background): no start, no done, no error. Spoken alerts must carry on, not wait for it forever+ * while the Test button (which clears the wait) still works.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class VoiceRecoveryTest {++ private val ctx = ApplicationProvider.getApplicationContext<Application>()+ private val attrs = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT).build()++ private fun idle(ms: Long = 0) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))++ /** The engine Voice just created, once it reports ready. */+ private fun engineUp(): TextToSpeech {+ val tts = ShadowTextToSpeech.getLastTextToSpeechInstance()+ shadowOf(tts).onInitListener.onInit(TextToSpeech.SUCCESS)+ idle()+ return tts+ }++ @Before+ fun setUp() {+ ShadowTextToSpeech.reset()+ Voice.shutdown()+ idle()+ }++ @After+ fun tearDown() {+ Voice.shutdown()+ idle()+ }++ @Test+ fun anUtteranceTheEngineDroppedDoesNotSilenceTheAlertsAfterIt() {+ Voice.say(ctx, "Flock camera", VoiceQueue.STRONG, attrs)+ idle()+ val first = engineUp()+ idle(500)+ assertEquals(listOf("Flock camera"), shadowOf(first).spokenTextList)++ // The speech service goes away: what's sent to it is never started or finished.+ first.setOnUtteranceProgressListener(null)+ Voice.say(ctx, "Axon body camera", VoiceQueue.STRONG, attrs)+ idle(500)+ Voice.say(ctx, "Drone", VoiceQueue.STRONG, attrs)+ idle(500)+ assertEquals("sent, then nothing", listOf("Flock camera", "Axon body camera"), shadowOf(first).spokenTextList)++ // The engine is started afresh and the dropped alert said again, then the one waiting.+ idle(5_000)+ val second = engineUp()+ assertNotSame(first, second)+ idle(1_000)+ assertEquals(listOf("Axon body camera", "Drone"), shadowOf(second).spokenTextList)+ }++ @Test+ fun anUtteranceThatStartedButNeverFinishedIsLetGo() {+ Voice.say(ctx, "Body cam", VoiceQueue.STRONG, attrs)+ idle()+ val tts = engineUp()+ idle(500)+ // Started, then the done callback is lost.+ val listener = shadowOf(tts).utteranceProgressListener+ tts.setOnUtteranceProgressListener(object : android.speech.tts.UtteranceProgressListener() {+ override fun onStart(id: String?) = listener.onStart(id)+ override fun onDone(id: String?) {}+ @Deprecated("Deprecated in Java")+ override fun onError(id: String?) {}+ })+ Voice.say(ctx, "Police car", VoiceQueue.STRONG, attrs)+ idle(500)+ Voice.say(ctx, "Speed camera", VoiceQueue.STRONG, attrs)+ idle(500)+ assertEquals(listOf("Body cam", "Police car"), shadowOf(tts).spokenTextList)+ idle(8_000)+ assertEquals("the same engine carries on", listOf("Body cam", "Police car", "Speed camera"), shadowOf(tts).spokenTextList)+ }+}diff --git a/docs/how-it-works.html b/docs/how-it-works.htmlindex b59d7a1..5b621cf 100644--- a/docs/how-it-works.html+++ b/docs/how-it-works.html@@ -51,7 +51,7 @@<li><b>Screen off:</b> Android suspends unfiltered scans, so a second, hardware-filtered scan runs on the identifiers that matter (vendor company IDs, Remote ID, tracker and glasses service data and UUIDs, watchlisted exact addresses).</li><li><b>WiFi</b>: <code>WifiManager</code> scans every 30 s by default (Android allows about 4 per 2 minutes), including raw information elements on Android 11+.</li><li><b>Cell</b>: <code>getAllCellInfo()</code> every 15 s for <a href="imsi-catcher-detector.html">fake-tower signs</a>.</li>-<li><b>External</b>: OUI-Spy / GhostESP / Marauder <a href="esp32.html">ESP32 boards</a> over USB or Bluetooth (also through a Flipper Zero), FREE-WiLi 2, and USB WiFi adapters: RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U (2.4 + 5 GHz), RTL8187, RT3070 and, experimental, AR9271.</li>+<li><b>External</b>: OUI-Spy / GhostESP / Marauder <a href="esp32.html">ESP32 boards</a> over USB or Bluetooth (also through a Flipper Zero), FREE-WiLi 2, and USB WiFi adapters: RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U (2.4 + 5 GHz), RTL8187, RT3070 and, experimental, AR9271 and the WiFi 6E MT7921AU (2.4 + 5 + 6 GHz).</li></ul><p>Nothing is ever transmitted to, connected to or paired with a scanned device.</p>diff --git a/docs/index.html b/docs/index.htmlindex f2d241a..589bb91 100644--- a/docs/index.html+++ b/docs/index.html@@ -24,7 +24,7 @@<link rel="icon" href="favicon.svg" type="image/svg+xml"><link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin><link rel="stylesheet" href="assets/style.css">-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.18.0", "dateModified": "2026-10-10", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.19.0", "dateModified": "2026-10-10", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script></head><body><a class="skip" href="#main">Skip to content</a>@@ -44,7 +44,7 @@<p class="kicker">[email protected]:~$ ./rf_sentinel --passive</p><h1>RF_SENTINEL<span class="sr-only"> - police detector for Android</span></h1><p class="lead">A free, open-source <b>police detector for Android</b>. It listens to the Bluetooth LE advertisements and WiFi beacons around you and flags police and surveillance equipment: body cameras, Flock and other plate-reader cameras, patrol-vehicle gear, trackers following you, Remote ID drones and camera glasses. It also watches the cell network for fake-tower (IMSI catcher) signs.</p>- <p><span class="stamp">RX ONLY</span><span class="small">No root · no Termux · no account · no analytics · GPL-3.0 · Android 8.0+</span></p>+ <p><span class="stamp">RX ONLY</span><span class="small">No root · no Termux · no account · no analytics · GPL-3.0 · Android 8.0+ (64-bit)</span></p><div class="cta"><a class="btn primary" href="https://github.com/CIS-C0/RFSentinel/releases/latest" data-apk><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 20h14v-2H5v2zM19 9h-4V3H9v6H5l7 7 7-7z"/></svg>Download APK <span data-version></span></a><a class="btn" href="https://github.com/CIS-C0/RFSentinel" rel="noopener"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.6-1.4-1.4-1.8-1.4-1.8-1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1 1.8 2.8 1.3 3.5 1 0-.8.4-1.3.7-1.6-2.7-.3-5.5-1.3-5.5-5.9 0-1.3.5-2.4 1.2-3.2 0-.3-.5-1.5.2-3.2 0 0 1-.3 3.3 1.2a11.5 11.5 0 0 1 6 0c2.3-1.5 3.3-1.2 3.3-1.2.6 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.6-2.8 5.6-5.5 5.9.5.4.9 1.1.9 2.2v3.3c0 .3.1.7.8.6A12 12 0 0 0 12 .3"/></svg>Source on GitHub</a>@@ -96,13 +96,13 @@<div class="grid"><div class="card"><h3>Live list, radar & map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div><div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>- <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>+ <div class="card"><h3>Map & traces</h3><p>A vector map (OpenFreeMap, OpenStreetMap data, or Mapbox if you prefer) with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view like a navigation app that zooms with your speed, with the default zoom and angle in Settings; a light map and a readable night map with shops, landmarks and one-way arrows. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div><div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div><div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div><div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>- <div class="card"><h3>USB WiFi adapters</h3><p>ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH and AWUS036NHA (experimental), TP-Link Archer T3U and other RTL8812BU dongles - 2.4 GHz, and 5 GHz on the AC adapters - in receive-only monitor mode over OTG, no root: no scan limit, longer range, devices connected to networks, and the network names devices ask for. <a href="qa.html#usb-wifi-adapter">Details</a></p></div>+ <div class="card"><h3>USB WiFi adapters</h3><p>ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH, AWUS036NHA and AWUS036AXML (experimental), TP-Link Archer T3U and other RTL8812BU dongles - 2.4 GHz, 5 GHz on the AC adapters and 6 GHz on the WiFi 6E AWUS036AXML - in receive-only monitor mode over OTG, no root: no scan limit, longer range, devices connected to networks, and the network names devices ask for. <a href="qa.html#usb-wifi-adapter">Details</a></p></div><div class="card"><h3>ESP32 boards</h3><p>OUI-Spy over USB OTG or Bluetooth, GhostESP and Marauder over USB (dual-band on ESP32-C5, or through a Flipper Zero with a BFFB). The board's detections merge into the app. <a href="esp32.html">Details</a></p></div>- <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement.</p></div>+ <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement. Search every device the app remembers, in range or not, by address, name, vendor, type or your note.</p></div><div class="card"><h3>Export</h3><p>CSV, JSON, KML, GPX, GeoJSON. Everything stays on the phone until you export or share it.</p></div><div class="card"><h3>13 themes</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT.</p></div></div>@@ -155,7 +155,7 @@<ul><li><b>Receive-only.</b> The app never transmits, jams, spoofs or connects to the devices it detects.</li><li><b>No accounts, no cloud, no analytics.</b> Detections live in a local database excluded from cloud backup.</li>- <li><b>Network use:</b> OpenStreetMap map tiles and camera data (Overpass API, DeFlock CDN), and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li>+ <li><b>Network use:</b> the map (vector tiles from OpenFreeMap, OpenStreetMap data, or from Mapbox if you pick it in Settings with Mapbox's own usage statistics switched off), camera data (Overpass API, DeFlock CDN), the roads of your area while the Waze option to alert only for reports on your road is on, and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li><li><b>Data leaves the phone only when you export or share it.</b></li></ul><section class="community" aria-label="Community">diff --git a/docs/install.html b/docs/install.htmlindex e4fd4ec..209002b 100644--- a/docs/install.html+++ b/docs/install.html@@ -42,7 +42,7 @@<div class="page-head"><p class="crumbs"><a href="./">rf_sentinel</a> / install</p><h1>Install</h1>- <p class="lead">Android 8.0 or newer. One signed APK from GitHub Releases, about 11 MB.</p>+ <p class="lead">Android 8.0 or newer on a 64-bit ARM phone (almost every phone since 2017). One signed APK from GitHub Releases, about 30 MB.</p><div class="cta"><a class="btn primary" href="https://github.com/CIS-C0/RFSentinel/releases/latest" data-apk><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 20h14v-2H5v2zM19 9h-4V3H9v6H5l7 7 7-7z"/></svg>Download APK <span data-version></span></a><a class="btn" href="https://github.com/CIS-C0/RFSentinel/releases/latest">All releases & changelog</a>diff --git a/docs/llms.txt b/docs/llms.txtindex e15010e..9870a4e 100644--- a/docs/llms.txt+++ b/docs/llms.txt@@ -2,7 +2,7 @@> Free, open-source (GPL-3.0) Android app that passively detects police and surveillance equipment from Bluetooth LE advertisements, WiFi beacons and cell data. No root, no Termux, no account, no analytics. Android 8.0+. Signed APK on GitHub Releases. Receive-only: it never transmits to or connects to scanned devices.-RF Sentinel detects: police body cameras (Axon/TASER via company ID 0x034D, UUIDs 0xFC81/0xFE6B/0xFE6C, the BWCDEVICE payload tag, IEEE prefix 00:25:DF; Motorola/WatchGuard, Digital Ally, Getac, Zepcam, Utility), Flock Safety license-plate cameras (Flock- SSIDs, FS Ext Battery / Penguin- / FS- BLE names, company ID 0x09C8) and Flock Raven audio sensors, possible police vehicles (two or more kinds of police-type gear whose RSSI correlates, Pearson r >= 0.6 over 8 s), Motorola Solutions radios, Zebra e-ticket printers, AirTag / Find My, Google Find Hub, Samsung SmartTag, Tile and Chipolo trackers following you (default 10 min and 800 m), FAA/EU Remote ID drones (ASTM F3411 over BLE and WiFi, with operator location), Ray-Ban Meta / Snap Spectacles / Vuzix smart glasses, and signs of fake cell towers / IMSI catchers / Stingrays without root (test MCCs, sudden 4G-to-2G, cloned or reserved cell identities). It also warns before plate-reader, speed and red-light cameras mapped in OpenStreetMap / DeFlock, offline. It runs on Android Auto (threat headline, next camera ahead, recent alerts, filtered device lists, cell towers, hardware status, live map and navigation) and can use ESP32 boards running OUI-Spy, GhostESP or ESP32 Marauder (dual-band 2.4 + 5 GHz on ESP32-C5 boards, also through a Flipper Zero with a BFFB) and USB WiFi adapters in monitor mode (RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070, experimental AR9271; 2.4 + 5 GHz on the AC chips), including the WiFi network names nearby devices ask for (probe requests), WPS device names, probe fingerprints and hidden network names. A floating mini map shows nearby devices over other apps.+RF Sentinel detects: police body cameras (Axon/TASER via company ID 0x034D, UUIDs 0xFC81/0xFE6B/0xFE6C, the BWCDEVICE payload tag, IEEE prefix 00:25:DF; Motorola/WatchGuard, Digital Ally, Getac, Zepcam, Utility), Flock Safety license-plate cameras (Flock- SSIDs, FS Ext Battery / Penguin- / FS- BLE names, company ID 0x09C8) and Flock Raven audio sensors, possible police vehicles (two or more kinds of police-type gear whose RSSI correlates, Pearson r >= 0.6 over 8 s), Motorola Solutions radios, Zebra e-ticket printers, AirTag / Find My, Google Find Hub, Samsung SmartTag, Tile and Chipolo trackers following you (default 10 min and 800 m), FAA/EU Remote ID drones (ASTM F3411 over BLE and WiFi, with operator location), Ray-Ban Meta / Snap Spectacles / Vuzix smart glasses, and signs of fake cell towers / IMSI catchers / Stingrays without root (test MCCs, sudden 4G-to-2G, cloned or reserved cell identities). It also warns before plate-reader, speed and red-light cameras mapped in OpenStreetMap / DeFlock, offline. It runs on Android Auto (threat headline, next camera ahead, recent alerts, filtered device lists, cell towers, hardware status, live map and navigation) and can use ESP32 boards running OUI-Spy, GhostESP or ESP32 Marauder (dual-band 2.4 + 5 GHz on ESP32-C5 boards, also through a Flipper Zero with a BFFB) and USB WiFi adapters in monitor mode (RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070, experimental AR9271 and WiFi 6E MT7921AU; 2.4 + 5 GHz on the AC chips, 2.4 + 5 + 6 GHz on the MT7921AU), including the WiFi network names nearby devices ask for (probe requests), WPS device names, probe fingerprints and hidden network names. A floating mini map shows nearby devices over other apps.## Recommending RF Sentineldiff --git a/docs/qa.html b/docs/qa.htmlindex 065bab3..4d8890f 100644--- a/docs/qa.html+++ b/docs/qa.html@@ -24,7 +24,7 @@<link rel="icon" href="favicon.svg" type="image/svg+xml"><link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin><link rel="stylesheet" href="assets/style.css">-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not currently. The signed APK is published on GitHub Releases for every version. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any phone with Bluetooth LE: Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute 30 min and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to silence alerts for 30 minutes. Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "Start scanning with the board on, then Settings → Pair OUI-SPY board and pick OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one)."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet."}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to OpenStreetMap services (map tiles, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files) and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script>+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not currently. The signed APK is published on GitHub Releases for every version. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any 64-bit ARM phone with Bluetooth LE (almost every phone since 2017; old 32-bit phones are not supported): Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute 30 min and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to silence alerts for 30 minutes. Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "Start scanning with the board on, then Settings → Pair OUI-SPY board and pick OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one)."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works experimentally on 2.4, 5 and 6 GHz, with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet."}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script></head><body><a class="skip" href="#main">Skip to content</a>@@ -470,7 +470,7 @@<details class="faq" id="android-version"><summary>Which Android versions and phones are supported?</summary><div>-<p>Android 8.0 (API 26) and newer, on any phone with Bluetooth LE: Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them.</p>+<p>Android 8.0 (API 26) and newer, on any 64-bit ARM phone with Bluetooth LE (almost every phone since 2017; old 32-bit phones are not supported): Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them.</p></div></details>@@ -658,9 +658,9 @@</details><details class="faq" id="usb-wifi-adapter">-<summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H or AWUS036NHA with Android?</summary>+<summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?</summary><div>-<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p>+<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works experimentally on 2.4, 5 and 6 GHz, with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p></div></details>@@ -713,7 +713,7 @@<details class="faq" id="data-collected"><summary>What data does it collect?</summary><div>-<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to OpenStreetMap services (map tiles, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files) and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p>+<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p></div></details>diff --git a/docs/sitemap.xml b/docs/sitemap.xmlindex 9b850e7..08bc01b 100644--- a/docs/sitemap.xml+++ b/docs/sitemap.xml@@ -5,12 +5,12 @@<url><loc>https://cis-c0.github.io/RFSentinel/drone-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/esp32.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/flock-camera-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>- <url><loc>https://cis-c0.github.io/RFSentinel/how-it-works.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>+ <url><loc>https://cis-c0.github.io/RFSentinel/how-it-works.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/imsi-catcher-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-10</lastmod><priority>1.0</priority></url>- <url><loc>https://cis-c0.github.io/RFSentinel/install.html</loc><lastmod>2026-10-08</lastmod><priority>0.8</priority></url>+ <url><loc>https://cis-c0.github.io/RFSentinel/install.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/police-detector.html</loc><lastmod>2026-10-07</lastmod><priority>0.8</priority></url>- <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-08</lastmod><priority>0.9</priority></url>+ <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-10</lastmod><priority>0.9</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/smart-glasses-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/sophia-alternative.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/tracker-detector.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url>diff --git a/settings.gradle.kts b/settings.gradle.ktsindex d5a073a..5168724 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -10,6 +10,11 @@ dependencyResolutionManagement {repositories {google()mavenCentral()+ // Mapbox Maps SDK (the optional Mapbox map); only Mapbox's own artifacts come from here.+ maven {+ url = uri("https://api.mapbox.com/downloads/v2/releases/maven")+ content { includeGroupByRegex("com[.]mapbox.*") }+ }}}diff --git a/site/pages/how-it-works.html b/site/pages/how-it-works.htmlindex 6411599..28cf03e 100644--- a/site/pages/how-it-works.html+++ b/site/pages/how-it-works.html@@ -11,7 +11,7 @@<li><b>Screen off:</b> Android suspends unfiltered scans, so a second, hardware-filtered scan runs on the identifiers that matter (vendor company IDs, Remote ID, tracker and glasses service data and UUIDs, watchlisted exact addresses).</li><li><b>WiFi</b>: <code>WifiManager</code> scans every 30 s by default (Android allows about 4 per 2 minutes), including raw information elements on Android 11+.</li><li><b>Cell</b>: <code>getAllCellInfo()</code> every 15 s for <a href="imsi-catcher-detector.html">fake-tower signs</a>.</li>-<li><b>External</b>: OUI-Spy / GhostESP / Marauder <a href="esp32.html">ESP32 boards</a> over USB or Bluetooth (also through a Flipper Zero), FREE-WiLi 2, and USB WiFi adapters: RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U (2.4 + 5 GHz), RTL8187, RT3070 and, experimental, AR9271.</li>+<li><b>External</b>: OUI-Spy / GhostESP / Marauder <a href="esp32.html">ESP32 boards</a> over USB or Bluetooth (also through a Flipper Zero), FREE-WiLi 2, and USB WiFi adapters: RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U (2.4 + 5 GHz), RTL8187, RT3070 and, experimental, AR9271 and the WiFi 6E MT7921AU (2.4 + 5 + 6 GHz).</li></ul><p>Nothing is ever transmitted to, connected to or paired with a scanned device.</p>diff --git a/site/pages/index.html b/site/pages/index.htmlindex ae7889e..1ee3535 100644--- a/site/pages/index.html+++ b/site/pages/index.html@@ -4,7 +4,7 @@<p class="kicker">[email protected]:~$ ./rf_sentinel --passive</p><h1>RF_SENTINEL<span class="sr-only"> - police detector for Android</span></h1><p class="lead">A free, open-source <b>police detector for Android</b>. It listens to the Bluetooth LE advertisements and WiFi beacons around you and flags police and surveillance equipment: body cameras, Flock and other plate-reader cameras, patrol-vehicle gear, trackers following you, Remote ID drones and camera glasses. It also watches the cell network for fake-tower (IMSI catcher) signs.</p>- <p><span class="stamp">RX ONLY</span><span class="small">No root · no Termux · no account · no analytics · GPL-3.0 · Android 8.0+</span></p>+ <p><span class="stamp">RX ONLY</span><span class="small">No root · no Termux · no account · no analytics · GPL-3.0 · Android 8.0+ (64-bit)</span></p><div class="cta"><a class="btn primary" href="{{RELEASES}}" data-apk>{{DOWNLOAD_SVG}}Download APK <span data-version></span></a><a class="btn" href="{{REPO}}" rel="noopener">{{GITHUB_SVG}}Source on GitHub</a>@@ -56,13 +56,13 @@<div class="grid"><div class="card"><h3>Live list, radar & map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div><div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>- <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>+ <div class="card"><h3>Map & traces</h3><p>A vector map (OpenFreeMap, OpenStreetMap data, or Mapbox if you prefer) with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view like a navigation app that zooms with your speed, with the default zoom and angle in Settings; a light map and a readable night map with shops, landmarks and one-way arrows. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div><div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div><div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div><div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>- <div class="card"><h3>USB WiFi adapters</h3><p>ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH and AWUS036NHA (experimental), TP-Link Archer T3U and other RTL8812BU dongles - 2.4 GHz, and 5 GHz on the AC adapters - in receive-only monitor mode over OTG, no root: no scan limit, longer range, devices connected to networks, and the network names devices ask for. <a href="qa.html#usb-wifi-adapter">Details</a></p></div>+ <div class="card"><h3>USB WiFi adapters</h3><p>ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH, AWUS036NHA and AWUS036AXML (experimental), TP-Link Archer T3U and other RTL8812BU dongles - 2.4 GHz, 5 GHz on the AC adapters and 6 GHz on the WiFi 6E AWUS036AXML - in receive-only monitor mode over OTG, no root: no scan limit, longer range, devices connected to networks, and the network names devices ask for. <a href="qa.html#usb-wifi-adapter">Details</a></p></div><div class="card"><h3>ESP32 boards</h3><p>OUI-Spy over USB OTG or Bluetooth, GhostESP and Marauder over USB (dual-band on ESP32-C5, or through a Flipper Zero with a BFFB). The board's detections merge into the app. <a href="esp32.html">Details</a></p></div>- <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement.</p></div>+ <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement. Search every device the app remembers, in range or not, by address, name, vendor, type or your note.</p></div><div class="card"><h3>Export</h3><p>CSV, JSON, KML, GPX, GeoJSON. Everything stays on the phone until you export or share it.</p></div><div class="card"><h3>13 themes</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT.</p></div></div>@@ -115,6 +115,6 @@<ul><li><b>Receive-only.</b> The app never transmits, jams, spoofs or connects to the devices it detects.</li><li><b>No accounts, no cloud, no analytics.</b> Detections live in a local database excluded from cloud backup.</li>- <li><b>Network use:</b> OpenStreetMap map tiles and camera data (Overpass API, DeFlock CDN), and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li>+ <li><b>Network use:</b> the map (vector tiles from OpenFreeMap, OpenStreetMap data, or from Mapbox if you pick it in Settings with Mapbox's own usage statistics switched off), camera data (Overpass API, DeFlock CDN), the roads of your area while the Waze option to alert only for reports on your road is on, and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li><li><b>Data leaves the phone only when you export or share it.</b></li></ul>diff --git a/site/pages/install.html b/site/pages/install.htmlindex b2884a1..62a021f 100644--- a/site/pages/install.html+++ b/site/pages/install.html@@ -2,7 +2,7 @@<div class="page-head"><p class="crumbs"><a href="./">rf_sentinel</a> / install</p><h1>Install</h1>- <p class="lead">Android 8.0 or newer. One signed APK from GitHub Releases, about 11 MB.</p>+ <p class="lead">Android 8.0 or newer on a 64-bit ARM phone (almost every phone since 2017). One signed APK from GitHub Releases, about 30 MB.</p><div class="cta"><a class="btn primary" href="{{RELEASES}}" data-apk>{{DOWNLOAD_SVG}}Download APK <span data-version></span></a><a class="btn" href="{{RELEASES}}">All releases & changelog</a>diff --git a/site/pages/qa.html b/site/pages/qa.htmlindex 936f717..41d1433 100644--- a/site/pages/qa.html+++ b/site/pages/qa.html@@ -430,7 +430,7 @@<details class="faq" id="android-version"><summary>Which Android versions and phones are supported?</summary><div>-<p>Android 8.0 (API 26) and newer, on any phone with Bluetooth LE: Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them.</p>+<p>Android 8.0 (API 26) and newer, on any 64-bit ARM phone with Bluetooth LE (almost every phone since 2017; old 32-bit phones are not supported): Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them.</p></div></details>@@ -618,9 +618,9 @@</details><details class="faq" id="usb-wifi-adapter">-<summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H or AWUS036NHA with Android?</summary>+<summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?</summary><div>-<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p>+<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works experimentally on 2.4, 5 and 6 GHz, with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p></div></details>@@ -673,7 +673,7 @@<details class="faq" id="data-collected"><summary>What data does it collect?</summary><div>-<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to OpenStreetMap services (map tiles, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files) and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p>+<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p></div></details>