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
Rename starred places; your own device names and notes
CIS-C07a76ca783f8b
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex f722b36..f38d5db 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -237,7 +237,7 @@ class MainActivity : AppCompatActivity() {applyViewMode()observeDevices()updateStatus()- lifecycleScope.launch { Favorites.load(this@MainActivity) }+ lifecycleScope.launch { Favorites.load(this@MainActivity); com.rfsentinel.app.data.DeviceNames.load(this@MainActivity) }// Only on a real fresh start - a theme change recreates this screen too.if (savedInstanceState == null && !Prefs.onboardingDone(this)) showOnboarding()@@ -868,12 +868,15 @@ class MainActivity : AppCompatActivity() {"${best.category.shortTag} · ${best.tier.label} ${best.confidence}%"else -> radioTag(s)}+ val alias = com.rfsentinel.app.data.DeviceNames.of(s.mac)return DeviceRow(mac = s.mac,- title = best?.label ?: s.name ?: s.deviceType,+ title = alias ?: best?.label ?: s.name ?: s.deviceType,subtitle = s.mac + " · " + (s.vendor ?: s.addressType.label),meta = listOf(- if (best != null && s.name != null) "\"${s.name}\"" else s.deviceType,+ // Under your own name, what it's heard as comes first.+ if (alias != null) best?.label ?: s.name?.let { "\"$it\"" } ?: s.deviceType+ else if (best != null && s.name != null) "\"${s.name}\"" else s.deviceType,// Ordinary rows name the radio in their tag; flagged ones keep it here.if (tag == radioTag(s)) null else s.sources.joinToString("+") { if (it == Advert.Source.BLE) "BLE" else "WiFi" },"${ProximityUtil.band(s.rssi)} ${s.rssi} dBm ${DeviceIntel.formatDistance(s.distanceM)}",diff --git a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.ktindex da3fcc1..49ac17d 100644--- a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt+++ b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt@@ -12,7 +12,7 @@ import androidx.sqlite.db.SupportSQLiteDatabaseDetectionEntity::class, WhitelistEntity::class, KnownDeviceEntity::class,TripEntity::class, TripPointEntity::class, TripDeviceEntity::class],- version = 4,+ version = 5,exportSchema = false)abstract class AppDatabase : RoomDatabase() {@@ -78,13 +78,20 @@ abstract class AppDatabase : RoomDatabase() {}}+ /** v2.25: your own names for devices. */+ val MIGRATION_4_5 = object : Migration(4, 5) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL("ALTER TABLE known_devices ADD COLUMN alias TEXT")+ }+ }+fun getInstance(context: Context): AppDatabase {return INSTANCE ?: synchronized(this) {INSTANCE ?: Room.databaseBuilder(context.applicationContext,AppDatabase::class.java,"rfsentinel.db"- ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4).build().also { INSTANCE = it }+ ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5).build().also { INSTANCE = it }}}}diff --git a/app/src/main/java/com/rfsentinel/app/data/DeviceNames.kt b/app/src/main/java/com/rfsentinel/app/data/DeviceNames.ktnew file mode 100644index 0000000..c05160d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/data/DeviceNames.kt@@ -0,0 +1,37 @@+package com.rfsentinel.app.data++import android.content.Context++/** Your own names for devices (known_devices.alias), kept in memory so the list and map needn't read the database per device. */+object DeviceNames {+ @Volatile private var names: Map<String, String> = emptyMap()++ /** Your name for [mac], or null. */+ fun of(mac: String): String? = names[mac]++ suspend fun load(context: Context) {+ names = AppDatabase.getInstance(context).knownDeviceDao().aliases().associate { it.mac to it.alias }+ }++ /** Names (or, with a blank [alias], un-names) a device, creating its history row if it hasn't been flushed yet. */+ suspend fun set(context: Context, mac: String, alias: String?, name: String?, vendor: String?, type: String?) {+ val clean = alias?.trim()?.take(64)?.ifEmpty { null }+ ensureRow(context, mac, name, vendor, type)+ AppDatabase.getInstance(context).knownDeviceDao().setAlias(mac, clean)+ names = if (clean != null) names + (mac to clean) else names - mac+ }++ /** Saves your note on a device ([note] blank clears it). */+ suspend fun setNote(context: Context, mac: String, note: String?, name: String?, vendor: String?, type: String?) {+ ensureRow(context, mac, name, vendor, type)+ AppDatabase.getInstance(context).knownDeviceDao().setNote(mac, note?.trim()?.take(1000)?.ifEmpty { null })+ }++ private suspend fun ensureRow(context: Context, mac: String, name: String?, vendor: String?, type: String?) {+ val dao = AppDatabase.getInstance(context).knownDeviceDao()+ if (dao.get(mac) == null) {+ val now = System.currentTimeMillis()+ dao.upsertAll(listOf(KnownDeviceEntity(mac, now, now, 1, 1, name, vendor, type)))+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.ktindex 8208fd9..6ec1016 100644--- a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt+++ b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt@@ -26,9 +26,15 @@ data class KnownDeviceEntity(val vendor: String? = null,val deviceType: String? = null,@ColumnInfo(defaultValue = "0") val favorite: Boolean = false,- val note: String? = null+ /** Your own note about it, from its device page. */+ val note: String? = null,+ /** Your own name for it, from its device page: shown in place of the name it broadcasts. */+ val alias: String? = null)+/** A device's own name ([KnownDeviceDao.aliases]). */+data class MacAlias(val mac: String, val alias: String)+@Daointerface KnownDeviceDao {@Query("SELECT * FROM known_devices WHERE mac = :mac")@@ -53,18 +59,27 @@ interface KnownDeviceDao {@Query("SELECT mac FROM known_devices WHERE favorite = 1")suspend fun favorites(): List<String>+ @Query("UPDATE known_devices SET alias = :alias WHERE mac = :mac")+ suspend fun setAlias(mac: String, alias: String?)++ @Query("UPDATE known_devices SET note = :note WHERE mac = :mac")+ suspend fun setNote(mac: String, note: String?)++ @Query("SELECT mac, alias FROM known_devices WHERE alias IS NOT NULL AND alias != ''")+ suspend fun aliases(): List<MacAlias>+@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+ * MAC (with or without colons), name, vendor, type, note or your own name; only favorites, only devices that were* flagged (in the match log), only those seen since [since].*/@Query("""SELECT * FROM known_devicesWHERE (: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 '\')+ OR deviceType LIKE :like ESCAPE '\' OR note LIKE :like ESCAPE '\' OR alias LIKE :like ESCAPE '\')AND (:favorites = 0 OR favorite = 1)AND (:flagged = 0 OR mac IN (SELECT mac FROM detections))AND lastSeen >= :since@@ -78,8 +93,9 @@ interface KnownDeviceDao {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")+ /** Forget non-favorite devices not heard since [before]; ones you named or wrote a note on are kept. */+ @Query("""DELETE FROM known_devices WHERE lastSeen < :before AND favorite = 0+ AND (alias IS NULL OR alias = '') AND (note IS NULL OR note = '')""")suspend fun prune(before: Long): Int@Query("DELETE FROM known_devices WHERE favorite = 0")diff --git a/app/src/main/java/com/rfsentinel/app/nav/NavSearchActivity.kt b/app/src/main/java/com/rfsentinel/app/nav/NavSearchActivity.ktindex 5ee2937..38e43b2 100644--- a/app/src/main/java/com/rfsentinel/app/nav/NavSearchActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/nav/NavSearchActivity.kt@@ -136,7 +136,7 @@ class NavSearchActivity : AppCompatActivity() {onMore = { startActivityForResult(intent(this, MODE_WORK), REQ_WORK) }))categories("Nearby") { categorySearch(it, along = false) }if (Navigator.active && Navigator.state != null) categories("Along your route") { categorySearch(it, along = true) }- section("Starred", Prefs.navFavorites(this), R.drawable.ic_nav_star)+ section("Starred", Prefs.navFavorites(this), R.drawable.ic_nav_star, rename = true)section("Recent", Prefs.recentDestinations(this), R.drawable.ic_nav_history)}if (list.childCount == 0) setNote("Type at least ${Places.MIN_QUERY} letters to search.")@@ -147,10 +147,10 @@ class NavSearchActivity : AppCompatActivity() {setPadding(px(16), px(14), px(16), px(4)); alpha = 0.7f})- private fun section(title: String, places: List<Place>, icon: Int) {+ private fun section(title: String, places: List<Place>, icon: Int, rename: Boolean = false) {if (places.isEmpty()) returnheader(title)- places.forEach { p -> list.addView(placeRow(p, icon)) }+ places.forEach { p -> list.addView(placeRow(p, icon).also { if (rename) addRename(it as LinearLayout, p) }) }}/** A row of kinds of place to look for (petrol, food, charging...). */@@ -256,6 +256,16 @@ class NavSearchActivity : AppCompatActivity() {return v}+ /** A pencil before a starred place's star, to give it your own name. */+ private fun addRename(row: LinearLayout, p: Place) {+ row.addView(ImageButton(this).apply {+ setImageResource(R.drawable.ic_nav_edit); setColorFilter(ChipStyle.onSurface(this@NavSearchActivity)); alpha = 0.6f+ background = null; contentDescription = "Rename"+ setOnClickListener { RenamePlace.ask(this@NavSearchActivity, p) { showStart() } }+ }, row.childCount - 1, LinearLayout.LayoutParams(px(44), px(44)))+ row.setOnLongClickListener { RenamePlace.ask(this, p) { showStart() }; true }+ }+private fun starButton(p: Place) = ImageButton(this).apply {val (accent, _) = ChipStyle.accent(this@NavSearchActivity)fun style() {diff --git a/app/src/main/java/com/rfsentinel/app/nav/RenamePlace.kt b/app/src/main/java/com/rfsentinel/app/nav/RenamePlace.ktnew file mode 100644index 0000000..d57645d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/nav/RenamePlace.kt@@ -0,0 +1,31 @@+package com.rfsentinel.app.nav++import android.content.Context+import android.widget.EditText+import android.widget.FrameLayout+import androidx.appcompat.app.AlertDialog+import com.rfsentinel.app.util.Prefs++/** Asks for a new name for a starred place; [done] gets the renamed place. */+object RenamePlace {+ fun ask(context: Context, p: Place, done: (Place) -> Unit) {+ val dp = context.resources.displayMetrics.density+ val input = EditText(context).apply {+ setText(p.name); setSelectAllOnFocus(true); isSingleLine = true+ hint = "Name"+ }+ val box = FrameLayout(context).apply {+ val side = (20 * dp).toInt(); setPadding(side, (8 * dp).toInt(), side, 0); addView(input)+ }+ AlertDialog.Builder(context)+ .setTitle("Rename starred place")+ .setView(box)+ .setPositiveButton("Save") { _, _ ->+ Prefs.renameNavFavorite(context, p, input.text.toString())?.let(done)+ }+ .setNegativeButton("Cancel", null)+ .show()+ .window?.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)+ input.requestFocus()+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex f6bf5cd..416d92a 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -877,7 +877,8 @@ class ScanForegroundService : Service() {vendor = s.vendor ?: e?.vendor,deviceType = s.deviceType,favorite = e?.favorite ?: false,- note = e?.note+ note = e?.note,+ alias = e?.alias)})}diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.ktindex 2cea0fc..df98270 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt@@ -19,6 +19,7 @@ import com.google.android.material.button.MaterialButtonimport com.rfsentinel.app.util.AlertPlayerimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.DetectionEntity+import com.rfsentinel.app.data.DeviceNamesimport com.rfsentinel.app.data.Favoritesimport com.rfsentinel.app.data.KnownDeviceEntityimport com.rfsentinel.app.data.WhitelistCache@@ -95,6 +96,9 @@ class DeviceDetailActivity : AppCompatActivity() {refresh()}}+ binding.actionRename.setOnClickListener { rename() }+ binding.actionNote.setOnClickListener { editNote() }+ binding.noteText.setOnClickListener { editNote() }binding.actionCopy.setOnClickListener { DeviceActions.copy(this, mac) }binding.actionShare.setOnClickListener { share() }@@ -162,8 +166,15 @@ class DeviceDetailActivity : AppCompatActivity() {} else {binding.tagText.visibility = View.GONE}- binding.titleText.text = best?.label ?: s?.name ?: known?.name ?: s?.deviceType ?: known?.deviceType ?: "Device"- binding.subtitleText.text = mac + ((s?.vendor ?: known?.vendor ?: VendorDb.macVendor(mac))?.let { "\n$it" } ?: "")+ val heardAs = best?.label ?: s?.name ?: known?.name ?: s?.deviceType ?: known?.deviceType ?: "Device"+ val alias = DeviceNames.of(mac)+ // Your own name in place of what it's heard as; that stays on the line below.+ binding.titleText.text = alias ?: heardAs+ binding.subtitleText.text = (if (alias != null) "$heardAs\n" else "") ++ mac + ((s?.vendor ?: known?.vendor ?: VendorDb.macVendor(mac))?.let { "\n$it" } ?: "")+ val note = known?.note?.takeIf { it.isNotBlank() }+ binding.noteText.visibility = if (note != null) View.VISIBLE else View.GONE+ binding.noteText.text = note?.let { "\uD83D\uDCDD $it" }binding.presenceText.text = when {liveMac != mac && live != null -> "In range under its new address $liveMac (it changed its address) · heard ${ago(now - live.lastSeen)}"s == null -> "Not in range right now" + (known?.let { " · last heard ${dateFmt.format(Date(it.lastSeen))}" } ?: "")@@ -223,6 +234,7 @@ class DeviceDetailActivity : AppCompatActivity() {else -> "Whitelist"}binding.actionFavorite.text = if (Favorites.contains(mac)) "★ Favorite" else "☆ Favorite"+ binding.actionNote.text = if (known?.note.isNullOrBlank()) "Add note" else "Edit note"// Sections: rebuilt only when their content changes (keeps scroll & selection stable).val content = buildSections(s)@@ -483,6 +495,56 @@ class DeviceDetailActivity : AppCompatActivity() {}}+ /** Your own name for the device, shown in place of the name it broadcasts. */+ private fun rename() {+ val s = DeviceRegistry.get(mac)+ val heardAs = s?.best?.label ?: s?.name ?: known?.name ?: s?.deviceType ?: known?.deviceType+ ask("Name this device", DeviceNames.of(mac).orEmpty(), heardAs ?: "Name", multiLine = false,+ clear = DeviceNames.of(mac)?.let { "Use its own name" }) { text ->+ lifecycleScope.launch {+ DeviceNames.set(this@DeviceDetailActivity, mac, text, s?.name ?: known?.name, s?.vendor ?: known?.vendor, s?.deviceType)+ known = AppDatabase.getInstance(this@DeviceDetailActivity).knownDeviceDao().get(mac)+ refresh()+ }+ }+ }++ /** Your own note on the device: kept with its history, searchable there. */+ private fun editNote() {+ val s = DeviceRegistry.get(mac)+ val old = known?.note.orEmpty()+ ask(if (old.isBlank()) "Add a note" else "Edit note", old, "Where you saw it, what it is…", multiLine = true,+ clear = old.takeIf { it.isNotBlank() }?.let { "Delete note" }) { text ->+ lifecycleScope.launch {+ DeviceNames.setNote(this@DeviceDetailActivity, mac, text, s?.name ?: known?.name, s?.vendor ?: known?.vendor, s?.deviceType)+ known = AppDatabase.getInstance(this@DeviceDetailActivity).knownDeviceDao().get(mac)+ refresh()+ }+ }+ }++ /** A text box with Save, Cancel and (when there is something to clear) [clear]; [done] gets the text, blank when cleared. */+ private fun ask(title: String, value: String, hint: String, multiLine: Boolean, clear: String?, done: (String) -> Unit) {+ val dp = resources.displayMetrics.density+ val input = android.widget.EditText(this).apply {+ setText(value); this.hint = hint+ if (multiLine) { isSingleLine = false; minLines = 2; maxLines = 6 } else { isSingleLine = true; setSelectAllOnFocus(true) }+ setSelection(text.length)+ }+ val box = android.widget.FrameLayout(this).apply {+ val side = (20 * dp).toInt(); setPadding(side, (8 * dp).toInt(), side, 0); addView(input)+ }+ androidx.appcompat.app.AlertDialog.Builder(this)+ .setTitle(title)+ .setView(box)+ .setPositiveButton("Save") { _, _ -> done(input.text.toString()) }+ .setNegativeButton("Cancel", null)+ .apply { if (clear != null) setNeutralButton(clear) { _, _ -> done("") } }+ .show()+ .window?.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)+ input.requestFocus()+ }+private fun ago(ms: Long) = if (ms < 2000) "just now" else "${ms / 1000}s ago"// ---- Actions --------------------------------------------------------------diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.ktindex 1eeadd0..df9ef5b 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt@@ -149,6 +149,7 @@ class DeviceHistoryActivity : AppCompatActivity() {return@launch}com.rfsentinel.app.data.Favorites.load(this@DeviceHistoryActivity)+ com.rfsentinel.app.data.DeviceNames.load(this@DeviceHistoryActivity)search(now = true)val keep = Prefs.retentionDays(this@DeviceHistoryActivity)androidx.appcompat.app.AlertDialog.Builder(this@DeviceHistoryActivity).setTitle("History imported")@@ -196,9 +197,10 @@ class DeviceHistoryActivity : AppCompatActivity() {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) ++ h.title.text = (if (k.favorite) "★ " else "") + (k.alias?.takeIf { it.isNotBlank() } ?: 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 },+ h.line.text = listOfNotNull(k.name?.takeIf { it.isNotBlank() && !k.alias.isNullOrBlank() }?.let { "\"$it\"" },+ k.vendor?.takeIf { it.isNotBlank() }, k.mac.takeIf { k.name?.isNotBlank() == true || !k.alias.isNullOrBlank() },k.note?.takeIf { it.isNotBlank() }?.let { "Note: $it" }).joinToString(" · ").ifEmpty { "Unknown vendor" }h.line.visibility = View.VISIBLEval last = DateUtils.getRelativeTimeSpanString(k.lastSeen, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS)diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt b/app/src/main/java/com/rfsentinel/app/ui/MapNav.ktindex 670c5ca..94b6d42 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt@@ -116,7 +116,7 @@ internal class MapNav(fun setup() {val ink = ColorStateList.valueOf(ChipStyle.onSurface(act))- for (v in listOf(b.navCardStar, b.navCardClose, b.navEnd, b.navOverview, b.navMenu)) v.imageTintList = ink+ for (v in listOf(b.navCardStar, b.navCardRename, b.navCardClose, b.navEnd, b.navOverview, b.navMenu)) v.imageTintList = inkb.navMute.imageTintList = ColorStateList.valueOf(0xFFFFFFFF.toInt())b.searchButton.backgroundTintList = ColorStateList.valueOf(ChipStyle.accent(act).first)b.searchButton.imageTintList = ColorStateList.valueOf(ChipStyle.accent(act).second)@@ -124,6 +124,8 @@ internal class MapNav(b.navCardClose.setOnClickListener { closeCard() }b.navCardStar.setOnClickListener { place?.let { Prefs.toggleNavFavorite(act, it); styleStar() } }+ b.navCardRename.setOnClickListener { renamePlace() }+ b.navCardTitle.setOnClickListener { if (place?.let { Prefs.isNavFavorite(act, it) } == true) renamePlace() }b.navStart.setOnClickListener { onStartButton() }b.navOpenIn.setOnClickListener { openInMenu(it) }ChipStyle.accent(act).first.let { accent ->@@ -151,7 +153,7 @@ internal class MapNav(*/private fun compactCard() {b.navCard.setPadding(px(10), px(6), px(10), px(6))- for (v in listOf(b.navCardStar, b.navCardClose)) v.layoutParams = LinearLayout.LayoutParams(px(40), px(40))+ for (v in listOf(b.navCardStar, b.navCardRename, b.navCardClose)) v.layoutParams = LinearLayout.LayoutParams(px(40), px(40))for (v in listOf(b.navStart, b.navOpenIn)) { v.insetTop = 0; v.insetBottom = 0; v.minimumHeight = px(40) }(b.navStart.parent as? LinearLayout)?.let { row -> (row.layoutParams as? LinearLayout.LayoutParams)?.topMargin = px(4) }}@@ -231,6 +233,13 @@ internal class MapNav(b.navCardStar.setImageResource(if (on) R.drawable.ic_nav_star else R.drawable.ic_nav_star_border)b.navCardStar.imageTintList = ColorStateList.valueOf(if (on) ChipStyle.accent(act).first else ChipStyle.onSurface(act))b.navCardStar.contentDescription = if (on) "Starred - tap to remove" else "Star this place"+ b.navCardRename.visibility = if (on) View.VISIBLE else View.GONE+ }++ /** Your own name for the starred place on the card. */+ private fun renamePlace() {+ val p = place ?: return+ com.rfsentinel.app.nav.RenamePlace.ask(act, p) { renamed -> if (place == p) { place = renamed; bindCard() } }}private fun onStartButton() {diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt b/app/src/main/java/com/rfsentinel/app/ui/MapShared.ktindex 2d90820..c4c42e2 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt@@ -34,7 +34,7 @@ internal object MapPins {val best = s.bestMapPin(s.mac, pos.lat, pos.lon,- best?.label ?: s.name ?: s.deviceType,+ com.rfsentinel.app.data.DeviceNames.of(s.mac) ?: best?.label ?: s.name ?: s.deviceType,flagged,DeviceColors.forDevice(context, s),buildString {diff --git a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.ktindex 4236ddc..004cae5 100644--- a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt+++ b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt@@ -183,12 +183,12 @@ object DeviceExport {// ---- Long-term history ----------------------------------------------------------fun historyCsv(rows: List<KnownDeviceEntity>): String {- val sb = StringBuilder("mac,name,vendor,device_type,first_seen,last_seen,sessions,detect_count,favorite,note\n")+ val sb = StringBuilder("mac,name,vendor,device_type,first_seen,last_seen,sessions,detect_count,favorite,note,custom_name\n")rows.forEach { r ->sb.append(r.mac).append(',').append(q(r.name)).append(',').append(q(r.vendor)).append(',').append(q(r.deviceType)).append(',').append(local(r.firstSeen)).append(',').append(local(r.lastSeen)).append(',').append(r.sessions).append(',').append(r.detectCount).append(',').append(r.favorite).append(',')- .append(q(r.note)).append('\n')+ .append(q(r.note)).append(',').append(q(r.alias)).append('\n')}return sb.toString()}@@ -200,6 +200,7 @@ object DeviceExport {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)+ addProperty("customName", r.alias)}fun matchesJson(rows: List<DetectionEntity>): JsonArray = gson.toJsonTree(rows).asJsonArraydiff --git a/app/src/main/java/com/rfsentinel/app/util/DeviceHistoryImport.kt b/app/src/main/java/com/rfsentinel/app/util/DeviceHistoryImport.ktindex f103e90..7c3d973 100644--- a/app/src/main/java/com/rfsentinel/app/util/DeviceHistoryImport.kt+++ b/app/src/main/java/com/rfsentinel/app/util/DeviceHistoryImport.kt@@ -52,7 +52,8 @@ object DeviceHistoryImport {/** A history row from a file's fields; null when the address is not a Bluetooth / WiFi address. */fun row(mac: String?, name: String?, vendor: String?, type: String?, first: String?, last: String?,- sessions: String?, detects: String?, favorite: String?, note: String?, now: Long = System.currentTimeMillis()): KnownDeviceEntity? {+ sessions: String?, detects: String?, favorite: String?, note: String?, alias: String? = null,+ now: Long = System.currentTimeMillis()): KnownDeviceEntity? {val m = mac?.trim().orEmpty()if (!MAC.matches(m)) return nullval f = parseTime(first); val l = parseTime(last)@@ -64,7 +65,8 @@ object DeviceHistoryImport {sessions = (sessions?.trim()?.toIntOrNull() ?: 1).coerceIn(1, 1_000_000),detectCount = (detects?.trim()?.toIntOrNull() ?: 1).coerceIn(1, 100_000_000),name = clean(name, 128), vendor = clean(vendor, 128), deviceType = clean(type, 64),- favorite = favorite?.trim()?.equals("true", true) == true, note = clean(note, 1000)+ favorite = favorite?.trim()?.equals("true", true) == true, note = clean(note, 1000),+ alias = clean(alias, 64))}@@ -79,7 +81,8 @@ object DeviceHistoryImport {detectCount = maxOf(mine.detectCount, theirs.detectCount),name = mine.name ?: theirs.name, vendor = mine.vendor ?: theirs.vendor, deviceType = mine.deviceType ?: theirs.deviceType,favorite = mine.favorite || theirs.favorite,- note = mine.note?.takeIf { it.isNotBlank() } ?: theirs.note+ note = mine.note?.takeIf { it.isNotBlank() } ?: theirs.note,+ alias = mine.alias?.takeIf { it.isNotBlank() } ?: theirs.alias)}@@ -138,7 +141,7 @@ object DeviceHistoryImport {}}r.endObject()- yield(row(f["mac"], f["name"], f["vendor"], f["deviceType"], f["firstSeen"], f["lastSeen"], f["sessions"], f["detectCount"], f["favorite"], f["note"]))+ yield(row(f["mac"], f["name"], f["vendor"], f["deviceType"], f["firstSeen"], f["lastSeen"], f["sessions"], f["detectCount"], f["favorite"], f["note"], f["customName"]))}r.endArray()}@@ -153,7 +156,8 @@ object DeviceHistoryImport {val r = it.next()if (r.all { f -> f.isBlank() }) continueyield(row(col(r, "mac"), col(r, "name"), col(r, "vendor"), col(r, "device_type", "devicetype"), col(r, "first_seen", "firstseen"),- col(r, "last_seen", "lastseen"), col(r, "sessions"), col(r, "detect_count", "detectcount"), col(r, "favorite"), col(r, "note")))+ col(r, "last_seen", "lastseen"), col(r, "sessions"), col(r, "detect_count", "detectcount"), col(r, "favorite"), col(r, "note"),+ col(r, "custom_name", "customname")))}}diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 972e10c..93f51a8 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -330,6 +330,14 @@ object Prefs {savePlaces(context, "nav_favorites", if (now) (listOf(p) + list).take(40) else list.filterNot { sameSpot(it, p) })return now}+ /** Gives a starred place your own name; the new place, or null when it isn't starred. */+ fun renameNavFavorite(context: Context, p: com.rfsentinel.app.nav.Place, name: String): com.rfsentinel.app.nav.Place? {+ val list = navFavorites(context)+ val i = list.indexOfFirst { sameSpot(it, p) }.takeIf { it >= 0 } ?: return null+ val renamed = list[i].copy(name = name.trim().ifEmpty { list[i].name })+ savePlaces(context, "nav_favorites", list.toMutableList().also { it[i] = renamed })+ return renamed+ }fun clearNavPlaces(context: Context) = placesSp(context).edit { remove("nav_home"); remove("nav_work"); remove("nav_favorites") }/** Spoken driving directions (default on). Separate from the alert voice and its mute / snooze. */diff --git a/app/src/main/res/drawable/ic_nav_edit.xml b/app/src/main/res/drawable/ic_nav_edit.xmlnew file mode 100644index 0000000..7ac2e12--- /dev/null+++ b/app/src/main/res/drawable/ic_nav_edit.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Design icon (Apache-2.0), for renaming. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" />+</vector>diff --git a/app/src/main/res/layout/activity_device_detail.xml b/app/src/main/res/layout/activity_device_detail.xmlindex 5e1706e..d8c487e 100644--- a/app/src/main/res/layout/activity_device_detail.xml+++ b/app/src/main/res/layout/activity_device_detail.xml@@ -48,6 +48,18 @@android:textColor="#888888"android:textSize="12sp" />+ <!-- Your own note on the device: tap to edit -->+ <TextView+ android:id="@+id/noteText"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="6dp"+ android:background="?attr/selectableItemBackground"+ android:paddingTop="4dp"+ android:paddingBottom="4dp"+ android:textSize="14sp"+ android:visibility="gone" />+<!-- Visual style: hot / cold signal dial and the match's confidence ring --><LinearLayoutandroid:id="@+id/visualTop"@@ -135,6 +147,18 @@android:layout_height="wrap_content"android:text="Favorite" />+ <com.google.android.material.chip.Chip+ android:id="@+id/actionRename"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Rename" />++ <com.google.android.material.chip.Chip+ android:id="@+id/actionNote"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Add note" />+<com.google.android.material.chip.Chipandroid:id="@+id/actionCopy"android:layout_width="wrap_content"diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xmlindex 3d90d29..d1d119c 100644--- a/app/src/main/res/layout/activity_map.xml+++ b/app/src/main/res/layout/activity_map.xml@@ -404,6 +404,15 @@android:textSize="13sp" /></LinearLayout>+ <ImageButton+ android:id="@+id/navCardRename"+ android:layout_width="44dp"+ android:layout_height="44dp"+ android:background="?attr/selectableItemBackgroundBorderless"+ android:contentDescription="Rename"+ android:src="@drawable/ic_nav_edit"+ android:visibility="gone" />+<ImageButtonandroid:id="@+id/navCardStar"android:layout_width="44dp"diff --git a/app/src/test/java/com/rfsentinel/app/util/DeviceCustomNameTest.kt b/app/src/test/java/com/rfsentinel/app/util/DeviceCustomNameTest.ktnew file mode 100644index 0000000..a82d046--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/util/DeviceCustomNameTest.kt@@ -0,0 +1,66 @@+package com.rfsentinel.app.util++import androidx.room.Room+import androidx.test.core.app.ApplicationProvider+import com.rfsentinel.app.data.AppDatabase+import com.rfsentinel.app.data.KnownDeviceDao+import com.rfsentinel.app.data.KnownDeviceEntity+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Your own device names and notes: saved, searchable, kept through pruning, exported and imported back. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = android.app.Application::class)+class DeviceCustomNameTest {++ private lateinit var db: AppDatabase+ private val dao get() = db.knownDeviceDao()++ @Before fun open() { db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java).allowMainThreadQueries().build() }+ @After fun close() { db.close() }++ private fun row(mac: String, last: Long) = KnownDeviceEntity(mac, last, last, 1, 1, "Heard", null, null)++ @Test+ fun namesAndNotesAreSavedAndSearchable() = runBlocking {+ dao.upsertAll(listOf(row("AA:00:00:00:00:01", 1000), row("AA:00:00:00:00:02", 1000)))+ dao.setAlias("AA:00:00:00:00:01", "Neighbour's car")+ dao.setNote("AA:00:00:00:00:02", "Seen at the market")+ assertEquals(listOf("AA:00:00:00:00:01" to "Neighbour's car"), dao.aliases().map { it.mac to it.alias })+ fun find(q: String) = runBlocking { dao.search(q, KnownDeviceDao.like(q), KnownDeviceDao.likeHex(q), false, false, 0, 10).map { it.mac } }+ assertEquals(listOf("AA:00:00:00:00:01"), find("neighbour"))+ assertEquals(listOf("AA:00:00:00:00:02"), find("market"))+ dao.setAlias("AA:00:00:00:00:01", null)+ assertEquals(0, dao.aliases().size)+ }++ @Test+ fun pruningKeepsDevicesYouNamedOrWroteOn() = runBlocking {+ dao.upsertAll(listOf(row("AA:00:00:00:00:01", 1000), row("AA:00:00:00:00:02", 1000), row("AA:00:00:00:00:03", 1000)))+ dao.setAlias("AA:00:00:00:00:01", "Mine")+ dao.setNote("AA:00:00:00:00:02", "A note")+ assertEquals(1, dao.prune(5000))+ assertNotNull(dao.get("AA:00:00:00:00:01")); assertNotNull(dao.get("AA:00:00:00:00:02"))+ assertNull(dao.get("AA:00:00:00:00:03"))+ }++ @Test+ fun theCustomNameGoesThroughExportAndImport() {+ val named = row("AA:00:00:00:00:01", 1000).copy(alias = "Doorbell", note = "front door")+ for (text in listOf(DeviceExport.historyCsv(listOf(named)), DeviceExport.historyJson(listOf(named)).toString())) {+ val back = DeviceHistoryImport.rows(text.byteInputStream()).filterNotNull().single()+ assertEquals("Doorbell", back.alias); assertEquals("front door", back.note)+ }+ val merged = DeviceHistoryImport.merge(row("AA:00:00:00:00:01", 2000), named)+ assertEquals("a missing name is filled in", "Doorbell", merged.alias)+ assertEquals("your own name stays", "Mine", DeviceHistoryImport.merge(named.copy(alias = "Mine"), named.copy(alias = "Other")).alias)+ }+}