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
Voice alerts redo: phone's speech engine (Google's when installed) with an English voice, priority queue (no stale or repeated phrases, pile-ups merged, follow warnings interrupt), audio ducked only while speaking, voice speed/picker/test in Settings
CIS-C05049602ed7f3
diff --git a/app/src/main/AlertPlayer.kt b/app/src/main/AlertPlayer.ktnew file mode 100644index 0000000..e69de29diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex d5866cd..4d04215 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -114,6 +114,55 @@ class SettingsActivity : AppCompatActivity() {}/** ESP32 boards on USB (OUI-Spy / GhostESP) and an OUI-SPY board over Bluetooth. */+ /** Speed, voice and a test button for spoken alerts; changes apply right away. */+ private fun setupVoiceControls() {+ val voice = com.rfsentinel.app.util.Voice+ val rates = mapOf(R.id.voiceRateSlow to 0.8f, R.id.voiceRateNormal to 1.0f, R.id.voiceRateFast to 1.25f)+ val current = Prefs.voiceRate(this)+ binding.voiceRateGroup.check(rates.minByOrNull { kotlin.math.abs(it.value - current) }!!.key)+ binding.voiceRateGroup.setOnCheckedChangeListener { _, id -> rates[id]?.let { Prefs.setVoiceRate(this, it) } }+ binding.voiceTestButton.setOnClickListener { com.rfsentinel.app.util.AlertPlayer.testVoice(this) }++ fun label(v: android.speech.tts.Voice, i: Int) =+ "${v.locale.getDisplayCountry(java.util.Locale.ENGLISH).ifEmpty { "English" }} · voice ${i + 1}" ++ (if (v.isNetworkConnectionRequired) " · online" else "") ++ (if (v.quality >= android.speech.tts.Voice.QUALITY_HIGH) " · high quality" else "")+ fun showVoice() {+ val list = voice.voices+ val chosen = Prefs.voiceName(this)?.let { n -> list.indexOfFirst { it.name == n } }?.takeIf { it >= 0 }+ binding.voiceText.text = when {+ list.isEmpty() -> "Uses the phone's speech engine (Google's when installed), in English."+ chosen != null -> "Voice: ${label(list[chosen], chosen)}"+ else -> "Voice: automatic (${label(list[0], 0)})"+ }+ }+ voice.warmUp(this) { runOnUiThread { if (!isDestroyed) showVoice() } }+ showVoice()+ binding.voicePickButton.setOnClickListener {+ val list = voice.voices+ if (list.isEmpty()) {+ Toast.makeText(this, "The speech engine is still starting - try again in a moment", Toast.LENGTH_SHORT).show()+ voice.warmUp(this); return@setOnClickListener+ }+ val names = listOf("Automatic (best English voice)") + list.mapIndexed { i, v -> label(v, i) }+ val sel = Prefs.voiceName(this)?.let { n -> list.indexOfFirst { it.name == n } + 1 } ?: 0+ androidx.appcompat.app.AlertDialog.Builder(this)+ .setTitle("Voice for spoken alerts")+ .setSingleChoiceItems(names.toTypedArray(), sel) { _, which ->+ // Each pick is spoken right away so you can compare.+ Prefs.setVoiceName(this, if (which == 0) null else list[which - 1].name)+ voice.voiceChanged(this)+ com.rfsentinel.app.util.AlertPlayer.testVoice(this)+ showVoice()+ }+ .setPositiveButton("Done", null)+ .setNeutralButton("Speech engine settings") { _, _ ->+ runCatching { startActivity(android.content.Intent("com.android.settings.TTS_SETTINGS")) }+ }+ .show()+ }+ }+private fun updateEspStatus() {val s = com.rfsentinel.app.esp.EspBoards.statusbinding.espStatusText.text = "ESP32 on USB (OUI-Spy or GhostESP): " +@@ -283,6 +332,7 @@ class SettingsActivity : AppCompatActivity() {binding.soundSwitch.isChecked = Prefs.soundEnabled(this)binding.vibrateSwitch.isChecked = Prefs.vibrateEnabled(this)binding.voiceSwitch.isChecked = Prefs.voiceEnabled(this)+ setupVoiceControls()binding.discreetSwitch.isChecked = Prefs.discreetMode(this)binding.bubbleSwitch.isChecked = Prefs.threatBubble(this) && Settings.canDrawOverlays(this)binding.bubbleSwitch.setOnCheckedChangeListener { sw, on ->diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.ktindex b7d935e..84e1ec4 100644--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt@@ -10,10 +10,8 @@ import android.os.Buildimport android.os.VibrationEffectimport android.os.Vibratorimport android.os.VibratorManager-import android.speech.tts.TextToSpeechimport com.rfsentinel.app.car.CarStateimport com.rfsentinel.app.detect.Tier-import java.util.Locale/*** Plays match alerts directly (synthesized beeps, a vibration pattern@@ -54,8 +52,6 @@ object AlertPlayer {.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build()- private var tts: TextToSpeech? = null- @Volatile private var ttsReady = falseprivate val main = Handler(Looper.getMainLooper())private var focusRequest: AudioFocusRequest? = null@@ -63,9 +59,8 @@ object AlertPlayer {val inCar = CarState.connectedval muted = Prefs.alertsMuted(context)val willSpeak = !muted && spoken != null && (Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))- if (!muted && (Prefs.soundEnabled(context) || willSpeak)) {- duckOthers(context, if (willSpeak) 6_000L else 2_500L)- }+ // Speech holds its own audio focus for exactly as long as it talks; this covers the beeps.+ if (!muted && Prefs.soundEnabled(context)) duckOthers(context, 2_500L)var beepMs = 0if (!muted && Prefs.soundEnabled(context) && (inCar || ringerAllowsSound(context))) {// Our own beeps (1 weak, 2 probable, 3 strong, long-short-long following) at@@ -85,17 +80,28 @@ object AlertPlayer {if (willSpeak) {val app = context.applicationContextval attrs = if (inCar) carSpeechAttributes else phoneSpeechAttributes+ val priority = when {+ following -> VoiceQueue.FOLLOWING+ tier == Tier.STRONG -> VoiceQueue.STRONG+ tier == Tier.MEDIUM -> VoiceQueue.PROBABLE+ else -> VoiceQueue.WEAK+ }// Speak after the beeps, not over them.- if (beepMs > 0) main.postDelayed({ speak(app, spoken!!, attrs) }, beepMs + 150L)- else speak(app, spoken!!, attrs)+ if (beepMs > 0) main.postDelayed({ Voice.say(app, spoken!!, priority, attrs) }, beepMs + 150L)+ else Voice.say(app, spoken!!, priority, attrs)}}/** A spoken navigation instruction (no beep, no vibration); silent when alerts are muted. */fun announce(context: Context, text: String) {if (Prefs.alertsMuted(context)) return- duckOthers(context, 5_000L)- speak(context.applicationContext, text, if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)+ Voice.say(context.applicationContext, text, VoiceQueue.STRONG, if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)+ }++ /** The Settings "Test voice" button: speaks right away with the chosen voice and speed. */+ fun testVoice(context: Context) {+ Voice.test(context.applicationContext, "RF Sentinel voice alerts. Axon body camera nearby.",+ if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)}/**@@ -141,50 +147,5 @@ object AlertPlayer {vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1))}- /** Announcements raised while the speech engine is still starting. */- private val pending = mutableListOf<Pair<String, AudioAttributes>>()-- @Synchronized- private fun speak(context: Context, text: String, attrs: AudioAttributes) {- val engine = tts- if (engine != null && ttsReady) {- engine.setAudioAttributes(attrs)- engine.speak(text, TextToSpeech.QUEUE_ADD, null, "rf-${System.nanoTime()}")- return- }- // Still starting: queue it (bounded) so it's spoken once ready.- if (pending.size < 5) pending += text to attrs- if (engine == null) {- tts = TextToSpeech(context) { status -> onTtsInit(status) }- }- }-- @Synchronized- private fun onTtsInit(status: Int) {- val engine = tts ?: return- if (status != TextToSpeech.SUCCESS) {- // Engine missing or still updating: drop it so the next alert tries again,- // instead of staying silent until the app restarts.- runCatching { engine.shutdown() }- tts = null- ttsReady = false- pending.clear()- return- }- ttsReady = true- engine.language = Locale.getDefault()- pending.forEach { (text, attrs) ->- engine.setAudioAttributes(attrs)- engine.speak(text, TextToSpeech.QUEUE_ADD, null, "rf-${System.nanoTime()}")- }- pending.clear()- }-- @Synchronized- fun shutdown() {- tts?.shutdown()- tts = null- ttsReady = false- pending.clear()- }+ fun shutdown() = Voice.shutdown()}diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 452661c..3796d19 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -57,6 +57,14 @@ object Prefs {/** Speak the alert ("Axon body camera nearby") via text-to-speech. */fun voiceEnabled(context: Context): Boolean = bool(context, "voice_enabled", false)fun setVoiceEnabled(context: Context, value: Boolean) = setBool(context, "voice_enabled", value)+ /** Speech rate for spoken alerts (1.0 = the engine's normal speed). */+ fun voiceRate(context: Context): Float = sp(context).getFloat("voice_rate", 1.0f)+ fun setVoiceRate(context: Context, rate: Float) = sp(context).edit { putFloat("voice_rate", rate) }+ /** The chosen speech-engine voice (null = best English voice on the phone). */+ fun voiceName(context: Context): String? = sp(context).getString("voice_name", null)+ fun setVoiceName(context: Context, name: String?) = sp(context).edit {+ if (name == null) remove("voice_name") else putString("voice_name", name)+ }/** Master mute for alert sound and voice (phone menu and Android Auto button). Vibration unaffected. */fun alertsMuted(context: Context): Boolean = bool(context, "alerts_muted", false)diff --git a/app/src/main/java/com/rfsentinel/app/util/Voice.kt b/app/src/main/java/com/rfsentinel/app/util/Voice.ktnew file mode 100644index 0000000..7169f6f--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/util/Voice.kt@@ -0,0 +1,187 @@+package com.rfsentinel.app.util++import android.content.Context+import android.media.AudioAttributes+import android.media.AudioFocusRequest+import android.media.AudioManager+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.speech.tts.TextToSpeech+import android.speech.tts.UtteranceProgressListener+import java.util.Locale++/**+ * Spoken alerts on the phone's own speech engine (Google's when installed - the+ * one Maps uses), with an English voice since every phrase is English: a French+ * or Spanish voice reading "Axon body camera nearby" is hard to understand.+ *+ * One phrase at a time from a [VoiceQueue] (most urgent first, no stale or+ * repeated announcements, pile-ups merged); other audio dips only while it+ * speaks. Speed and voice are chosen in Settings.+ */+object Voice {++ private const val GOOGLE_TTS = "com.google.android.tts"++ private val main = Handler(Looper.getMainLooper())+ private var tts: TextToSpeech? = null+ private var ready = false+ private var app: Context? = null+ private val queue = VoiceQueue()+ private var speaking: VoiceQueue.Item? = null+ private var speakingAttrs: AudioAttributes? = null+ private var focus: AudioFocusRequest? = null+ /** Attributes for queued items (the latest caller's: car or phone). */+ private var nextAttrs: AudioAttributes? = null++ /** English voices on this phone's engine, best first (filled once the engine is up). */+ @Volatile var voices: List<android.speech.tts.Voice> = emptyList()+ private set++ /** Queues [text] with a [VoiceQueue] priority; it's spoken as soon as nothing more urgent is. */+ fun say(context: Context, text: String, priority: Int, attrs: AudioAttributes) = main.post {+ app = context.applicationContext+ nextAttrs = attrs+ val now = System.currentTimeMillis()+ if (!queue.add(text, priority, now)) return@post+ val current = speaking+ if (current != null && queue.preempts(priority, current.priority)) {+ tts?.stop() // onDone/onStop isn't guaranteed after stop(): move on ourselves+ speaking = null+ }+ pump()+ }++ /** Says [text] right away, replacing anything queued (the Settings "Test voice" button). */+ fun test(context: Context, text: String, attrs: AudioAttributes) = main.post {+ app = context.applicationContext+ queue.clear()+ tts?.stop()+ speaking = null+ nextAttrs = attrs+ testText = text // bypasses the repeat filter: the button can be pressed again and again+ pump()+ }++ private var testText: String? = null++ private fun pump() {+ if (speaking != null) return+ val ctx = app ?: return+ val engine = tts+ if (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 attrs = nextAttrs ?: return+ speaking = item+ speakingAttrs = attrs+ holdFocus(ctx, attrs)+ engine.setAudioAttributes(attrs)+ engine.setSpeechRate(Prefs.voiceRate(ctx))+ val params = Bundle().apply { putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1f) }+ if (engine.speak(item.text, TextToSpeech.QUEUE_FLUSH, params, "rf-${System.nanoTime()}") != TextToSpeech.SUCCESS) {+ speaking = null+ releaseFocus()+ }+ }++ private fun start(ctx: Context) {+ ready = false+ val google = runCatching { ctx.packageManager.getPackageInfo(GOOGLE_TTS, 0) }.isSuccess+ val listener = TextToSpeech.OnInitListener { status -> main.post { onInit(status) } }+ tts = if (google) TextToSpeech(ctx, listener, GOOGLE_TTS) else TextToSpeech(ctx, listener)+ }++ private fun onInit(status: Int) {+ val engine = tts ?: return+ if (status != TextToSpeech.SUCCESS) {+ // Engine missing or updating: try again with the next alert instead of staying silent.+ runCatching { engine.shutdown() }+ tts = null+ queue.clear()+ return+ }+ engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() {+ override fun onStart(id: String?) {}+ override fun onDone(id: String?) = finished()+ @Deprecated("Deprecated in Java")+ override fun onError(id: String?) = finished()+ override fun onError(id: String?, errorCode: Int) = finished()+ override fun onStop(id: String?, interrupted: Boolean) {}+ })+ voices = englishVoices(engine)+ applyVoice(engine)+ ready = true+ pump()+ }++ private fun finished() {+ main.post {+ speaking = null+ // A short breath between phrases, then the next (or give the audio back).+ main.postDelayed({ pump() }, 250)+ }+ }++ /** 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())+ .filter { it.locale.language == "en" && !it.features.orEmpty().contains(TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED) }+ .sortedWith(+ compareBy<android.speech.tts.Voice> { it.isNetworkConnectionRequired }+ .thenByDescending { it.quality }+ .thenBy { if (it.locale.country == "US") 0 else if (it.locale.country == "GB") 1 else 2 }+ .thenBy { it.name }+ )++ private fun applyVoice(engine: TextToSpeech) {+ val ctx = app ?: return+ val chosen = Prefs.voiceName(ctx)?.let { name -> voices.firstOrNull { it.name == name } }+ val voice = chosen ?: voices.firstOrNull()+ if (voice != null) engine.voice = voice+ else engine.language = Locale.US+ }++ /** After the voice was changed in Settings. */+ fun voiceChanged(context: Context) = main.post {+ app = context.applicationContext+ tts?.let { if (ready) applyVoice(it) }+ }++ /** Starts the engine early (Settings opens the voice list). */+ fun warmUp(context: Context, onReady: () -> Unit = {}) = main.post {+ app = context.applicationContext+ if (tts == null) start(context.applicationContext)+ fun waitReady(tries: Int) {+ if (ready) onReady() else if (tries > 0) main.postDelayed({ waitReady(tries - 1) }, 200)+ }+ waitReady(50)+ }++ private fun holdFocus(ctx: Context, attrs: AudioAttributes) {+ if (focus != null) return+ val am = ctx.getSystemService(AudioManager::class.java) ?: return+ val req = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)+ .setAudioAttributes(attrs)+ .build()+ focus = req+ am.requestAudioFocus(req)+ }++ private fun releaseFocus() {+ val req = focus ?: return+ focus = null+ app?.getSystemService(AudioManager::class.java)?.abandonAudioFocusRequest(req)+ }++ fun shutdown() = main.post {+ queue.clear()+ speaking = null+ releaseFocus()+ tts?.shutdown()+ tts = null+ ready = false+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/util/VoiceQueue.kt b/app/src/main/java/com/rfsentinel/app/util/VoiceQueue.ktnew file mode 100644index 0000000..45e8b6e--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/util/VoiceQueue.kt@@ -0,0 +1,73 @@+package com.rfsentinel.app.util++/**+ * What to say next, and what to drop (pure; unit-tested). Spoken alerts must+ * be about *now*: a burst of detections shouldn't leave a minute of stale+ * announcements, the same phrase shouldn't repeat back to back, and the most+ * urgent thing (something following you) goes first.+ */+class VoiceQueue(+ private val maxAgeMs: Long = MAX_AGE_MS,+ private val repeatGapMs: Long = REPEAT_GAP_MS+) {+ data class Item(val text: String, val priority: Int, val time: Long)++ companion object {+ const val MAX_AGE_MS = 12_000L+ const val REPEAT_GAP_MS = 30_000L+ /** From this many waiting, they're merged into one announcement. */+ const val MERGE_FROM = 3++ // Priorities.+ const val FOLLOWING = 4+ const val STRONG = 3+ const val PROBABLE = 2+ const val WEAK = 1+ }++ private val waiting = ArrayList<Item>()+ private val lastSaid = HashMap<String, Long>()++ val size get() = waiting.size++ /** Queues [text]; false when it's a repeat of something said (or waiting) recently. */+ fun add(text: String, priority: Int, now: Long): Boolean {+ val key = text.trim().lowercase()+ if (waiting.any { it.text.trim().lowercase() == key }) return false+ lastSaid[key]?.let { if (now - it < repeatGapMs) return false }+ waiting += Item(text, priority, now)+ return true+ }++ /** True when [priority] should interrupt something of [speaking] priority. */+ fun preempts(priority: Int, speaking: Int) = priority >= FOLLOWING && priority > speaking++ /**+ * The next thing to say, or null: stale items are dropped, the most urgent+ * (then oldest) goes first, and a pile-up becomes one sentence.+ */+ fun next(now: Long): Item? {+ waiting.removeAll { now - it.time > maxAgeMs }+ if (waiting.isEmpty()) return null+ val ordered = waiting.sortedWith(compareByDescending<Item> { it.priority }.thenBy { it.time })+ val item = if (ordered.size >= MERGE_FROM && ordered.first().priority < FOLLOWING) {+ // "3 alerts: Axon body camera nearby, Flock camera nearby and Drone overhead"+ val names = ordered.take(3).map { it.text.trim().trimEnd('.') }+ val more = ordered.size - names.size+ val list = names.dropLast(1).joinToString(", ") + " and " + names.last() ++ (if (more > 0) ", and $more more" else "")+ waiting.clear()+ Item("${ordered.size} alerts: $list.", ordered.first().priority, now)+ .also { ordered.forEach { o -> lastSaid[o.text.trim().lowercase()] = now } }+ } else {+ waiting.remove(ordered.first())+ ordered.first()+ }+ lastSaid[item.text.trim().lowercase()] = now+ // Keep the repeat memory small.+ if (lastSaid.size > 64) lastSaid.entries.removeAll { now - it.value > repeatGapMs }+ return item+ }++ fun clear() = waiting.clear()+}diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex 27eaca0..46ac550 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -233,6 +233,59 @@android:layout_height="wrap_content"android:text="Spoken alerts (e.g. while driving)" />+ <TextView style="@style/SettingsLabel" android:text="Voice speed" />++ <RadioGroup+ android:id="@+id/voiceRateGroup"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="horizontal">++ <RadioButton+ android:id="@+id/voiceRateSlow"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Slow" />++ <RadioButton+ android:id="@+id/voiceRateNormal"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Normal" />++ <RadioButton+ android:id="@+id/voiceRateFast"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Fast" />+ </RadioGroup>++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="horizontal">++ <Button+ android:id="@+id/voicePickButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Choose voice" />++ <Button+ android:id="@+id/voiceTestButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Test voice" />+ </LinearLayout>++ <TextView+ android:id="@+id/voiceText"+ style="@style/SettingsLabel"+ android:paddingTop="0dp"+ android:textSize="12sp" />+<com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/bubbleSwitch"android:layout_width="match_parent"diff --git a/app/src/test/java/com/rfsentinel/app/util/VoiceQueueTest.kt b/app/src/test/java/com/rfsentinel/app/util/VoiceQueueTest.ktnew file mode 100644index 0000000..9dbdfba--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/util/VoiceQueueTest.kt@@ -0,0 +1,59 @@+package com.rfsentinel.app.util++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class VoiceQueueTest {++ @Test+ fun mostUrgentFirstThenOldest() {+ val q = VoiceQueue()+ q.add("Drone overhead", VoiceQueue.PROBABLE, 0)+ q.add("Warning. Tracker may be following you.", VoiceQueue.FOLLOWING, 100)+ assertEquals("Warning. Tracker may be following you.", q.next(200)!!.text)+ assertEquals("Drone overhead", q.next(300)!!.text)+ assertNull(q.next(400))+ }++ @Test+ fun staleAlertsAreDropped() {+ val q = VoiceQueue()+ q.add("Flock camera nearby", VoiceQueue.STRONG, 0)+ assertNull(q.next(VoiceQueue.MAX_AGE_MS + 1))+ }++ @Test+ fun noRepeatWithin30Seconds() {+ val q = VoiceQueue()+ assertTrue(q.add("Axon body camera nearby", VoiceQueue.STRONG, 0))+ assertFalse(q.add("axon body camera nearby", VoiceQueue.STRONG, 10)) // already waiting+ q.next(20)+ assertFalse(q.add("Axon body camera nearby", VoiceQueue.STRONG, 10_000))+ assertTrue(q.add("Axon body camera nearby", VoiceQueue.STRONG, 40_000))+ }++ @Test+ fun pileUpBecomesOneSentence() {+ val q = VoiceQueue()+ q.add("Axon body camera nearby", VoiceQueue.STRONG, 0)+ q.add("Flock camera nearby", VoiceQueue.PROBABLE, 1)+ q.add("Drone overhead", VoiceQueue.PROBABLE, 2)+ q.add("Cell network warning", VoiceQueue.WEAK, 3)+ assertEquals(+ "4 alerts: Axon body camera nearby, Flock camera nearby and Drone overhead, and 1 more.",+ q.next(10)!!.text+ )+ assertEquals(0, q.size)+ }++ @Test+ fun onlyFollowingInterrupts() {+ val q = VoiceQueue()+ assertTrue(q.preempts(VoiceQueue.FOLLOWING, VoiceQueue.STRONG))+ assertFalse(q.preempts(VoiceQueue.STRONG, VoiceQueue.PROBABLE))+ assertFalse(q.preempts(VoiceQueue.FOLLOWING, VoiceQueue.FOLLOWING))+ }+}