Wake word, from the review: a heard word always shows, holds end, stop and retry
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
1. Heard, but not the assistant and not on screen: Android blocks the activity start silently and runCatching called it a success, so nothing opened and nothing was posted. The opening is decided from what Android allows (wakeOpening: session, activity while an activity of the app is started, else a notification); "Heard you. Tap to ask." goes on a channel of its own (high importance, fixed words, times out after a minute) and the sheet cancels it. Settings says that only the digital assistant app opens by voice over other apps, with a row to that system setting. 2. The hold after the word is apart from the sheets' count and ends on a process scope in a finally; a starting service clears it. 3. A tap on the state in Settings retries now (WakeStatus.retryNow -> WakeListener.retryNow) and restarts the back-off; thirty seconds of samples taken in also resets the count of failures. 4. State writes carry the instance's token (WakeStatus.begin): an older instance's last "off" no longer overwrites a newer one. Engine.create is synchronized and writes the keywords to a file of its own. 5. numTrailingBlanks = 1 means more than one blank frame after the phrase (about 80 ms): the comment is corrected, and Settings and the test row say to pause after the phrase. 6. Stop no longer calls stopService or stopSelf() under a possible pending foreground start: the setting goes off and the loop ends the service with stopSelf(lastStartId); a start that arrives after the loop ended begins it again. 7. The "tap to listen again" notification is cancelled when the service starts. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
24 files changed
+615
-104
No files matched your search
@@ -1,9 +1,12 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.os.Bundle
|
||||
import eu.llembas.android.auth.InstanceStore
|
||||
import eu.llembas.android.wake.AppVisibility
|
||||
|
||||
/** The process: one store of instances, and the notification channels, made once. */
|
||||
class LembasApp : Application() {
|
||||
@@ -13,6 +16,25 @@ class LembasApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instances = InstanceStore(this)
|
||||
// Whether the app is on screen: the wake word may open the assistant's sheet as an
|
||||
// activity only then (Android blocks one started from the background, silently).
|
||||
registerActivityLifecycleCallbacks(
|
||||
object : ActivityLifecycleCallbacks {
|
||||
override fun onActivityStarted(activity: Activity) = AppVisibility.activityStarted()
|
||||
|
||||
override fun onActivityStopped(activity: Activity) = AppVisibility.activityStopped()
|
||||
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
|
||||
|
||||
override fun onActivityResumed(activity: Activity) = Unit
|
||||
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
|
||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
|
||||
|
||||
override fun onActivityDestroyed(activity: Activity) = Unit
|
||||
},
|
||||
)
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannels(
|
||||
listOf(
|
||||
|
||||
@@ -2,6 +2,7 @@ package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
@@ -18,6 +19,7 @@ import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
|
||||
/** What a way into the sheet asks for. */
|
||||
enum class Opening {
|
||||
@@ -74,6 +76,8 @@ class AssistActivity : ComponentActivity() {
|
||||
keyguard = getSystemService(KeyguardManager::class.java)
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
AssistPresence.shown()
|
||||
// The sheet is up: "Heard you. Tap to ask." has been answered, however it was opened.
|
||||
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
|
||||
take(intent)
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
|
||||
@@ -4,6 +4,7 @@ package eu.llembas.android.ui.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.role.RoleManager
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.SystemClock
|
||||
@@ -138,6 +139,7 @@ interface SettingsActions {
|
||||
fun wakePhrase(id: String) {}
|
||||
fun wakeSensitivity(id: String) {}
|
||||
fun wakeTest() {}
|
||||
fun wakeRetry() {}
|
||||
fun wakeScreenOnly(on: Boolean) {}
|
||||
fun batterySettings() {}
|
||||
fun notificationSummaries(on: Boolean) {}
|
||||
@@ -177,6 +179,8 @@ data class SettingsState(
|
||||
val wakeState: WakeState = WakeState.Off,
|
||||
/** "Test the wake word": whether its ten seconds are running, and how often the phrase landed. */
|
||||
val wakeTest: WakeTestShown = WakeTestShown(),
|
||||
/** Whether LLeMbas is the phone's digital assistant app: only then can the wake word open it over other apps. */
|
||||
val isAssistant: Boolean = true,
|
||||
/** Whether Android's notification access is given to LLeMbas. */
|
||||
val notificationAccess: Boolean = false,
|
||||
/** Whether this build can read notifications at all (only the `notifications` build declares the listener). */
|
||||
@@ -290,7 +294,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
|
||||
else -> scope.launch {
|
||||
store.savePrefs { it.copy(wakeWord = false) }
|
||||
WakeWordService.stop(context)
|
||||
WakeWordService.stop()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -303,6 +307,13 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
scope.launch { store.savePrefs { it.copy(wakeSensitivity = id) } }
|
||||
}
|
||||
|
||||
// A tap on the wake word's state: start it if the phone stopped it (asking for the
|
||||
// microphone where that is missing), and if it is waiting to try again, try now.
|
||||
override fun wakeRetry() {
|
||||
WakeStatus.retryNow()
|
||||
wakeWord(true)
|
||||
}
|
||||
|
||||
override fun wakeTest() {
|
||||
tested = true
|
||||
WakeStatus.startTrial(SystemClock.elapsedRealtime())
|
||||
@@ -391,6 +402,8 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
phoneRecognizer = remember { PhoneRecognizer.available(context) },
|
||||
wakeAvailable = WakeEngine.AVAILABLE,
|
||||
wakeState = wakeState,
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
isAssistant = context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) ?: false,
|
||||
wakeTest = WakeTestShown(running = clock < trial.until, done = tested && clock >= trial.until, heard = if (tested) trial.heard else 0),
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
notificationAccess = NotificationAccess.granted(context),
|
||||
@@ -709,8 +722,18 @@ internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onCho
|
||||
else -> null
|
||||
},
|
||||
tint = if (trouble) palette.warning else null,
|
||||
onClick = { actions.wakeWord(true) },
|
||||
onClick = actions::wakeRetry,
|
||||
)
|
||||
if (!state.isAssistant) {
|
||||
// Said plainly: Android lets only the phone's assistant open over other apps.
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Assistant,
|
||||
stringResource(R.string.wake_not_assistant),
|
||||
subtitle = stringResource(R.string.wake_not_assistant_line),
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.wakeAvailable) {
|
||||
val phrase = WakePhrases.byId(state.prefs.wakePhrase)
|
||||
|
||||
@@ -2,14 +2,21 @@ package eu.llembas.android.wake
|
||||
|
||||
import android.content.Context
|
||||
import eu.llembas.android.R
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** One word of a wake phrase: its [id], how it is written for the person, and its spelling in the model's [pieces]. */
|
||||
data class WakeWord(val id: String, val words: String, val pieces: String)
|
||||
@@ -88,14 +95,91 @@ interface WakeMicrophone {
|
||||
* Whether the assistant's sheet is up -- the wake-word service lets go of the microphone while
|
||||
* it is, and takes it back once the sheet is gone. Counted, since the session and the activity
|
||||
* can overlap for a moment when one hands over to the other.
|
||||
*
|
||||
* The wake word's own hold is apart from the count: when the word is heard the microphone is
|
||||
* the sheet's for a few seconds ([holdFor]), whether or not a sheet then says it is up. It ends
|
||||
* by itself on a scope that outlives the service, so a service that is destroyed in those
|
||||
* seconds cannot leave the wake word "paused while the assistant is open" for good.
|
||||
*/
|
||||
object AssistPresence {
|
||||
private val sheets = MutableStateFlow(0)
|
||||
private val held = MutableStateFlow(0L)
|
||||
private val holds = AtomicLong(0)
|
||||
private val _open = MutableStateFlow(0)
|
||||
val open: StateFlow<Int> = _open.asStateFlow()
|
||||
|
||||
fun shown() = _open.update { it + 1 }
|
||||
private val process = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
fun hidden() = _open.update { (it - 1).coerceAtLeast(0) }
|
||||
private fun count() {
|
||||
_open.value = sheets.value + if (held.value != 0L) 1 else 0
|
||||
}
|
||||
|
||||
fun shown() {
|
||||
sheets.update { it + 1 }
|
||||
count()
|
||||
}
|
||||
|
||||
fun hidden() {
|
||||
sheets.update { (it - 1).coerceAtLeast(0) }
|
||||
count()
|
||||
}
|
||||
|
||||
/** The word was heard: the microphone is the sheet's for [millis], then the hold lets go by itself. */
|
||||
fun holdFor(millis: Long, scope: CoroutineScope = process) {
|
||||
// Each hold has a number of its own, never used twice, so an old one cannot end a newer one.
|
||||
val mine = holds.incrementAndGet()
|
||||
held.value = mine
|
||||
count()
|
||||
scope.launch {
|
||||
try {
|
||||
delay(millis)
|
||||
} finally {
|
||||
// Only the newest hold lets go; an older one that ends later changes nothing.
|
||||
if (held.compareAndSet(mine, 0L)) count()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** No hold is left standing: the wake-word service starts from what the sheets say alone. */
|
||||
fun release() {
|
||||
held.value = 0L
|
||||
count()
|
||||
}
|
||||
}
|
||||
|
||||
/** How the assistant is opened when the word was heard, from what Android will allow. */
|
||||
enum class WakeOpening {
|
||||
/** LLeMbas is the phone's assistant: its voice-interaction service shows the sheet, from anywhere. */
|
||||
Session,
|
||||
|
||||
/** The app is on screen: the sheet's activity may start. */
|
||||
Activity,
|
||||
|
||||
/**
|
||||
* Neither: Android blocks an activity started from the background, and says nothing when it
|
||||
* does -- so it is not relied on, and a notification to tap is posted.
|
||||
*/
|
||||
Notification,
|
||||
}
|
||||
|
||||
fun wakeOpening(isAssistant: Boolean, appVisible: Boolean): WakeOpening = when {
|
||||
isAssistant -> WakeOpening.Session
|
||||
appVisible -> WakeOpening.Activity
|
||||
else -> WakeOpening.Notification
|
||||
}
|
||||
|
||||
/** Whether the app has an activity on screen: counted from every activity's start and stop (LembasApp). */
|
||||
object AppVisibility {
|
||||
private val started = AtomicInteger(0)
|
||||
val visible: Boolean get() = started.get() > 0
|
||||
|
||||
fun activityStarted() {
|
||||
started.incrementAndGet()
|
||||
}
|
||||
|
||||
fun activityStopped() {
|
||||
started.updateAndGet { (it - 1).coerceAtLeast(0) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -160,7 +244,13 @@ sealed interface WakeState {
|
||||
*/
|
||||
data class WakeTrial(val until: Long = 0, val heard: Int = 0)
|
||||
|
||||
/** The wake word's state for the whole process: written by the service, read by everything else. */
|
||||
/**
|
||||
* The wake word's state for the whole process: written by the service, read by everything else.
|
||||
*
|
||||
* A service instance writes with the token [begin] gave it, and only the newest token's writes
|
||||
* count: an old instance on its way out (its loop ending after Settings turned the wake word off
|
||||
* and on again) cannot write its "off" over the new one's state.
|
||||
*/
|
||||
object WakeStatus {
|
||||
private val _state = MutableStateFlow<WakeState>(WakeState.Off)
|
||||
val state: StateFlow<WakeState> = _state.asStateFlow()
|
||||
@@ -168,10 +258,31 @@ object WakeStatus {
|
||||
private val _trial = MutableStateFlow(WakeTrial())
|
||||
val trial: StateFlow<WakeTrial> = _trial.asStateFlow()
|
||||
|
||||
fun set(now: WakeState) {
|
||||
_state.value = now
|
||||
private val _retries = MutableStateFlow(0)
|
||||
|
||||
/** Counts up each time somebody asks for a retry now ([retryNow]). */
|
||||
val retries: StateFlow<Int> = _retries.asStateFlow()
|
||||
|
||||
private val generation = AtomicInteger(0)
|
||||
|
||||
/** A new writer takes over: its token, which makes every older one's writes count for nothing. */
|
||||
fun begin(): Int = generation.incrementAndGet()
|
||||
|
||||
/** [now], if [token] is still the newest writer's. */
|
||||
fun set(token: Int, now: WakeState) {
|
||||
synchronized(generation) {
|
||||
if (token == generation.get()) _state.value = now
|
||||
}
|
||||
}
|
||||
|
||||
/** [now], said by the app itself, outside any service instance: not started and why, turned off. */
|
||||
fun set(now: WakeState) {
|
||||
synchronized(generation) { _state.value = now }
|
||||
}
|
||||
|
||||
/** Try again now, instead of when the back-off says: the person tapped the failure. */
|
||||
fun retryNow() = _retries.update { it + 1 }
|
||||
|
||||
/** Start a test at [now]: the next [TRIAL_MS] of heard phrases are counted, not acted on. */
|
||||
fun startTrial(now: Long) {
|
||||
_trial.value = WakeTrial(until = now + TRIAL_MS)
|
||||
@@ -190,6 +301,13 @@ object WakeStatus {
|
||||
const val TRIAL_MS = 10_000L
|
||||
}
|
||||
|
||||
/**
|
||||
* What the service's notification says the moment Android starts it (again): what is true --
|
||||
* [current], while its loop is [running]; "starting" for a service that has only just begun.
|
||||
* Never a phrase by default.
|
||||
*/
|
||||
fun wakeStateAtStart(running: Boolean, current: WakeState): WakeState = if (running && current != WakeState.Off) current else WakeState.Starting
|
||||
|
||||
/**
|
||||
* [state] in plain words: the notification's title and Settings' line. A failure names what
|
||||
* failed and that it is tried again; it never claims to listen while it does not.
|
||||
|
||||
@@ -10,9 +10,13 @@ import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/** What the service wants right now: this phrase, spelled for the engine as [keywords], unless [pause]d. */
|
||||
data class WakePlan(val phrase: WakePhrase, val keywords: String, val pause: WakePause)
|
||||
@@ -67,11 +71,20 @@ class WakeListener(
|
||||
detectorFor = null
|
||||
}
|
||||
|
||||
private val nudges = MutableStateFlow(0)
|
||||
|
||||
/** How many samples the last stretch of listening heard before it ended. */
|
||||
@Volatile private var listened = 0L
|
||||
|
||||
/** Try again now rather than when the back-off says: somebody asked. The count of failures starts over. */
|
||||
fun retryNow() = nudges.update { it + 1 }
|
||||
|
||||
/** Listen for [plan]'s phrase until cancelled: after the word, again; after a failure, again later. */
|
||||
private suspend fun hear(plan: WakePlan) {
|
||||
var failures = 0
|
||||
while (true) {
|
||||
try {
|
||||
listened = 0
|
||||
listen(plan)
|
||||
failures = 0
|
||||
heard(plan.phrase)
|
||||
@@ -84,7 +97,11 @@ class WakeListener(
|
||||
say(WakeState.Failed(e.why, e.detail))
|
||||
// A build without an engine does not grow one: nothing to try again.
|
||||
if (e.why == WakeFailure.NoEngine) return
|
||||
delay(backoff(failures++))
|
||||
// It had been listening well for a while: this is a new trouble, not the old one again.
|
||||
if (listened >= STEADY_SAMPLES) failures = 0
|
||||
val seen = nudges.value
|
||||
val asked = withTimeoutOrNull(backoff(failures++)) { nudges.first { it != seen } } != null
|
||||
if (asked) failures = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,6 +131,7 @@ class WakeListener(
|
||||
continue
|
||||
}
|
||||
empty = 0
|
||||
listened += read
|
||||
val samples = FloatArray(read)
|
||||
var sound = false
|
||||
for (i in 0 until read) {
|
||||
@@ -177,5 +195,8 @@ class WakeListener(
|
||||
private const val EMPTY_READS = 50
|
||||
private const val SILENT_SAMPLES = RATE * 5
|
||||
private const val HEARD_REST_MS = 1_500L
|
||||
|
||||
/** Half a minute of sound taken in: the microphone and the engine work. */
|
||||
private const val STEADY_SAMPLES = RATE * 30L
|
||||
}
|
||||
}
|
||||
@@ -31,9 +31,9 @@ import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
@@ -58,6 +58,13 @@ class WakeWordService : LifecycleService() {
|
||||
private val batterySaver = MutableStateFlow(false)
|
||||
private val mayRecord = MutableStateFlow(true)
|
||||
private var following: Job? = null
|
||||
private var watching: Job? = null
|
||||
|
||||
/** This instance's right to write the state (WakeStatus.begin). */
|
||||
private var token = 0
|
||||
|
||||
/** The newest start Android has delivered: what the service stops itself by, so a start still on its way is not stopped. */
|
||||
private var lastStart = 0
|
||||
|
||||
/** Set when the service could not even start: the state then says why, and is not wiped on the way out. */
|
||||
private var keepState = false
|
||||
@@ -97,17 +104,23 @@ class WakeWordService : LifecycleService() {
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
super.onStartCommand(intent, flags, startId)
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
// Stop is the setting going off; the loop sees it and ends the service on the path
|
||||
// that has shown its notification first (follow). The service is stopped from here
|
||||
// only when nothing is running in it, and only if no newer start is on its way
|
||||
// (stopSelf(startId)): stopping under a pending foreground start closes the app.
|
||||
lifecycleScope.launch {
|
||||
lembas.instances.savePrefs { it.copy(wakeWord = false) }
|
||||
stopSelf()
|
||||
if (following?.isActive != true) stopSelf(startId)
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
lastStart = startId
|
||||
mayRecord.value = micAllowed(this)
|
||||
val running = following?.isActive == true
|
||||
// The notification first: Android stops a foreground service that is slow to show one.
|
||||
// It says what is true now -- "starting" for a service that just began, and on every
|
||||
// later start (the app opens) whatever the state already is; never a phrase by default.
|
||||
val now = WakeStatus.state.value.takeUnless { following == null || it == WakeState.Off } ?: WakeState.Starting
|
||||
val now = wakeStateAtStart(running, WakeStatus.state.value)
|
||||
try {
|
||||
ServiceCompat.startForeground(this, NOTIFICATION_ID, wakeNotification(this, now), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
|
||||
} catch (e: Exception) {
|
||||
@@ -124,23 +137,45 @@ class WakeWordService : LifecycleService() {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (following == null) {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
// It is listening again: "tap to listen again" (after a restart) has nothing left to say.
|
||||
manager.cancel(WakeBootReceiver.RESUME_ID)
|
||||
if (!running) {
|
||||
keepState = false
|
||||
WakeStatus.set(now)
|
||||
// This instance writes the state from here; an older one's last words count for nothing.
|
||||
token = WakeStatus.begin()
|
||||
// And it starts from what the sheets say: no hold of an earlier instance is left standing.
|
||||
AssistPresence.release()
|
||||
WakeStatus.set(token, now)
|
||||
following = lifecycleScope.launch { follow() }
|
||||
}
|
||||
if (watching == null) {
|
||||
// The one place the notification is written: from the state, whenever it changes.
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
lifecycleScope.launch {
|
||||
watching = lifecycleScope.launch {
|
||||
WakeStatus.state.collect { state ->
|
||||
if (state != WakeState.Off) manager.notify(NOTIFICATION_ID, wakeNotification(this@WakeWordService, state))
|
||||
}
|
||||
}
|
||||
// A tap on the failure in Settings: try now, not when the back-off says.
|
||||
lifecycleScope.launch { WakeStatus.retries.drop(1).collect { listener.retryNow() } }
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private val listener by lazy {
|
||||
WakeListener(
|
||||
say = { WakeStatus.set(token, it) },
|
||||
engine = { keywords -> WakeEngine.create(this, keywords) },
|
||||
microphone = { PhoneMicrophone() },
|
||||
// A test in Settings takes the word; otherwise the assistant opens.
|
||||
heard = { if (!WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) wake() },
|
||||
log = { message, cause -> Log.w(TAG, message, cause) },
|
||||
)
|
||||
}
|
||||
|
||||
/** Listen, or pause, as the phone and Settings change; stop when Settings turns it off. */
|
||||
private suspend fun follow() {
|
||||
val mine = token
|
||||
val plans = combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open, mayRecord) { prefs, on, saver, open, mic ->
|
||||
if (!prefs.wakeWord) {
|
||||
null
|
||||
@@ -149,50 +184,36 @@ class WakeWordService : LifecycleService() {
|
||||
WakePlan(phrase, wakeKeywords(phrase, WakeSensitivity.byId(prefs.wakeSensitivity)), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic))
|
||||
}
|
||||
}
|
||||
val listener = WakeListener(
|
||||
say = WakeStatus::set,
|
||||
engine = { keywords -> WakeEngine.create(this, keywords) },
|
||||
microphone = { PhoneMicrophone() },
|
||||
// A test in Settings takes the word; otherwise the assistant opens.
|
||||
heard = { if (!WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) wake() },
|
||||
log = { message, cause -> Log.w(TAG, message, cause) },
|
||||
)
|
||||
try {
|
||||
listener.follow(plans.takeWhile { it != null }.filterNotNull())
|
||||
} finally {
|
||||
// After the loop has ended, so nothing it said on its way out is left standing.
|
||||
if (!keepState) WakeStatus.set(WakeState.Off)
|
||||
// After the loop has ended, so nothing it said on its way out is left standing --
|
||||
// and only if no newer writer has taken over meanwhile.
|
||||
if (!keepState) WakeStatus.set(mine, WakeState.Off)
|
||||
}
|
||||
stopSelf()
|
||||
// Not if a newer start is already on its way: that one finds the loop ended and begins it again.
|
||||
stopSelf(lastStart)
|
||||
}
|
||||
|
||||
/**
|
||||
* The word was heard: the assistant opens listening. Through the voice-interaction service
|
||||
* when LLeMbas is the phone's assistant (Android lets it open the sheet from the background),
|
||||
* else as an activity; and if Android refuses that too, a notification to tap.
|
||||
* when LLeMbas is the phone's assistant (Android lets it open the sheet from the background);
|
||||
* as an activity while the app is on screen; and otherwise with a notification to tap,
|
||||
* because Android blocks an activity started from the background and says nothing when it
|
||||
* does ([wakeOpening]). The activity is still tried then -- where a phone allows it, it
|
||||
* opens and takes the notification away.
|
||||
*/
|
||||
private fun wake() {
|
||||
AssistPresence.shown() // the microphone is the sheet's from here, until it says it is gone
|
||||
val shownBySystem = LembasAssistService.current?.let { service ->
|
||||
runCatching { service.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.isSuccess
|
||||
} ?: false
|
||||
val opened = shownBySystem || runCatching { startActivity(AssistActivity.listening(this).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess
|
||||
if (!opened) {
|
||||
getSystemService(NotificationManager::class.java).notify(
|
||||
HEARD_ID,
|
||||
NotificationCompat.Builder(this, CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(getString(R.string.wake_heard))
|
||||
.setContentIntent(PendingIntent.getActivity(this, 1, AssistActivity.listening(this), PendingIntent.FLAG_IMMUTABLE))
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
// Released by the sheet as it shows and hides; if nothing opened, at once.
|
||||
lifecycleScope.launch {
|
||||
delay(SHEET_GRACE_MS)
|
||||
AssistPresence.hidden()
|
||||
// The microphone is the sheet's from here: for a moment by this hold, then for as long as a sheet says it is up.
|
||||
AssistPresence.holdFor(SHEET_GRACE_MS)
|
||||
val session = LembasAssistService.current
|
||||
val shownBySystem = session != null &&
|
||||
runCatching { session.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.isSuccess
|
||||
val opening = wakeOpening(shownBySystem, AppVisibility.visible)
|
||||
if (opening == WakeOpening.Session) return
|
||||
val started = runCatching { startActivity(AssistActivity.listening(this).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess
|
||||
if (opening == WakeOpening.Notification || !started) {
|
||||
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,14 +223,15 @@ class WakeWordService : LifecycleService() {
|
||||
runCatching { unregisterReceiver(receiver) }
|
||||
// The scope ends with the service: the listener's loop is joined and its engine released
|
||||
// on the way out (WakeListener.follow), not here under a loop that may still run.
|
||||
if (!keepState) WakeStatus.set(WakeState.Off)
|
||||
if (!keepState) WakeStatus.set(token, WakeState.Off)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL = "wake_word"
|
||||
const val CHANNEL_HEARD = "wake_heard"
|
||||
private const val NOTIFICATION_ID = 7001
|
||||
private const val HEARD_ID = 7002
|
||||
const val HEARD_ID = 7002
|
||||
private const val SHEET_GRACE_MS = 3_000L
|
||||
private const val TAG = "LLeMbasWake"
|
||||
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
|
||||
@@ -230,21 +252,51 @@ class WakeWordService : LifecycleService() {
|
||||
}
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, WakeWordService::class.java))
|
||||
/**
|
||||
* The wake word was turned off. The service is not stopped from outside: it ends itself
|
||||
* when it sees the setting, after it has shown its notification -- stopping it under a
|
||||
* foreground start that is still on its way closes the app. The state is "off" at once.
|
||||
*/
|
||||
fun stop() {
|
||||
WakeStatus.set(WakeState.Off)
|
||||
}
|
||||
|
||||
fun micAllowed(context: Context) = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun channel(context: Context) {
|
||||
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
|
||||
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
|
||||
context.getSystemService(NotificationManager::class.java).createNotificationChannels(
|
||||
listOf(
|
||||
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
|
||||
// "Heard you. Tap to ask.": it must come up over what is on screen, or the word was for nothing.
|
||||
NotificationChannel(CHANNEL_HEARD, context.getString(R.string.channel_wake_heard), NotificationManager.IMPORTANCE_HIGH),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Heard you. Tap to ask.": what the wake word posts when it cannot open the assistant itself.
|
||||
* A fixed sentence, nothing from the account; the tap opens the assistant listening.
|
||||
*/
|
||||
fun wakeHeardNotification(context: Context): Notification {
|
||||
val ask = PendingIntent.getActivity(context, 1, AssistActivity.listening(context), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return NotificationCompat.Builder(context, WakeWordService.CHANNEL_HEARD)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.wake_heard))
|
||||
.setContentText(context.getString(R.string.wake_heard_line))
|
||||
.setContentIntent(ask)
|
||||
.setAutoCancel(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setTimeoutAfter(HEARD_TIMEOUT_MS)
|
||||
.build()
|
||||
}
|
||||
|
||||
/** A minute: a "tap to ask" nobody tapped is no longer an answer to anything. */
|
||||
private const val HEARD_TIMEOUT_MS = 60_000L
|
||||
|
||||
/**
|
||||
* The persistent notification, from [state] alone: what the wake word is doing in plain words
|
||||
* (the phrase it listens for, why it is paused, what failed). Nothing from the account.
|
||||
|
||||
Reference in new issue
Block a user