Wake word: the wake runs outside the loop it pauses; what Android says is recorded
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
Review W1 (must): wake() was a suspend function run inside the hearing job, and its own first step -- holding the microphone for the sheet -- paused the listener, which cancelled that job: no wait for the sheet, no fallback, and no "Last wake" record for a real wake. - WakeListener hands `heard` to the scope beside the listening, so a pause never cancels the answer (test: a suspending heard that pauses the plan). The service runs the wake on the app's own scope, one at a time, holds the microphone for the whole attempt, and writes the record NonCancellable. - WakeOpener holds the order of what is tried, apart from Android, with tests: wait up to 1 s for the connection when Android says the service is active; "opened" only once a sheet says it is up; a session that was not refused gets a second wait before anything else is shown (W3: never two sheets -- and the session closes a sheet the wake word opened in its place); the activity counts only where Android will start it. - The record gains isActiveService, FEATURE_VOICE_RECOGNIZERS, screen, keyguard, app visible, ms until the sheet, the service's onCreate and onDestroy times, onPrepareToShowSession / onShowSessionFailed (API 34+), and whether the connection was waited for. Settings says when the role is held but Android does not use LLeMbas as its voice assistant. - AssistLink.shutdown is guarded by instance. W2: a session counts as up once per show; the activity from onStart to onStop. W4: the activity says it is up from onStart and onNewIntent, and turns the screen on there too. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
22 files changed
+740
-97
No files matched your search
@@ -22,6 +22,7 @@ import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
/** What a way into the sheet asks for. */
|
||||
enum class Opening {
|
||||
@@ -61,6 +62,8 @@ enum class Opening {
|
||||
class AssistActivity : ComponentActivity() {
|
||||
private lateinit var controller: AssistController
|
||||
private lateinit var keyguard: KeyguardManager
|
||||
private var started = false
|
||||
private var byWake = false
|
||||
|
||||
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
|
||||
private val locked = mutableStateOf(false)
|
||||
@@ -79,11 +82,7 @@ class AssistActivity : ComponentActivity() {
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
|
||||
// so nothing else has woken the phone).
|
||||
if (intent?.getBooleanExtra(EXTRA_WAKE, false) == true) setTurnScreenOn(true)
|
||||
AssistPresence.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// The sheet is up: "Heard you. Tap to ask." has been answered, however it was opened.
|
||||
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
|
||||
woken(intent)
|
||||
take(intent)
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
@@ -113,13 +112,48 @@ class AssistActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Opened again while it is up -- the headset's button pressed twice, the tile again. */
|
||||
/** Opened again while it is up -- the headset's button pressed twice, the tile again, the wake word. */
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
woken(intent)
|
||||
// The same sheet answers again: it is up, and whoever asked for it is told so.
|
||||
if (started) AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
take(intent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch, so
|
||||
* nothing else has woken the phone), and the sheet is remembered as the wake word's, so that
|
||||
* the assistant's own sheet can take its place if that one comes after all.
|
||||
*/
|
||||
private fun woken(intent: Intent?) {
|
||||
byWake = intent?.getBooleanExtra(EXTRA_WAKE, false) == true
|
||||
if (byWake) setTurnScreenOn(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* On screen: only now is the sheet "up" -- for the wake word's pause (which must end when the
|
||||
* sheet is left with Home, not only when it is destroyed) and for whoever waits to hear that
|
||||
* it opened.
|
||||
*/
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
started = true
|
||||
open = WeakReference(this)
|
||||
AssistPresence.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// "Heard you. Tap to ask." has been answered, however the sheet was opened.
|
||||
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
started = false
|
||||
if (open?.get() === this) open = null
|
||||
AssistPresence.hidden()
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
/**
|
||||
* What the way in asked for: a question handed over by the session, listening (the headset's
|
||||
* voice button, the widget's microphone, the Speak shortcut), the last assistant chat (the
|
||||
@@ -158,7 +192,6 @@ class AssistActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
AssistPresence.hidden()
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -178,6 +211,15 @@ class AssistActivity : ComponentActivity() {
|
||||
/** The sheet, listening. */
|
||||
fun listening(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN)
|
||||
|
||||
/** The sheet that is on screen now, if this activity is it. */
|
||||
@Volatile
|
||||
private var open: WeakReference<AssistActivity>? = null
|
||||
|
||||
/** The assistant's own sheet came up: a sheet the wake word had opened in its place goes. */
|
||||
fun closeWoken() {
|
||||
open?.get()?.takeIf { it.byWake }?.finish()
|
||||
}
|
||||
|
||||
/** On the intent the wake word opens the sheet with: turn the screen on. */
|
||||
const val EXTRA_WAKE = "eu.llembas.android.WAKE"
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package eu.llembas.android.assist
|
||||
import android.app.KeyguardManager
|
||||
import android.app.assist.AssistStructure
|
||||
import android.app.role.RoleManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
@@ -49,6 +50,11 @@ import kotlinx.coroutines.runBlocking
|
||||
* preinstalled assistant (`CAPTURE_AUDIO_HOTWORD` is a privileged permission).
|
||||
*/
|
||||
class LembasAssistService : VoiceInteractionService() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
AssistLink.created(System.currentTimeMillis())
|
||||
}
|
||||
|
||||
override fun onReady() {
|
||||
super.onReady()
|
||||
current = this
|
||||
@@ -61,12 +67,33 @@ class LembasAssistService : VoiceInteractionService() {
|
||||
}
|
||||
|
||||
override fun onShutdown() {
|
||||
if (current === this) current = null
|
||||
AssistLink.shutdown(System.currentTimeMillis())
|
||||
// Only the instance that is the current one disconnects it: an old one going away late
|
||||
// must not say "not connected" over a new one.
|
||||
if (current === this) {
|
||||
current = null
|
||||
AssistLink.shutdown(System.currentTimeMillis())
|
||||
}
|
||||
Log.i(TAG, "assistant service disconnected by Android")
|
||||
super.onShutdown()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
AssistLink.destroyed(System.currentTimeMillis())
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/** Android 14+: Android is about to show a session it was asked for -- or, below, could not. Kept for the wake word's record. */
|
||||
override fun onPrepareToShowSession(args: Bundle, showFlags: Int) {
|
||||
AssistLink.prepared(SystemClock.elapsedRealtime())
|
||||
super.onPrepareToShowSession(args, showFlags)
|
||||
}
|
||||
|
||||
override fun onShowSessionFailed(args: Bundle) {
|
||||
AssistLink.showFailed(SystemClock.elapsedRealtime())
|
||||
Log.w(TAG, "Android could not show the assistant's session")
|
||||
super.onShowSessionFailed(args)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* The service while the system has it bound -- while LLeMbas is the phone's assistant. The
|
||||
@@ -80,6 +107,16 @@ class LembasAssistService : VoiceInteractionService() {
|
||||
private const val TAG = "LLeMbasWake"
|
||||
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
/**
|
||||
* Whether Android itself uses this service as its voice-interaction service right now.
|
||||
* Holding the assistant role is not the same: Android keeps the service only while a
|
||||
* speech recogniser is set that it accepts, and resets it at start-up otherwise -- the
|
||||
* long press then opens the assistant as an ordinary screen, and nothing is connected
|
||||
* that could open it from the background.
|
||||
*/
|
||||
fun isActive(context: Context): Boolean =
|
||||
runCatching { VoiceInteractionService.isActiveService(context, ComponentName(context, LembasAssistService::class.java)) }.getOrDefault(false)
|
||||
|
||||
/** Whether Android says LLeMbas holds the assistant role (Settings › Default apps › Digital assistant app). */
|
||||
fun holdsRole(context: Context): Boolean =
|
||||
runCatching { context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) }.getOrNull() ?: false
|
||||
@@ -104,6 +141,9 @@ class LembasAssistSession(context: Context) :
|
||||
private var controller = AssistController(context, scope)
|
||||
private val current = mutableStateOf(controller)
|
||||
|
||||
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
|
||||
private var up = false
|
||||
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
|
||||
@@ -152,8 +192,16 @@ class LembasAssistSession(context: Context) :
|
||||
override fun onShow(args: Bundle?, showFlags: Int) {
|
||||
super.onShow(args, showFlags)
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
AssistPresence.shown()
|
||||
// Android calls this again for a show asked for while the sheet is up, and hides once:
|
||||
// the sheet is counted as up once.
|
||||
if (!up) {
|
||||
up = true
|
||||
AssistPresence.shown()
|
||||
}
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
|
||||
// this one was slow to come, goes now that this one is here.
|
||||
AssistActivity.closeWoken()
|
||||
// The wake word asks for the sheet listening, whatever Settings says about opening.
|
||||
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
|
||||
}
|
||||
@@ -165,7 +213,10 @@ class LembasAssistSession(context: Context) :
|
||||
*/
|
||||
override fun onHide() {
|
||||
super.onHide()
|
||||
AssistPresence.hidden()
|
||||
if (up) {
|
||||
up = false
|
||||
AssistPresence.hidden()
|
||||
}
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
@@ -187,6 +187,8 @@ data class SettingsState(
|
||||
val isAssistant: Boolean = true,
|
||||
/** Whether Android has the assistant service connected right now: without it the wake word cannot open the sheet by itself. */
|
||||
val assistantConnected: Boolean = true,
|
||||
/** Whether Android itself uses LLeMbas's service as its voice assistant (the role can be held without it). */
|
||||
val assistantActive: 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). */
|
||||
@@ -412,6 +414,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
isAssistant = LembasAssistService.holdsRole(context),
|
||||
assistantConnected = assistantConnected,
|
||||
assistantActive = LembasAssistService.isActive(context),
|
||||
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),
|
||||
@@ -741,6 +744,18 @@ internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onCho
|
||||
subtitle = stringResource(R.string.wake_not_assistant_line),
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
} else if (!state.assistantActive) {
|
||||
// Chosen as the assistant, yet Android does not run it as its voice assistant:
|
||||
// the long press opens it as an ordinary screen, and nothing is connected that
|
||||
// could open it from the background. Choosing it again puts that right.
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Assistant,
|
||||
stringResource(R.string.wake_assistant_inactive),
|
||||
subtitle = stringResource(R.string.wake_assistant_inactive_line),
|
||||
tint = palette.warning,
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
} else if (!state.assistantConnected) {
|
||||
// The assistant in name, but Android holds no connection to it at this moment:
|
||||
// the one thing that lets the sheet open from the background is missing.
|
||||
|
||||
@@ -303,11 +303,30 @@ fun wakeAttemptWords(context: Context, attempt: WakeAttempt, zone: ZoneId = Zone
|
||||
WakeWay.Activity.id -> lines += context.getString(R.string.wake_out_activity)
|
||||
WakeWay.Notification.id -> lines += context.getString(R.string.wake_out_notification)
|
||||
}
|
||||
if (attempt.outcome == WakeAttempt.OUT_OPENED || attempt.outcome == WakeAttempt.OUT_TESTED) return lines
|
||||
lines += context.getString(if (attempt.assistant) R.string.wake_role_held else R.string.wake_role_not_held)
|
||||
if (attempt.outcome == WakeAttempt.OUT_TESTED) return lines
|
||||
if (attempt.sheetMs >= 0) lines += context.getString(R.string.wake_sheet_ms, attempt.sheetMs.toString())
|
||||
if (attempt.outcome == WakeAttempt.OUT_OPENED) return lines
|
||||
// Why the assistant's own way was not there, from what Android itself said at that moment.
|
||||
lines += when {
|
||||
!attempt.assistant -> context.getString(R.string.wake_role_not_held)
|
||||
!attempt.recognizers -> context.getString(R.string.wake_no_recognizers)
|
||||
!attempt.active -> context.getString(R.string.wake_not_active)
|
||||
else -> context.getString(R.string.wake_role_held)
|
||||
}
|
||||
if (attempt.waited) lines += context.getString(R.string.wake_waited)
|
||||
if (attempt.showFailed) lines += context.getString(R.string.wake_show_failed)
|
||||
lines += if (attempt.readyAt == 0L) context.getString(R.string.wake_link_never) else context.getString(R.string.wake_link_ready, time(attempt.readyAt))
|
||||
if (attempt.shutdownAt != 0L) lines += context.getString(R.string.wake_link_shutdown, time(attempt.shutdownAt))
|
||||
if (attempt.connectedLater != 0L) lines += context.getString(R.string.wake_link_later, time(attempt.connectedLater))
|
||||
// The rest as it was noted, for whoever looks for the cause: names and values, not a sentence.
|
||||
lines += listOf(
|
||||
"screen=${if (attempt.screenOn) "on" else "off"}",
|
||||
"locked=${attempt.locked}",
|
||||
"visible=${attempt.visible}",
|
||||
"created=${if (attempt.createdAt == 0L) "-" else time(attempt.createdAt)}",
|
||||
"destroyed=${if (attempt.destroyedAt == 0L) "-" else time(attempt.destroyedAt)}",
|
||||
"prepared=${attempt.prepared}",
|
||||
).joinToString(" ")
|
||||
return lines
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ class WakeListener(
|
||||
|
||||
/** Listen as [plans] say, until the flow ends or this is cancelled; the engine is released on the way out. */
|
||||
suspend fun follow(plans: Flow<WakePlan>) = coroutineScope {
|
||||
// Where a heard word is answered: beside the listening, so a pause does not cancel the answer.
|
||||
val answers = this
|
||||
var hearing: Job? = null
|
||||
try {
|
||||
plans.distinctUntilChanged().collect { plan ->
|
||||
@@ -54,7 +56,7 @@ class WakeListener(
|
||||
if (plan.pause != WakePause.None) {
|
||||
say(WakeState.Paused(plan.pause))
|
||||
} else {
|
||||
hearing = launch { hear(plan) }
|
||||
hearing = launch { hear(plan) { phrase -> answers.launch { heard(phrase) } } }
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -80,14 +82,17 @@ class WakeListener(
|
||||
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) {
|
||||
private suspend fun hear(plan: WakePlan, heardIt: (WakePhrase) -> Unit) {
|
||||
var failures = 0
|
||||
while (true) {
|
||||
try {
|
||||
listened = 0
|
||||
listen(plan)
|
||||
failures = 0
|
||||
heard(plan.phrase)
|
||||
// Handed to the caller's scope, not run here: answering the word usually pauses
|
||||
// the listening (the sheet takes the microphone), which cancels this very loop --
|
||||
// and must not cancel the answer with it.
|
||||
heardIt(plan.phrase)
|
||||
// The sheet takes the microphone now (a new plan cancels this); otherwise listen again.
|
||||
delay(HEARD_REST_MS)
|
||||
} catch (e: CancellationException) {
|
||||
|
||||
@@ -31,6 +31,29 @@ data class WakeAttempt(
|
||||
val shutdownAt: Long = 0,
|
||||
/** Set afterwards, when the service was not connected and Android connected it later. */
|
||||
val connectedLater: Long = 0,
|
||||
/**
|
||||
* Whether Android itself said LLeMbas's service is its active voice-interaction service
|
||||
* (`VoiceInteractionService.isActiveService`). The role can be held without it: Android then
|
||||
* opens the assistant as an ordinary screen on a long press, and keeps no connection that
|
||||
* could open it from the background.
|
||||
*/
|
||||
val active: Boolean = false,
|
||||
/** Whether the phone has voice recognisers at all (`FEATURE_VOICE_RECOGNIZERS`): without it Android runs no voice-interaction service. */
|
||||
val recognizers: Boolean = true,
|
||||
val screenOn: Boolean = true,
|
||||
val locked: Boolean = false,
|
||||
/** Whether one of the app's own screens was showing. */
|
||||
val visible: Boolean = false,
|
||||
/** How long the sheet took to say it was up, in ms; -1 when none came. */
|
||||
val sheetMs: Long = -1,
|
||||
/** When the assistant service was last made and destroyed in this run of the app; 0: never. */
|
||||
val createdAt: Long = 0,
|
||||
val destroyedAt: Long = 0,
|
||||
/** Whether the wake waited for Android to connect the service (it was active but not connected yet). */
|
||||
val waited: Boolean = false,
|
||||
/** What Android told the service about this show (API 34+): it prepared one, or it failed. */
|
||||
val prepared: Boolean = false,
|
||||
val showFailed: Boolean = false,
|
||||
) {
|
||||
companion object {
|
||||
/** The sheet came up. */
|
||||
@@ -98,21 +121,32 @@ fun wakeWay(connected: Boolean, screenOn: Boolean, appVisible: Boolean): WakeWay
|
||||
else -> WakeWay.Notification
|
||||
}
|
||||
|
||||
/** What is left when the assistant's own way did not open the sheet. */
|
||||
fun wakeFallback(appVisible: Boolean): WakeWay = if (appVisible) WakeWay.Activity else WakeWay.Notification
|
||||
|
||||
/**
|
||||
* The assistant service's life in this run of the app, as Android told it: when it was made,
|
||||
* connected (`onReady`), disconnected (`onShutdown`), and when a sheet last came up. Written by
|
||||
* the assistant service, the session and the sheet's activity; read when the word is heard.
|
||||
* connected (`onReady`), disconnected (`onShutdown`) and destroyed, what Android said of the last
|
||||
* show it was asked for, and when a sheet last came up. Written by the assistant service, the
|
||||
* session and the sheet's activity; read when the word is heard.
|
||||
*/
|
||||
object AssistLink {
|
||||
@Volatile var createdAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var destroyedAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var readyAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var shutdownAt = 0L
|
||||
private set
|
||||
|
||||
/** On the phone's elapsed clock: when Android last said it prepares to show a session, and when one failed to show. */
|
||||
@Volatile var preparedAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var showFailedAt = 0L
|
||||
private set
|
||||
|
||||
private val _shown = MutableStateFlow(0L)
|
||||
|
||||
/** When a sheet last came up, on the phone's elapsed clock (ms); 0: not yet. */
|
||||
@@ -123,6 +157,14 @@ object AssistLink {
|
||||
/** Whether Android has the assistant service connected right now. */
|
||||
val connected: StateFlow<Boolean> = _connected.asStateFlow()
|
||||
|
||||
fun created(now: Long) {
|
||||
createdAt = now
|
||||
}
|
||||
|
||||
fun destroyed(now: Long) {
|
||||
destroyedAt = now
|
||||
}
|
||||
|
||||
fun ready(now: Long) {
|
||||
readyAt = now
|
||||
_connected.value = true
|
||||
@@ -133,7 +175,129 @@ object AssistLink {
|
||||
_connected.value = false
|
||||
}
|
||||
|
||||
fun prepared(elapsed: Long) {
|
||||
preparedAt = elapsed
|
||||
}
|
||||
|
||||
fun showFailed(elapsed: Long) {
|
||||
showFailedAt = elapsed
|
||||
}
|
||||
|
||||
fun sheetShown(elapsed: Long) {
|
||||
_shown.value = elapsed
|
||||
}
|
||||
}
|
||||
|
||||
/** What is true of the phone and the assistant at the moment the phrase is heard. */
|
||||
data class WakeFacts(
|
||||
/** The assistant service is connected (`LembasAssistService.current` is there). */
|
||||
val connected: Boolean,
|
||||
/** Android says the service is its active voice-interaction service. */
|
||||
val active: Boolean,
|
||||
/** LLeMbas holds the assistant role. */
|
||||
val role: Boolean,
|
||||
val recognizers: Boolean = true,
|
||||
val screenOn: Boolean = true,
|
||||
val locked: Boolean = false,
|
||||
val visible: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Opening the assistant when the phrase was heard, apart from Android so that the order of what
|
||||
* is tried -- and what is written down about it -- can be tested.
|
||||
*
|
||||
* 1. The assistant's own way, where its service is connected ([wakeWay]). When Android says the
|
||||
* service is active but has not connected it yet, a moment is waited for the connection.
|
||||
* 2. "Opened" only once a sheet says it is up ([sheetCame]).
|
||||
* 3. Otherwise the sheet's activity -- relied on only where Android will start it: the service is
|
||||
* connected (a bound service lets the whole app start activities) or the app is on screen. A
|
||||
* session that was only slow is given a second wait first, so there are never two sheets.
|
||||
* 4. Otherwise a notification to tap.
|
||||
*
|
||||
* [open] returns what happened, for the record.
|
||||
*/
|
||||
class WakeOpener(
|
||||
private val facts: () -> WakeFacts,
|
||||
/** Wait up to the given ms for Android to connect the service; whether it did. */
|
||||
private val awaitConnected: suspend (Long) -> Boolean,
|
||||
/** Ask the connected service to show its sheet; throws what Android throws. */
|
||||
private val showSession: () -> Unit,
|
||||
/** Start the sheet's activity; throws what Android throws. */
|
||||
private val startActivity: () -> Unit,
|
||||
/** Wait up to the given ms for a sheet to say it is up; how long it took, or null. */
|
||||
private val sheetCame: suspend (Long) -> Long?,
|
||||
private val notify: (WakeAttempt) -> Unit,
|
||||
/** What Android said of the show since it was asked: prepared, failed. */
|
||||
private val showSignals: () -> Pair<Boolean, Boolean> = { false to false },
|
||||
private val now: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
suspend fun open(phrase: String, link: WakeAttempt = WakeAttempt()): WakeAttempt {
|
||||
var seen = facts()
|
||||
var waited = false
|
||||
if (!seen.connected && seen.active) {
|
||||
// Android's own assistant, only not connected at this instant: it may be on its way.
|
||||
waited = true
|
||||
if (awaitConnected(CONNECT_WAIT_MS)) seen = facts().copy(connected = true)
|
||||
}
|
||||
val way = wakeWay(seen.connected, seen.screenOn, seen.visible)
|
||||
var attempt = link.copy(
|
||||
at = now(),
|
||||
phrase = phrase,
|
||||
way = way.id,
|
||||
assistant = seen.role,
|
||||
active = seen.active,
|
||||
recognizers = seen.recognizers,
|
||||
screenOn = seen.screenOn,
|
||||
locked = seen.locked,
|
||||
visible = seen.visible,
|
||||
waited = waited,
|
||||
)
|
||||
if (way == WakeWay.Session || way == WakeWay.AssistantActivity) {
|
||||
val refused = runCatching { if (way == WakeWay.Session) showSession() else startActivity() }.exceptionOrNull()
|
||||
val took = if (refused == null) sheetCame(SHEET_WAIT_MS) else null
|
||||
val (prepared, failed) = showSignals()
|
||||
attempt = attempt.copy(prepared = prepared, showFailed = failed)
|
||||
if (took != null) return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = took)
|
||||
attempt = if (refused != null) {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_REFUSED, detail = describe(refused))
|
||||
} else {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_NO_SHEET)
|
||||
}
|
||||
// The activity was the way that just did not come up: starting it a second time is no fallback.
|
||||
if (way == WakeWay.AssistantActivity && refused == null) return notified(attempt)
|
||||
// A session Android did not refuse may only be slow: a second wait, before anything
|
||||
// else is put on screen beside it.
|
||||
if (refused == null) {
|
||||
sheetCame(SHEET_WAIT_MS)?.let { late -> return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = SHEET_WAIT_MS + late) }
|
||||
}
|
||||
} else {
|
||||
attempt = attempt.copy(outcome = WakeAttempt.OUT_NOT_CONNECTED)
|
||||
}
|
||||
// The sheet's activity. Android blocks one started from the background without a word,
|
||||
// so it counts only where it may start -- and only once it says it is up.
|
||||
val started = runCatching { startActivity() }.isSuccess
|
||||
if (started && (seen.connected || seen.visible)) {
|
||||
sheetCame(SHEET_WAIT_MS)?.let { took -> return attempt.copy(fallback = WakeWay.Activity.id, sheetMs = took) }
|
||||
}
|
||||
return notified(attempt)
|
||||
}
|
||||
|
||||
private fun notified(attempt: WakeAttempt): WakeAttempt {
|
||||
val told = attempt.copy(fallback = WakeWay.Notification.id)
|
||||
notify(told)
|
||||
return told
|
||||
}
|
||||
|
||||
private fun describe(e: Throwable): String = listOfNotNull(e.javaClass.simpleName, e.message?.takeIf { it.isNotBlank() }).joinToString(": ").take(200)
|
||||
|
||||
companion object {
|
||||
/** How long a sheet has to say it is up before the way that was tried counts as not having opened it. */
|
||||
const val SHEET_WAIT_MS = 2_500L
|
||||
|
||||
/** How long Android is given to connect a service it says is active. */
|
||||
const val CONNECT_WAIT_MS = 1_000L
|
||||
|
||||
/** The longest an attempt can take: the connection, three waits for a sheet, and a margin. The microphone is held that long. */
|
||||
const val ATTEMPT_MAX_MS = CONNECT_WAIT_MS + 3 * SHEET_WAIT_MS + 1_500L
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
@@ -31,6 +32,8 @@ import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.drop
|
||||
@@ -38,6 +41,7 @@ import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
@@ -172,7 +176,8 @@ class WakeWordService : LifecycleService() {
|
||||
// A test in Settings takes the word; otherwise the assistant opens.
|
||||
heard = { phrase ->
|
||||
if (WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) {
|
||||
record(WakeAttempt(at = System.currentTimeMillis(), phrase = phrase.words, outcome = WakeAttempt.OUT_TESTED))
|
||||
val tested = WakeAttempt(at = System.currentTimeMillis(), phrase = phrase.words, outcome = WakeAttempt.OUT_TESTED)
|
||||
wakeScope.launch { record(this@WakeWordService, tested) }
|
||||
} else {
|
||||
wake(phrase)
|
||||
}
|
||||
@@ -204,68 +209,56 @@ class WakeWordService : LifecycleService() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The word was heard: the assistant opens listening, by the first way Android allows
|
||||
* ([wakeWay]) -- and what was tried and how it went is written down ([WakeAttempt], kept in
|
||||
* the settings and shown in Settings › Wake word), because a silent "no" here looks to the
|
||||
* The word was heard: the assistant opens listening ([WakeOpener] decides how and checks that
|
||||
* it did), and what was tried and how it went is written down ([WakeAttempt], kept in the
|
||||
* settings and shown in Settings › Wake word), because a silent "no" here looks to the
|
||||
* person like a wake word that does not work.
|
||||
*
|
||||
* A way that Android does not refuse is not yet a sheet on screen: the sheet says when it
|
||||
* is up ([AssistLink.shown]), and when it has not said so in time the fallback follows --
|
||||
* the activity while the app is on screen, else a notification to tap (the activity is
|
||||
* still tried then; where a phone allows it, it opens and takes the notification away).
|
||||
* It runs on the app's own scope, never inside the listening loop: the hold below pauses
|
||||
* the listener, which cancels the loop that heard the word -- and a wake that ran in that
|
||||
* loop was cancelled by its own first step. One at a time: a word heard while the last one
|
||||
* is still being answered is let go.
|
||||
*/
|
||||
private suspend fun wake(phrase: WakePhrase) {
|
||||
// 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 asked = SystemClock.elapsedRealtime()
|
||||
val assistant = LembasAssistService.current
|
||||
val way = wakeWay(connected = assistant != null, screenOn = power().isInteractive, appVisible = AppVisibility.visible)
|
||||
var attempt = WakeAttempt(
|
||||
at = System.currentTimeMillis(),
|
||||
phrase = phrase.words,
|
||||
way = way.id,
|
||||
assistant = LembasAssistService.holdsRole(this),
|
||||
readyAt = AssistLink.readyAt,
|
||||
shutdownAt = AssistLink.shutdownAt,
|
||||
)
|
||||
// The assistant's own ways first, where it is connected.
|
||||
val refused: Throwable? = when (way) {
|
||||
WakeWay.Session -> runCatching { assistant?.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.exceptionOrNull()
|
||||
WakeWay.AssistantActivity -> runCatching { assistant?.startActivity(AssistActivity.woken(this)) }.exceptionOrNull()
|
||||
else -> null
|
||||
}
|
||||
if (way == WakeWay.Session || way == WakeWay.AssistantActivity) {
|
||||
if (refused == null && sheetCame(asked)) return record(attempt.copy(outcome = WakeAttempt.OUT_OPENED))
|
||||
attempt = if (refused != null) {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_REFUSED, detail = WakeError(WakeFailure.Engine, refused).detail)
|
||||
} else {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_NO_SHEET)
|
||||
private fun wake(phrase: WakePhrase) {
|
||||
if (waking?.isActive == true) return
|
||||
// The microphone is the sheet's from here, for as long as the attempt can take; once it
|
||||
// is over, for a moment more, and then for as long as a sheet says it is up.
|
||||
AssistPresence.holdFor(WakeOpener.ATTEMPT_MAX_MS)
|
||||
waking = wakeScope.launch {
|
||||
try {
|
||||
val asked = SystemClock.elapsedRealtime()
|
||||
val opener = WakeOpener(
|
||||
facts = { wakeFacts(this@WakeWordService) },
|
||||
awaitConnected = { ms -> withTimeoutOrNull(ms) { AssistLink.connected.first { it } } != null },
|
||||
showSession = {
|
||||
val assistant = LembasAssistService.current ?: error("the assistant service is not connected")
|
||||
assistant.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0)
|
||||
},
|
||||
// Through the assistant service where it is connected (the same permission either way: Android lets
|
||||
// the whole app start activities while it holds the service bound).
|
||||
startActivity = { (LembasAssistService.current ?: this@WakeWordService).startActivity(AssistActivity.woken(this@WakeWordService)) },
|
||||
sheetCame = { ms ->
|
||||
withTimeoutOrNull(ms) { AssistLink.shown.first { it >= asked } }?.let { (it - asked).coerceAtLeast(0) }
|
||||
},
|
||||
notify = { attempt ->
|
||||
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this@WakeWordService, attempt.assistant))
|
||||
},
|
||||
showSignals = { (AssistLink.preparedAt >= asked) to (AssistLink.showFailedAt >= asked) },
|
||||
)
|
||||
val link = WakeAttempt(
|
||||
createdAt = AssistLink.createdAt,
|
||||
destroyedAt = AssistLink.destroyedAt,
|
||||
readyAt = AssistLink.readyAt,
|
||||
shutdownAt = AssistLink.shutdownAt,
|
||||
)
|
||||
record(this@WakeWordService, opener.open(phrase.words, link))
|
||||
} finally {
|
||||
AssistPresence.holdFor(SHEET_GRACE_MS)
|
||||
}
|
||||
} else {
|
||||
attempt = attempt.copy(outcome = WakeAttempt.OUT_NOT_CONNECTED)
|
||||
}
|
||||
// Then what is left: the sheet's activity, relied on only while the app is on screen.
|
||||
val fallback = wakeFallback(AppVisibility.visible)
|
||||
val started = runCatching { startActivity(AssistActivity.woken(this)) }
|
||||
if (fallback == WakeWay.Activity && started.isSuccess && sheetCame(asked)) {
|
||||
return record(attempt.copy(fallback = WakeWay.Activity.id))
|
||||
}
|
||||
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this, attempt.assistant))
|
||||
record(attempt.copy(fallback = WakeWay.Notification.id))
|
||||
}
|
||||
|
||||
/** Whether a sheet came up since [asked] (the phone's elapsed clock), waiting a moment for it. */
|
||||
private suspend fun sheetCame(asked: Long): Boolean = withTimeoutOrNull(SHEET_WAIT_MS) { AssistLink.shown.first { it >= asked } } != null
|
||||
|
||||
/** Write [attempt] down: in the log under a fixed tag, and first among the last few in the settings. */
|
||||
private suspend fun record(attempt: WakeAttempt) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"wake word heard: way=${attempt.way} outcome=${attempt.outcome} fallback=${attempt.fallback} assistant=${attempt.assistant} " +
|
||||
"readyAt=${attempt.readyAt} shutdownAt=${attempt.shutdownAt} ${attempt.detail}",
|
||||
)
|
||||
runCatching { lembas.instances.savePrefs { it.copy(wakeLog = wakeLogAdd(it.wakeLog, attempt)) } }
|
||||
}
|
||||
private var waking: Job? = null
|
||||
|
||||
private fun power() = getSystemService(PowerManager::class.java)
|
||||
|
||||
@@ -284,8 +277,29 @@ class WakeWordService : LifecycleService() {
|
||||
const val HEARD_ID = 7002
|
||||
private const val SHEET_GRACE_MS = 3_000L
|
||||
|
||||
/** How long a sheet has to say it is up before the way that was tried counts as not having opened it. */
|
||||
private const val SHEET_WAIT_MS = 2_500L
|
||||
/** The app's own scope: a wake and its record outlive the listening loop, and the service too. */
|
||||
private val wakeScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
/** What is true at this moment, for the opener and the record. */
|
||||
fun wakeFacts(context: Context): WakeFacts = WakeFacts(
|
||||
connected = LembasAssistService.current != null,
|
||||
active = LembasAssistService.isActive(context),
|
||||
role = LembasAssistService.holdsRole(context),
|
||||
recognizers = context.packageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS),
|
||||
screenOn = context.getSystemService(PowerManager::class.java).isInteractive,
|
||||
locked = context.getSystemService(KeyguardManager::class.java).isKeyguardLocked,
|
||||
visible = AppVisibility.visible,
|
||||
)
|
||||
|
||||
/**
|
||||
* Write [attempt] down: in the log under a fixed tag, and first among the last few in the
|
||||
* settings. Not cancellable: what happened is kept whatever ends meanwhile.
|
||||
*/
|
||||
suspend fun record(context: Context, attempt: WakeAttempt) = withContext(NonCancellable) {
|
||||
Log.i(TAG, "wake word heard: $attempt")
|
||||
runCatching { context.lembas.instances.savePrefs { it.copy(wakeLog = wakeLogAdd(it.wakeLog, attempt)) } }
|
||||
Unit
|
||||
}
|
||||
private const val TAG = "LLeMbasWake"
|
||||
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
|
||||
|
||||
|
||||
Reference in new issue
Block a user