maauto: focus arbitration + per-channel queues + backoff
- Commit
1c0f358c22de85ff832554772556ccff33012f32- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 21:25 UTC (2 months ago)
- Parents
857d949
Diff
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ChannelSendQueue.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ChannelSendQueue.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ChannelSendQueue.ktnew file mode 100644index 0000000000..938ff07377--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ChannelSendQueue.kt@@ -0,0 +1,96 @@+package com.vayunmathur.auto.protocol++/**+ * One framed message waiting for the wire: the message-codec payload plus the flags its+ * frame needs. Enqueued by any thread, drained only under the connection's engine lock.+ */+class QueuedSend(+ val channelId: Int,+ /** Message-codec bytes (`[type][protobuf]`), not yet framed or TLS-wrapped. */+ val payload: ByteArray,+ val isControl: Boolean,+ val encrypted: Boolean,+)++/**+ * Per-channel send queues with control priority.+ *+ * Why this exists: a video burst must never head-block control traffic or acks. Every+ * `send()` enqueues here; the drain takes channel 0 first (control opens, discovery,+ * ping responses), then round-robins the service channels so a ch2 video flood cannot+ * starve a ch6 ack or a ch8 key binding.+ *+ * Pure JVM, no I/O: the connection owns one of these and drains it under its SSLEngine+ * lock, which is what keeps the single-engine discipline while senders run on any+ * thread (vsync drain, audio sinks, input injection). All methods are synchronized;+ * payloads are never copied, only referenced.+ */+class ChannelSendQueue {+ private val lock = Any()++ /** Channel 0: control opens, discovery, ping responses. Always drains first. */+ private val controlQueue = ArrayDeque<QueuedSend>()++ /** Service channels by id, plus the round-robin order of the non-empty ones. */+ private val channelQueues = LinkedHashMap<Int, ArrayDeque<QueuedSend>>()+ private val channelOrder = ArrayDeque<Int>()++ /** Enqueues [send] on its channel's queue. Thread-safe, never blocks. */+ fun enqueue(send: QueuedSend) = synchronized(lock) {+ if (send.channelId == CONTROL_CHANNEL_ID) {+ controlQueue.addLast(send)+ return@synchronized+ }+ val queue = channelQueues.getOrPut(send.channelId) { ArrayDeque() }+ if (queue.isEmpty()) channelOrder.addLast(send.channelId)+ queue.addLast(send)+ }++ /**+ * Removes and returns the next send: channel 0 first, then service channels in+ * round-robin order, FIFO within each channel. Null when empty.+ */+ fun poll(): QueuedSend? = synchronized(lock) {+ if (controlQueue.isNotEmpty()) return controlQueue.removeFirst()+ while (channelOrder.isNotEmpty()) {+ val id = channelOrder.removeFirst()+ val queue = channelQueues[id] ?: continue+ val send = queue.removeFirstOrNull()+ if (send == null) {+ channelQueues.remove(id)+ continue+ }+ // A still-full channel goes to the back; a drained one leaves the rotation.+ if (queue.isNotEmpty()) channelOrder.addLast(id) else channelQueues.remove(id)+ return send+ }+ return null+ }++ /** Total sends waiting, across all channels. */+ fun pendingCount(): Int = synchronized(lock) {+ controlQueue.size + channelQueues.values.sumOf { it.size }+ }++ /** Total payload bytes waiting. Telemetry only; framing/TLS overhead is extra. */+ fun pendingBytes(): Long = synchronized(lock) {+ controlQueue.sumOf { it.payload.size.toLong() } ++ channelQueues.values.sumOf { queue -> queue.sumOf { it.payload.size.toLong() } }+ }++ fun isEmpty(): Boolean = synchronized(lock) {+ controlQueue.isEmpty() && channelQueues.values.all { it.isEmpty() }+ }++ /** Drops everything unsent. Called when the session ends; a new socket starts clean. */+ fun clear() = synchronized(lock) {+ controlQueue.clear()+ channelQueues.clear()+ channelOrder.clear()+ }++ companion object {+ /** The control channel: its queue always drains ahead of every service channel. */+ const val CONTROL_CHANNEL_ID = 0+ }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FocusArbitration.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FocusArbitration.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FocusArbitration.ktnew file mode 100644index 0000000000..8720854512--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FocusArbitration.kt@@ -0,0 +1,153 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AudioFocusState+import com.vayunmathur.auto.protocol.gal.NavigationFocusType+import com.vayunmathur.auto.protocol.gal.VideoFocusMode++/**+ * Which side currently owns the car screen, normalized from the wire modes.+ *+ * The wire carries four [VideoFocusMode] values; input focus is derived from video focus+ * rather than negotiated separately (gearhead derives it the same way), so the transient+ * and no-input variants fold into these three plus [FocusArbitration.inputAllowed].+ */+enum class VideoFocus {+ /** No focus indication has arrived yet. Nothing streams and nothing injects. */+ NONE,++ /** The car is showing its own UI; the phone must not stream video or inject input. */+ NATIVE,++ /** The phone owns the screen; video streams and input usually flows. */+ PROJECTED,+}++/**+ * What changed in one arbitration step.+ *+ * [GalConnection] watches [FocusArbitration.generation] and forwards changes to the+ * Android side, which mirrors them into `AutoSessionState` without polling.+ */+data class FocusChange(+ val videoChanged: Boolean = false,+ val audioChanged: Boolean = false,+ val navigationChanged: Boolean = false,+) {+ val any: Boolean get() = videoChanged || audioChanged || navigationChanged+}++/**+ * Video/audio/navigation focus arbitration: who owns the screen and the speakers.+ *+ * Pure state machine, no I/O, so the whole preemption matrix is host-testable. Owned by+ * [GalControlSession]: control notifications (audio 0x13, navigation 0x0E) feed it+ * directly, and the video focus indication (0x8008 on the video channel) arrives via+ * `GalControlSession.onVideoFocusIndication`.+ *+ * Semantics, from the gearhead teardown (`FINDINGS.md`):+ *+ * - `VIDEO_FOCUS_PROJECTED` gates both streaming and input.+ * - `VIDEO_FOCUS_PROJECTED_NO_INPUT_FOCUS` still streams ([shouldStreamVideo]) but input+ * from the head unit must be dropped ([inputAllowed] is false).+ * - `VIDEO_FOCUS_NATIVE` and `VIDEO_FOCUS_NATIVE_TRANSIENT` both park the stream; the+ * transient variant is not distinguished here because neither streams.+ * - Audio focus is tracked alongside video: guidance/transient gains decide [mayPlayMedia]+ * while video stays native (e.g. TTS over the car's own UI). Loss variants silence us.+ */+class FocusArbitration {+ /** Which side owns the screen. Starts at [VideoFocus.NONE] until told otherwise. */+ @Volatile+ var videoFocus: VideoFocus = VideoFocus.NONE+ private set++ /**+ * Whether head-unit input may be injected. Derived from video focus, not negotiated:+ * projected video with input focus only.+ */+ @Volatile+ var inputAllowed: Boolean = false+ private set++ /** Last audio focus state the head unit reported. */+ @Volatile+ var audioFocus: AudioFocusState = AudioFocusState.AUDIO_FOCUS_STATE_INVALID+ private set++ /** Whether navigation is projected (control 0x0E `NAV_FOCUS_PROJECTED`). */+ @Volatile+ var navigationProjected: Boolean = false+ private set++ /**+ * Bumps on every accepted change, so a driver can forward focus without diffing+ * three fields.+ */+ @Volatile+ var generation: Long = 0+ private set++ /** Whether video frames may go out: projected focus, transient or not. */+ val shouldStreamVideo: Boolean get() = videoFocus == VideoFocus.PROJECTED++ /**+ * Whether phone audio may play: an explicit gain, or projected video as the+ * implicit grant. Checked by the audio sinks before starting a stream.+ */+ val mayPlayMedia: Boolean get() = when (audioFocus) {+ AudioFocusState.AUDIO_FOCUS_STATE_GAIN,+ AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT,+ AudioFocusState.AUDIO_FOCUS_STATE_GAIN_MEDIA_ONLY,+ AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT_GUIDANCE_ONLY,+ -> true+ // LOSS, LOSS_TRANSIENT, LOSS_TRANSIENT_CAN_DUCK and INVALID silence us.+ // Ducking (CAN_DUCK) is a sink-side volume decision, not a play gate.+ else -> videoFocus == VideoFocus.PROJECTED+ }++ /**+ * Folds a 0x8008 video focus indication into the state. Absent modes are ignored:+ * the lite runtime drops unknown enum values on parse, so a future mode arrives+ * as absent rather than as a wrong known one -- never clobber state with it.+ */+ fun onVideoFocus(mode: VideoFocusMode?): FocusChange {+ if (mode == null) return FocusChange()+ val (focus, input) = when (mode) {+ VideoFocusMode.VIDEO_FOCUS_PROJECTED -> VideoFocus.PROJECTED to true+ VideoFocusMode.VIDEO_FOCUS_PROJECTED_NO_INPUT_FOCUS -> VideoFocus.PROJECTED to false+ VideoFocusMode.VIDEO_FOCUS_NATIVE,+ VideoFocusMode.VIDEO_FOCUS_NATIVE_TRANSIENT,+ -> VideoFocus.NATIVE to false+ }+ if (focus == videoFocus && input == inputAllowed) return FocusChange()+ videoFocus = focus+ inputAllowed = input+ generation+++ return FocusChange(videoChanged = true)+ }++ /** Folds a control 0x13 audio focus notification into the state. */+ fun onAudioFocus(state: AudioFocusState): FocusChange {+ if (state == audioFocus) return FocusChange()+ audioFocus = state+ generation+++ return FocusChange(audioChanged = true)+ }++ /** Folds a control 0x0E navigation focus notification into the state. */+ fun onNavigationFocus(focus: NavigationFocusType): FocusChange {+ val projected = focus == NavigationFocusType.NAV_FOCUS_PROJECTED+ if (projected == navigationProjected) return FocusChange()+ navigationProjected = projected+ generation+++ return FocusChange(navigationChanged = true)+ }++ /** A new socket means a new session: no focus survives a reconnect. */+ fun reset() {+ videoFocus = VideoFocus.NONE+ inputAllowed = false+ audioFocus = AudioFocusState.AUDIO_FOCUS_STATE_INVALID+ navigationProjected = false+ generation+++ }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.ktindex 12b34aba44..62efa0812f 100644--- a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt@@ -1,7 +1,9 @@ package com.vayunmathur.auto.protocol import java.io.Closeable+import java.util.concurrent.locks.ReentrantLock import javax.net.ssl.SSLContext+import kotlin.concurrent.withLock /** A message on a service channel, handed to whatever owns that service. */ fun interface ChannelMessageHandler {@@ -25,10 +27,19 @@ fun isChannelControlMessage(type: Int): Boolean = when (type) { /** * Ties a [GalTransport] to the control session. *- * Owns the single [javax.net.ssl.SSLEngine] for the connection and therefore the read/write- * loop: an engine is not thread-safe, so wrapping and unwrapping both happen on whichever- * thread calls [pump]. Callers drive it rather than it spawning threads, which keeps the- * whole thing testable over an in-memory transport.+ * Owns the single [javax.net.ssl.SSLEngine] for the connection. The engine is not+ * thread-safe, so every wrap and unwrap happens under [engineLock] -- one lock, many+ * threads. The pump thread reads and processes; the vsync encoder thread, the audio+ * sinks and input injection only ever call [send], which enqueues and flushes under+ * the same lock. Callers drive [pump] rather than it spawning threads, which keeps+ * the whole thing testable over an in-memory transport.+ *+ * Outbound traffic goes through per-channel queues ([ChannelSendQueue]): channel 0+ * always drains first and service channels round-robin, so a video burst never+ * head-blocks control opens, ping responses or acks. [send] enqueues then flushes,+ * so latency matches the old immediate write; the queue bites when sends batch up+ * under contention. Batch owners may [enqueue] several messages and [flushSends]+ * once instead. * * The [FrameFlags.ENCRYPTED] flag decides whether a frame goes through TLS, so the same * reader handles the plaintext version and handshake frames and the wrapped ones that@@ -53,12 +64,24 @@ class GalConnection( private val reader = FrameReader(decrypt = tls::unwrap) private val writer = FrameWriter(encrypt = tls::wrap) + /**+ * The single-engine discipline: every [SSLEngine] wrap/unwrap on this connection+ * holds this lock. Reentrant, so [pump] can answer (which [send]s) while holding it.+ */+ private val engineLock = ReentrantLock()++ /** Per-channel outbound queues; see the class KDoc for the drain order. */+ private val sendQueue = ChannelSendQueue()+ val session: GalControlSession = GalControlSession(engine, deviceModel, deviceManufacturer) private val buffer = ByteArray(READ_BUFFER_SIZE) /**- * Reads once and handles whatever that produced.+ * Reads once, handles whatever that produced, then drains the send queue.+ *+ * The blocking read holds no lock; everything engine-touching (unwrap in+ * [FrameReader], wrap in [flushSends]) runs under [engineLock]. * * @return false at end of stream, when the head unit has gone away. */@@ -66,65 +89,64 @@ class GalConnection( val count = transport.read(buffer, 0, buffer.size) if (count < 0) return false - for (message in reader.offer(buffer, 0, count)) {- val decoded = MessageCodec.decode(message.channelId, message.payload)- // Channel-open traffic (0x7 out / 0x8 in) rides the TARGET channel,- // not channel 0: gearhead's `izd.b()` sends the open via- // `izl.g(this.b, ...)` where `b` is the channel being opened, and- // the HU's 0x8 comes back the same way. A ch0-framed 0x7 parses but- // is refused with STATUS_INVALID_CHANNEL (-5, Run 6). So an inbound- // 0x8 on ANY channel belongs to the session; everything else on a- // service channel goes to that channel's owner.- if (message.channelId == CONTROL_CHANNEL ||- decoded.type == GalMessage.Control.CHANNEL_OPEN_RESPONSE- ) {- val before = session.state- val replies = session.onMessage(decoded.type, decoded.payload)- // Log the payload: incoming message bodies are otherwise invisible, and- // the head unit's answers (discovery list, open status, errors) carry- // the only explanation we ever get for a rejection. Control payloads- // are small (a discovery response is a few hundred bytes) and each- // log line comfortably holds ~1.5KB of hex, so log them whole: the- // 64-byte cap once hid the 569-byte service list we needed to see.- trace(- "ctrl in 0x${decoded.type.toString(16)} (${decoded.payload.size}B) " +- "$before -> ${session.state}, ${replies.size} reply " +- decoded.payload.joinToString("") { "%02x".format(it) },- )- session.failure?.let { trace("session failed: $it") }- replies.forEach(::send)- } else {- trace(- "ch${message.channelId} in 0x${decoded.type.toString(16)} " +- "(${decoded.payload.size}B) " +- decoded.payload.take(IN_PAYLOAD_LOG_BYTES).joinToString("") {- "%02x".format(it)- },- )- onChannelMessage.onMessage(decoded)+ engineLock.withLock {+ for (message in reader.offer(buffer, 0, count)) {+ val decoded = MessageCodec.decode(message.channelId, message.payload)+ // Channel-open traffic (0x7 out / 0x8 in) rides the TARGET channel,+ // not channel 0: gearhead's `izd.b()` sends the open via+ // `izl.g(this.b, ...)` where `b` is the channel being opened, and+ // the HU's 0x8 comes back the same way. A ch0-framed 0x7 parses but+ // is refused with STATUS_INVALID_CHANNEL (-5, Run 6). So an inbound+ // 0x8 on ANY channel belongs to the session; everything else on a+ // service channel goes to that channel's owner.+ if (message.channelId == CONTROL_CHANNEL ||+ decoded.type == GalMessage.Control.CHANNEL_OPEN_RESPONSE+ ) {+ val before = session.state+ val replies = session.onMessage(decoded.type, decoded.payload)+ // Log the payload: incoming message bodies are otherwise invisible, and+ // the head unit's answers (discovery list, open status, errors) carry+ // the only explanation we ever get for a rejection. Control payloads+ // are small (a discovery response is a few hundred bytes) and each+ // log line comfortably holds ~1.5KB of hex, so log them whole: the+ // 64-byte cap once hid the 569-byte service list we needed to see.+ trace(+ "ctrl in 0x${decoded.type.toString(16)} (${decoded.payload.size}B) " ++ "$before -> ${session.state}, ${replies.size} reply " ++ decoded.payload.joinToString("") { "%02x".format(it) },+ )+ session.failure?.let { trace("session failed: $it") }+ replies.forEach(::send)+ } else {+ trace(+ "ch${message.channelId} in 0x${decoded.type.toString(16)} " ++ "(${decoded.payload.size}B) " ++ decoded.payload.take(IN_PAYLOAD_LOG_BYTES).joinToString("") {+ "%02x".format(it)+ },+ )+ onChannelMessage.onMessage(decoded)+ } }+ // Sends other threads enqueued while we were blocked in read go out now,+ // control-first, under the same lock as the replies above.+ flushSendsLocked() } return true } - /** Frames a control message and writes it. */+ /**+ * Enqueues a control message and flushes. Thread-safe: safe from the vsync+ * encoder thread, audio sinks and input injection alike.+ */ fun send(message: OutboundMessage) {- // Most control messages ride channel 0; the channel-open request rides- // its target channel (see OutboundMessage.channelId).- write(- channelId = message.channelId,- payload = MessageCodec.encode(message.type, message.payload),- // Per-message: only the channel-open request sets CONTROL today.- // The CONTROL-less 0x5 is live-accepted, so nothing else takes the- // bit; see OutboundMessage.isControl.- isControl = message.isControl,- encrypted = message.encrypted,- )+ enqueue(message)+ flushSends() } /**- * Frames a service-channel message and writes it. Always encrypted, never- * CONTROL-flagged.+ * Enqueues a service-channel message and flushes. Always encrypted, never+ * CONTROL-flagged. Thread-safe; see [send]. * * `jbe.i()` builds flags as `FIRST | LAST | (Lizm.f ? 0x04 : 0) | * (Lizm.h ? 0x08 : 0)`, and every service-channel send goes through@@ -134,14 +156,62 @@ class GalConnection( * belongs only to channel-0 channel-open requests (see [send] above). */ fun send(channelId: Int, type: Int, payload: ByteArray) {- write(- channelId = channelId,- payload = MessageCodec.encode(type, payload),- isControl = false,- encrypted = true,+ enqueue(channelId, type, payload)+ flushSends()+ }++ /**+ * Enqueues a control message without flushing. Pair with [flushSends] when+ * batching several messages; otherwise prefer [send]. Thread-safe.+ */+ fun enqueue(message: OutboundMessage) {+ // Most control messages ride channel 0; the channel-open request rides+ // its target channel (see OutboundMessage.channelId).+ sendQueue.enqueue(+ QueuedSend(+ channelId = message.channelId,+ payload = MessageCodec.encode(message.type, message.payload),+ // Per-message: only the channel-open request sets CONTROL today.+ // The CONTROL-less 0x5 is live-accepted, so nothing else takes the+ // bit; see OutboundMessage.isControl.+ isControl = message.isControl,+ encrypted = message.encrypted,+ ),+ )+ }++ /**+ * Enqueues a service-channel message without flushing. Pair with [flushSends]+ * when batching; otherwise prefer [send]. Thread-safe.+ */+ fun enqueue(channelId: Int, type: Int, payload: ByteArray) {+ sendQueue.enqueue(+ QueuedSend(+ channelId = channelId,+ payload = MessageCodec.encode(type, payload),+ isControl = false,+ encrypted = true,+ ), ) } + /**+ * Writes everything queued, control-first. Thread-safe; holds [engineLock]+ * across the drain so a burst goes out as one ordered unit.+ */+ fun flushSends() = engineLock.withLock { flushSendsLocked() }++ /** Sends still queued, across all channels. Telemetry and tests. */+ fun pendingSends(): Int = sendQueue.pendingCount()++ private fun flushSendsLocked() {+ var next = sendQueue.poll()+ while (next != null) {+ write(next.channelId, next.payload, next.isControl, next.encrypted)+ next = sendQueue.poll()+ }+ }+ private fun write(channelId: Int, payload: ByteArray, isControl: Boolean, encrypted: Boolean) { trace( "out ch$channelId 0x${
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.ktindex 7b0b3fb6e2..bd752f78c9 100644--- a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt@@ -1,16 +1,22 @@ package com.vayunmathur.auto.protocol +import com.vayunmathur.auto.protocol.gal.AudioFocusNotification+import com.vayunmathur.auto.protocol.gal.AudioFocusRequestMessage+import com.vayunmathur.auto.protocol.gal.AudioFocusRequestType import com.vayunmathur.auto.protocol.gal.AuthComplete import com.vayunmathur.auto.protocol.gal.ByeByeReason import com.vayunmathur.auto.protocol.gal.ByeByeRequest import com.vayunmathur.auto.protocol.gal.ChannelOpenRequest import com.vayunmathur.auto.protocol.gal.ChannelOpenResponse import com.vayunmathur.auto.protocol.gal.MessageStatus+import com.vayunmathur.auto.protocol.gal.NavigationFocusNotification import com.vayunmathur.auto.protocol.gal.PingRequest import com.vayunmathur.auto.protocol.gal.PingResponse import com.vayunmathur.auto.protocol.gal.Service import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryRequest import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryResponse+import com.vayunmathur.auto.protocol.gal.VideoFocusIndication+import com.vayunmathur.auto.protocol.gal.VideoFocusMode import java.nio.ByteBuffer import javax.net.ssl.SSLEngine import javax.net.ssl.SSLEngineResult.HandshakeStatus@@ -107,6 +113,19 @@ class GalControlSession( var pendingChannels: List<Int> = emptyList() private set + /**+ * Who owns the screen and the speakers. Fed by the control notifications below+ * and, for video, by [onVideoFocusIndication] (the 0x8008 rides the video+ * channel, so the sink forwards it). The driver observes [onFocusChange].+ */+ val focus = FocusArbitration()++ /**+ * Fires whenever [focus] accepts a change, on whatever thread drives the session.+ * The Android side mirrors this into `AutoSessionState` without polling.+ */+ var onFocusChange: (FocusChange) -> Unit = {}+ private var tlsInbound: ByteBuffer = ByteBuffer.allocate(0) /** Handles one control-channel message and returns whatever should go back. */@@ -122,14 +141,15 @@ class GalControlSession( state = SessionState.CLOSED emptyList() }- // Focus and status notifications are observed by higher layers; the control channel- // itself has nothing to answer.- GalMessage.Control.AUDIO_FOCUS_NOTIFICATION,- GalMessage.Control.NAVIGATION_FOCUS_NOTIFICATION,+ // Call availability and discovery updates are observed by higher layers;+ // the control channel itself has nothing to answer. Focus notifications+ // feed [focus] instead (see below). GalMessage.Control.CALL_AVAILABILITY_STATUS, GalMessage.Control.SERVICE_DISCOVERY_UPDATE, GalMessage.Control.PING_RESPONSE, -> emptyList()+ GalMessage.Control.AUDIO_FOCUS_NOTIFICATION -> onAudioFocusNotification(payload)+ GalMessage.Control.NAVIGATION_FOCUS_NOTIFICATION -> onNavigationFocusNotification(payload) // The head unit's rejection of one of our messages. Observed, not fatal: // gearhead's `izu` logs it (`ai(1698)`) and carries on, and channel-level@@ -190,6 +210,34 @@ class GalControlSession( encrypted = true, ) + /**+ * Folds a video focus indication (0x8008) into [focus].+ *+ * The indication rides the video channel, not channel 0, so the video sink parses+ * it and forwards it here; the session stays the single owner of the+ * arbitration state. Observed, never answered.+ *+ * An unset mode is ignored: the lite runtime drops unknown enum values on parse,+ * so a future mode arrives as absent rather than as a wrong known one -- never+ * clobber a known state with it.+ */+ fun onVideoFocusIndication(indication: VideoFocusIndication) {+ if (!indication.hasMode()) return+ notifyFocus(focus.onVideoFocus(indication.mode))+ }++ /**+ * Asks the head unit for audio focus (control 0x18) for the audio sinks.+ *+ * Fire-and-forget: the head unit answers with an 0x13 notification, which lands+ * in [focus] via [onAudioFocusNotification]. Encrypted like every post-auth send.+ */+ fun requestAudioFocus(type: AudioFocusRequestType): OutboundMessage = OutboundMessage(+ type = GalMessage.Control.AUDIO_FOCUS_REQUEST,+ payload = AudioFocusRequestMessage.newBuilder().setRequest(type).build().toByteArray(),+ encrypted = true,+ )+ // ---- handlers ---- private fun onVersionRequest(payload: ByteArray): List<OutboundMessage> {@@ -315,6 +363,28 @@ class GalControlSession( refusedChannels += id } + /**+ * Folds a control 0x13 audio focus notification into [focus]. Observed, never+ * answered: like gearhead's `izu`, the session carries on regardless.+ */+ private fun onAudioFocusNotification(payload: ByteArray): List<OutboundMessage> {+ notifyFocus(focus.onAudioFocus(AudioFocusNotification.parseFrom(payload).state))+ return emptyList()+ }++ /**+ * Folds a control 0x0E navigation focus notification into [focus]. Observed,+ * never answered.+ */+ private fun onNavigationFocusNotification(payload: ByteArray): List<OutboundMessage> {+ notifyFocus(focus.onNavigationFocus(NavigationFocusNotification.parseFrom(payload).focus))+ return emptyList()+ }++ private fun notifyFocus(change: FocusChange) {+ if (change.any) onFocusChange(change)+ }+ private fun onPing(payload: ByteArray): List<OutboundMessage> = listOf( OutboundMessage( type = GalMessage.Control.PING_RESPONSE,
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessagingCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessagingCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessagingCodec.ktnew file mode 100644index 0000000000..787c723f00--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessagingCodec.kt@@ -0,0 +1,95 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.MessagingAction+import com.vayunmathur.auto.protocol.gal.MessagingActionType+import com.vayunmathur.auto.protocol.gal.MessagingDismiss+import com.vayunmathur.auto.protocol.gal.MessagingMessage+import com.vayunmathur.auto.protocol.gal.MessagingThread+import com.vayunmathur.auto.protocol.gal.MessagingThreads++/**+ * A user action that arrived on ch14, already classified.+ *+ * The head unit is the only sender: the phone never sends [GalMessage.Notification.ACTION]+ * to itself, so anything else on this channel in this direction is out of scope and+ * decodes to null rather than throwing.+ */+sealed interface InboundMessagingAction {+ /** The user typed a reply on the head unit; [text] is what they wrote. */+ data class Reply(val threadId: String, val text: String) : InboundMessagingAction++ /** The user marked the thread read on the head unit. */+ data class MarkRead(val threadId: String) : InboundMessagingAction++ /**+ * The user asked to reply by voice: the owner opens a ch6 mic turn for+ * [threadId] through [com.vayunmathur.auto.platform.MessagingAudio] and the+ * transcribed text comes back as a [Reply].+ */+ data class VoiceReplyBegin(val threadId: String) : InboundMessagingAction+}++/**+ * Pure ch14 (NOTIFICATION, service 14) codecs: threads, body, reply, mark-read.+ *+ * Android-free like everything else in this module, so the whole message set is+ * host-testable. Each encoder returns the channel type alongside the payload;+ * the driver frames them with [MessageCodec] and sends them with+ * `GalConnection.send(channelId, type, payload)` -- always encrypted, never+ * CONTROL-flagged, like all service-channel traffic.+ */+object MessagingCodec {++ /** Phone -> HU: a thread-list snapshot. */+ fun encodeThreads(threads: List<MessagingThread>): Pair<Int, ByteArray> =+ GalMessage.Notification.THREADS to MessagingThreads.newBuilder()+ .addAllThreads(threads)+ .build()+ .toByteArray()++ /** Phone -> HU: one message body posted. */+ fun encodeMessage(message: MessagingMessage): Pair<Int, ByteArray> =+ GalMessage.Notification.MESSAGE to message.toByteArray()++ /** Phone -> HU: a thread dismissed on the phone or read elsewhere. */+ fun encodeDismiss(threadId: String, messageId: String? = null): Pair<Int, ByteArray> {+ val builder = MessagingDismiss.newBuilder().setThreadId(threadId)+ if (messageId != null) builder.messageId = messageId+ return GalMessage.Notification.DISMISS to builder.build().toByteArray()+ }++ /**+ * Parses a HU -> phone ACTION payload, throwing on malformed bytes like+ * every other generated parser here. Callers that must survive hostile+ * traffic use [decodeInbound] instead.+ */+ fun decodeAction(payload: ByteArray): MessagingAction =+ MessagingAction.parseFrom(payload)++ /**+ * Classifies one inbound ch14 message, or null when it is not a user+ * action we handle: a type other than ACTION, an uninitialized ACTION+ * (missing a required field), or an action type with no mapping. Null+ * means "observed and ignored", never an error -- the pump must survive+ * whatever a head unit sends.+ */+ fun decodeInbound(type: Int, payload: ByteArray): InboundMessagingAction? {+ if (type != GalMessage.Notification.ACTION) return null+ val action = runCatching { MessagingAction.parseFrom(payload) }.getOrNull()+ ?: return null+ if (!action.isInitialized) return null+ return when (action.action) {+ MessagingActionType.MESSAGE_REPLY -> InboundMessagingAction.Reply(+ threadId = action.threadId,+ text = action.replyText,+ )+ MessagingActionType.MESSAGE_MARK_READ -> InboundMessagingAction.MarkRead(+ threadId = action.threadId,+ )+ MessagingActionType.MESSAGE_VOICE_REPLY_BEGIN -> InboundMessagingAction.VoiceReplyBegin(+ threadId = action.threadId,+ )+ else -> null+ }+ }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ReconnectBackoff.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ReconnectBackoff.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ReconnectBackoff.ktnew file mode 100644index 0000000000..5a33f2d3dd--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/ReconnectBackoff.kt@@ -0,0 +1,51 @@+package com.vayunmathur.auto.protocol++/**+ * Reconnect backoff: full-jitter exponential delay between redials.+ *+ * Pure policy, no threads or clocks: the service loop calls [onFailure] when a session+ * ends abnormally and sleeps the returned delay, and [onSuccess] when a session+ * establishes (or ends cleanly) to reset the streak. Delay for consecutive failure `n`+ * is uniform in `[0, min(maxDelayMs, baseDelayMs * 2^n)]` โ full jitter, so a fleet of+ * phones hammering one head unit spreads out instead of marching in lockstep.+ *+ * @param jitter draws the actual delay within `[0, bound)`. Defaults to `Math.random`;+ * tests inject a fixed draw to assert exact caps.+ */+class ReconnectBackoff(+ private val baseDelayMs: Long = DEFAULT_BASE_DELAY_MS,+ private val maxDelayMs: Long = DEFAULT_MAX_DELAY_MS,+ private val jitter: (bound: Long) -> Long = { bound -> (Math.random() * bound).toLong() },+) {+ /** Consecutive failures since the last success. */+ var failures: Int = 0+ private set++ /**+ * Records a failed attempt and returns how long to wait before the next one.+ * Capped at [maxDelayMs]; the shift saturates so long streaks cannot overflow.+ */+ fun onFailure(): Long {+ val shift = failures.coerceAtMost(MAX_SHIFT)+ val cap = (baseDelayMs shl shift).coerceAtMost(maxDelayMs)+ failures+++ // Bound is exclusive and at least 1; a zero cap still yields a (zero) draw.+ return jitter(cap + 1).coerceIn(0, maxDelayMs)+ }++ /** Records a success: the next failure backs off from the base again. */+ fun onSuccess() {+ failures = 0+ }++ companion object {+ /** First retry waits up to half a second. */+ const val DEFAULT_BASE_DELAY_MS = 500L++ /** Retries never wait longer than half a minute. */+ const val DEFAULT_MAX_DELAY_MS = 30_000L++ /** `base << 20` already overflows any sane cap; saturate the shift here. */+ private const val MAX_SHIFT = 20+ }+}
auto/protocol/src/main/proto/gal/notification.proto
diff --git a/auto/protocol/src/main/proto/gal/notification.proto b/auto/protocol/src/main/proto/gal/notification.protonew file mode 100644index 0000000000..45d9bd088b--- /dev/null+++ b/auto/protocol/src/main/proto/gal/notification.proto@@ -0,0 +1,66 @@+// Google Automotive Link messaging channel (service 14, NOTIFICATION).+//+// MA sender-defined DTOs: the teardown recovered the service descriptor slot+// (`Service.notification`, field 13, `xjm`) but never the xjm channel message+// IDs, so there is nothing exact to pin here. These messages frame the+// Phase 7 set -- threads, body, reply, mark-read -- as proto2 channel payloads+// behind the 2-byte type prefix, exactly like every other service channel.+//+// This is a DHU-tolerated stub by construction: an unknown ch14 payload earns+// at worst a bare MessageError (0xff) on ch14 while video and the bring-up+// carry on. If the teardown ever recovers the real xjm IDs, they replace the+// MA-defined types in `GalMessage.Notification` and these DTOs get re-pinned+// against them.++syntax = "proto2";++package gal;++option java_package = "com.vayunmathur.auto.protocol.gal";+option java_multiple_files = true;++// One conversation. Phone -> head unit, inside THREADS.+message MessagingThread {+ required string thread_id = 1;+ optional string title = 2;+ optional string sender = 3;+ optional int64 last_message_ms = 4;+ optional uint32 unread_count = 5;+}++// A thread-list snapshot. Phone -> head unit (0x8001).+message MessagingThreads {+ repeated MessagingThread threads = 1;+}++// One message body posted. Phone -> head unit (0x8002).+message MessagingMessage {+ required string thread_id = 1;+ required string message_id = 2;+ optional string sender = 3;+ required string body = 4;+ optional int64 timestamp_ms = 5;+}++// A thread dismissed on the phone or read elsewhere.+// Phone -> head unit (0x8003).+message MessagingDismiss {+ required string thread_id = 1;+ optional string message_id = 2;+}++enum MessagingActionType {+ // The user typed a reply on the head unit; `reply_text` carries it.+ MESSAGE_REPLY = 1;+ // The user marked the thread read on the head unit.+ MESSAGE_MARK_READ = 2;+ // The user asked to reply by voice: open a ch6 mic turn for this thread.+ MESSAGE_VOICE_REPLY_BEGIN = 3;+}++// A user action on the head unit. HU -> phone (0x8004).+message MessagingAction {+ required string thread_id = 1;+ required MessagingActionType action = 2;+ optional string reply_text = 3;+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ChannelSendQueueTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ChannelSendQueueTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ChannelSendQueueTest.ktnew file mode 100644index 0000000000..82281018a4--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ChannelSendQueueTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.auto.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The send-queue contract the channel owners rely on: control always jumps the line,+ * service channels round-robin so a video flood cannot starve acks or key bindings,+ * and each channel stays FIFO.+ */+class ChannelSendQueueTest {++ private fun send(channelId: Int, byte: Byte = 0): QueuedSend =+ QueuedSend(channelId, byteArrayOf(byte), isControl = false, encrypted = true)++ @Test+ fun `control drains before video even when video queued first`() {+ val queue = ChannelSendQueue()+ queue.enqueue(send(GalService.VIDEO_SINK.id, 1))+ queue.enqueue(send(ChannelSendQueue.CONTROL_CHANNEL_ID, 2))++ assertEquals(2, queue.poll()!!.payload.single())+ assertEquals(1, queue.poll()!!.payload.single())+ assertNull(queue.poll())+ }++ @Test+ fun `service channels round-robin so acks never head-block behind video`() {+ val queue = ChannelSendQueue()+ repeat(5) { queue.enqueue(send(GalService.VIDEO_SINK.id, 10)) }+ queue.enqueue(send(GalService.AUDIO_SOURCE.id, 20))++ // Video first (it queued first), then the mic ack, then video again.+ assertEquals(10, queue.poll()!!.payload.single())+ assertEquals(20, queue.poll()!!.payload.single())+ assertEquals(10, queue.poll()!!.payload.single())+ }++ @Test+ fun `each channel stays FIFO`() {+ val queue = ChannelSendQueue()+ queue.enqueue(send(GalService.INPUT_SOURCE.id, 1))+ queue.enqueue(send(GalService.VIDEO_SINK.id, 9))+ queue.enqueue(send(GalService.INPUT_SOURCE.id, 2))++ // Round-robin: input(1), video(9), input(2) โ input's own order preserved.+ assertEquals(1, queue.poll()!!.payload.single())+ assertEquals(9, queue.poll()!!.payload.single())+ assertEquals(2, queue.poll()!!.payload.single())+ }++ @Test+ fun `a drained channel leaves the rotation and rejoins on enqueue`() {+ val queue = ChannelSendQueue()+ queue.enqueue(send(2, 1))+ queue.enqueue(send(8, 2))+ assertEquals(1, queue.poll()!!.payload.single())+ assertEquals(2, queue.poll()!!.payload.single())+ assertTrue(queue.isEmpty())++ queue.enqueue(send(8, 3))+ assertEquals(3, queue.poll()!!.payload.single())+ assertNull(queue.poll())+ }++ @Test+ fun `pending counts cover every channel`() {+ val queue = ChannelSendQueue()+ assertTrue(queue.isEmpty())+ assertEquals(0, queue.pendingCount())+ assertEquals(0, queue.pendingBytes())++ queue.enqueue(send(0, 1))+ queue.enqueue(QueuedSend(2, ByteArray(100), isControl = false, encrypted = true))++ assertFalse(queue.isEmpty())+ assertEquals(2, queue.pendingCount())+ assertEquals(101, queue.pendingBytes())+ }++ @Test+ fun `clear drops everything unsent for the next session`() {+ val queue = ChannelSendQueue()+ queue.enqueue(send(0))+ queue.enqueue(send(2))+ queue.enqueue(send(6))++ queue.clear()++ assertTrue(queue.isEmpty())+ assertNull(queue.poll())+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FocusArbitrationTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FocusArbitrationTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FocusArbitrationTest.ktnew file mode 100644index 0000000000..f220183c85--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FocusArbitrationTest.kt@@ -0,0 +1,166 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AudioFocusState+import com.vayunmathur.auto.protocol.gal.NavigationFocusType+import com.vayunmathur.auto.protocol.gal.VideoFocusIndication+import com.vayunmathur.auto.protocol.gal.VideoFocusMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The focus preemption matrix, host-tested: video modes gate streaming and input, audio+ * focus decides playback while video stays native, navigation tracks its own flag.+ */+class FocusArbitrationTest {++ @Test+ fun `starts parked with nothing allowed`() {+ val focus = FocusArbitration()++ assertEquals(VideoFocus.NONE, focus.videoFocus)+ assertFalse(focus.inputAllowed)+ assertFalse(focus.shouldStreamVideo)+ assertFalse(focus.mayPlayMedia)+ assertFalse(focus.navigationProjected)+ }++ @Test+ fun `projected focus streams and allows input`() {+ val focus = FocusArbitration()++ val change = focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)++ assertTrue(change.videoChanged)+ assertTrue(change.any)+ assertEquals(VideoFocus.PROJECTED, focus.videoFocus)+ assertTrue(focus.inputAllowed)+ assertTrue(focus.shouldStreamVideo)+ }++ @Test+ fun `projected without input focus still streams but blocks input`() {+ // gearhead derives input focus from video focus rather than negotiating it:+ // the stream keeps flowing while head-unit touches must be dropped.+ val focus = FocusArbitration()++ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED_NO_INPUT_FOCUS)++ assertEquals(VideoFocus.PROJECTED, focus.videoFocus)+ assertTrue(focus.shouldStreamVideo)+ assertFalse(focus.inputAllowed)+ }++ @Test+ fun `native and transient both park the stream`() {+ val focus = FocusArbitration()++ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_NATIVE)+ assertEquals(VideoFocus.NATIVE, focus.videoFocus)+ assertFalse(focus.shouldStreamVideo)+ assertFalse(focus.inputAllowed)++ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_NATIVE_TRANSIENT)+ assertEquals(VideoFocus.NATIVE, focus.videoFocus)+ assertFalse(focus.shouldStreamVideo)+ }++ @Test+ fun `unknown and absent modes never clobber known state`() {+ val focus = FocusArbitration()+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+ val generation = focus.generation++ // The lite runtime drops unknown enum values on parse, so a future mode+ // arrives as an absent one; the machine ignores it.+ assertEquals(FocusChange(), focus.onVideoFocus(null))++ assertEquals(VideoFocus.PROJECTED, focus.videoFocus)+ assertTrue(focus.inputAllowed)+ assertEquals(generation, focus.generation)+ }++ @Test+ fun `audio gain allows media while video stays native`() {+ // TTS over the car's own UI: video parked, speakers ours.+ val focus = FocusArbitration()+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_NATIVE)++ focus.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT)++ assertTrue(focus.mayPlayMedia)+ assertFalse(focus.shouldStreamVideo)+ }++ @Test+ fun `audio loss silences media without projected video`() {+ val focus = FocusArbitration()+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_NATIVE)+ focus.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_GAIN)++ val change = focus.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_LOSS)++ assertTrue(change.audioChanged)+ assertFalse(focus.mayPlayMedia)+ }++ @Test+ fun `projected video is the implicit grant when audio is silent`() {+ val focus = FocusArbitration()+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)++ assertTrue(focus.mayPlayMedia)+ }++ @Test+ fun `navigation focus tracks its own flag`() {+ val focus = FocusArbitration()++ val change = focus.onNavigationFocus(NavigationFocusType.NAV_FOCUS_PROJECTED)++ assertTrue(change.navigationChanged)+ assertTrue(focus.navigationProjected)++ focus.onNavigationFocus(NavigationFocusType.NAV_FOCUS_NATIVE)+ assertFalse(focus.navigationProjected)+ }++ @Test+ fun `duplicate notifications do not bump the generation`() {+ val focus = FocusArbitration()+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+ focus.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_GAIN)+ val generation = focus.generation++ assertEquals(FocusChange(), focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED))+ assertEquals(+ FocusChange(),+ focus.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_GAIN),+ )+ assertEquals(+ FocusChange(),+ focus.onNavigationFocus(NavigationFocusType.NAV_FOCUS_NATIVE),+ )++ assertEquals(generation, focus.generation)+ }++ @Test+ fun `reset clears everything for a reconnect`() {+ val focus = FocusArbitration()+ focus.onVideoFocus(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+ focus.onAudioFocus(AudioFocusState.AUDIO_FOCUS_STATE_GAIN)+ focus.onNavigationFocus(NavigationFocusType.NAV_FOCUS_PROJECTED)++ focus.reset()++ assertEquals(VideoFocus.NONE, focus.videoFocus)+ assertFalse(focus.inputAllowed)+ assertFalse(focus.shouldStreamVideo)+ assertFalse(focus.mayPlayMedia)+ assertFalse(focus.navigationProjected)+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionQueueTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionQueueTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionQueueTest.ktnew file mode 100644index 0000000000..91817a51e7--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionQueueTest.kt@@ -0,0 +1,110 @@+package com.vayunmathur.auto.protocol++import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The connection-level queue contract: sends from any thread go out control-first+ * under the single engine lock, so a video burst never head-blocks control traffic.+ *+ * Plaintext sends exercise the queue without a TLS handshake (encrypted service+ * sends need a handshook engine; see [GalConnectionTest]).+ */+class GalConnectionQueueTest {++ /** Captures everything the connection writes; reads as end of stream. */+ private class FakeTransport : GalTransport {+ val written = ByteArrayOutputStream()++ override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1++ override fun write(bytes: ByteArray, offset: Int, length: Int) {+ written.write(bytes, offset, length)+ }++ override fun flush() = Unit++ override fun close() = Unit+ }++ private fun channelOf(frame: ByteArray): Int = frame[0].toInt() and 0xFF++ /** Splits the written bytes into frames via their 4-byte headers. */+ private fun framesOf(written: ByteArray): List<ByteArray> {+ val frames = mutableListOf<ByteArray>()+ var offset = 0+ while (offset < written.size) {+ val header = FrameHeader.readFrom(ByteBuffer.wrap(written, offset, written.size - offset))+ val frame = written.copyOfRange(offset, offset + header.size + header.payloadLength)+ frames += frame+ offset += frame.size+ }+ return frames+ }++ @Test+ fun `a video burst queued first still loses the wire to control`() {+ val transport = FakeTransport()+ val connection = GalConnection(transport, TestTls.context(), deviceModel = "Pixel 8")++ // A video bulk send queued ahead of control traffic...+ connection.enqueue(+ OutboundMessage(+ type = GalMessage.Media.DATA_WITH_TIMESTAMP,+ payload = ByteArray(64),+ encrypted = false,+ channelId = GalService.VIDEO_SINK.id,+ ),+ )+ // ...then a control reply and a mic ack.+ connection.enqueue(+ OutboundMessage(+ type = GalMessage.Control.PING_RESPONSE,+ payload = byteArrayOf(0x08, 0x01),+ encrypted = false,+ ),+ )+ connection.enqueue(+ OutboundMessage(+ type = GalMessage.Media.ACK,+ payload = byteArrayOf(0x08, 0x00),+ encrypted = false,+ channelId = GalService.AUDIO_SOURCE.id,+ ),+ )+ assertEquals(3, connection.pendingSends())++ connection.flushSends()++ assertEquals(0, connection.pendingSends())+ val channels = framesOf(transport.written.toByteArray()).map(::channelOf)+ assertEquals(+ listOf(0, GalService.VIDEO_SINK.id, GalService.AUDIO_SOURCE.id),+ channels,+ "channel 0 first, then service channels in first-enqueue order",+ )+ }++ @Test+ fun `enqueue without flush holds sends for one ordered drain`() {+ val transport = FakeTransport()+ val connection = GalConnection(transport, TestTls.context(), deviceModel = "Pixel 8")++ connection.enqueue(+ OutboundMessage(+ type = GalMessage.Control.PING_RESPONSE,+ payload = byteArrayOf(0x08, 0x01),+ encrypted = false,+ ),+ )+ assertEquals(1, connection.pendingSends())+ assertEquals(0, transport.written.size(), "nothing goes out before the flush")++ connection.flushSends()+ assertEquals(0, connection.pendingSends())+ assertTrue(transport.written.size() > 0)+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionFocusTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionFocusTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionFocusTest.ktnew file mode 100644index 0000000000..ac04c09500--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionFocusTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AudioFocusNotification+import com.vayunmathur.auto.protocol.gal.AudioFocusRequestMessage+import com.vayunmathur.auto.protocol.gal.AudioFocusRequestType+import com.vayunmathur.auto.protocol.gal.AudioFocusState+import com.vayunmathur.auto.protocol.gal.NavigationFocusNotification+import com.vayunmathur.auto.protocol.gal.NavigationFocusType+import com.vayunmathur.auto.protocol.gal.VideoFocusIndication+import com.vayunmathur.auto.protocol.gal.VideoFocusMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The session half of focus arbitration: control notifications feed the state with no+ * reply on the wire, the video indication arrives via the sink, and the audio request+ * builder gives the audio sinks their control 0x18.+ */+class GalControlSessionFocusTest {++ private fun session(): GalControlSession = GalControlSession(+ GalCredential.serverEngine(TestTls.context()),+ deviceModel = "Pixel 8",+ deviceManufacturer = "Google",+ )++ @Test+ fun `audio focus notification feeds arbitration with no reply`() {+ val session = session()+ val generation = session.focus.generation++ val replies = session.onMessage(+ GalMessage.Control.AUDIO_FOCUS_NOTIFICATION,+ AudioFocusNotification.newBuilder()+ .setState(AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT)+ .build()+ .toByteArray(),+ )++ assertTrue(replies.isEmpty(), "notifications are observed, never answered")+ assertEquals(+ AudioFocusState.AUDIO_FOCUS_STATE_GAIN_TRANSIENT,+ session.focus.audioFocus,+ )+ assertTrue(session.focus.mayPlayMedia)+ assertTrue(session.focus.generation > generation)+ }++ @Test+ fun `navigation focus notification tracks projection`() {+ val session = session()++ session.onMessage(+ GalMessage.Control.NAVIGATION_FOCUS_NOTIFICATION,+ NavigationFocusNotification.newBuilder()+ .setFocus(NavigationFocusType.NAV_FOCUS_PROJECTED)+ .build()+ .toByteArray(),+ )++ assertTrue(session.focus.navigationProjected)+ }++ @Test+ fun `video focus indication gates the stream`() {+ val session = session()++ session.onVideoFocusIndication(+ VideoFocusIndication.newBuilder().setMode(VideoFocusMode.VIDEO_FOCUS_PROJECTED).build(),+ )+ assertTrue(session.focus.shouldStreamVideo)+ assertTrue(session.focus.inputAllowed)++ session.onVideoFocusIndication(+ VideoFocusIndication.newBuilder().setMode(VideoFocusMode.VIDEO_FOCUS_NATIVE).build(),+ )+ assertEquals(VideoFocus.NATIVE, session.focus.videoFocus)+ assertFalse(session.focus.shouldStreamVideo)+ }++ @Test+ fun `audio focus request builds an encrypted control 18`() {+ val out = session().requestAudioFocus(AudioFocusRequestType.AUDIO_FOCUS_GAIN_TRANSIENT)++ assertEquals(GalMessage.Control.AUDIO_FOCUS_REQUEST, out.type)+ assertTrue(out.encrypted)+ assertEquals(+ AudioFocusRequestType.AUDIO_FOCUS_GAIN_TRANSIENT,+ AudioFocusRequestMessage.parseFrom(out.payload).request,+ )+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessagingCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessagingCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessagingCodecTest.ktnew file mode 100644index 0000000000..86a2b655c1--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessagingCodecTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.MessagingAction+import com.vayunmathur.auto.protocol.gal.MessagingActionType+import com.vayunmathur.auto.protocol.gal.MessagingMessage+import com.vayunmathur.auto.protocol.gal.MessagingThread+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the ch14 (NOTIFICATION, service 14) message set: threads, body, reply, mark-read.+ *+ * Byte-exact where the field layout is ours to define (MA sender-defined DTOs in+ * `gal/notification.proto`): a renumbered field here only breaks us against+ * ourselves, but the exact-bytes form still catches an accidental proto edit+ * the same day it lands, not at a DHU that silently ignores us.+ */+class MessagingCodecTest {++ @Test+ fun `threads encode under the THREADS type`() {+ val thread = MessagingThread.newBuilder()+ .setThreadId("t1")+ .setTitle("Ada")+ .setSender("+15551234567")+ .setLastMessageMs(1_700_000_000_000L)+ .setUnreadCount(2)+ .build()+ val (type, payload) = MessagingCodec.encodeThreads(listOf(thread))+ assertEquals(GalMessage.Notification.THREADS, type)++ val decoded = MessageCodec.decode(GalService.NOTIFICATION.id, MessageCodec.encode(type, payload))+ assertEquals(GalMessage.Notification.THREADS, decoded.type)+ val parsed = com.vayunmathur.auto.protocol.gal.MessagingThreads.parseFrom(decoded.payload)+ assertEquals(1, parsed.threadsCount)+ assertEquals("t1", parsed.getThreads(0).threadId)+ assertEquals("Ada", parsed.getThreads(0).title)+ assertEquals(2, parsed.getThreads(0).unreadCount)+ }++ @Test+ fun `a message body pins field numbers on the wire`() {+ val message = MessagingMessage.newBuilder()+ .setThreadId("t1")+ .setMessageId("m7")+ .setSender("Ada")+ .setBody("On my way")+ .setTimestampMs(42L)+ .build()+ val (type, payload) = MessagingCodec.encodeMessage(message)+ assertEquals(GalMessage.Notification.MESSAGE, type)+ assertContentEquals(+ byteArrayOf(+ 0x0A, 0x02, 0x74, 0x31, // field 1, thread_id "t1"+ 0x12, 0x02, 0x6D, 0x37, // field 2, message_id "m7"+ 0x1A, 0x03, 0x41, 0x64, 0x61, // field 3, sender "Ada"+ 0x22, 0x09, 0x4F, 0x6E, 0x20, 0x6D, 0x79, 0x20, 0x77, 0x61, 0x79, // field 4+ 0x28, 0x2A, // field 5, varint 42+ ),+ payload,+ )+ }++ @Test+ fun `a dismiss carries thread and optional message ids`() {+ val (type, withMessage) = MessagingCodec.encodeDismiss("t1", "m7")+ assertEquals(GalMessage.Notification.DISMISS, type)+ val parsed = com.vayunmathur.auto.protocol.gal.MessagingDismiss.parseFrom(withMessage)+ assertEquals("t1", parsed.threadId)+ assertEquals("m7", parsed.messageId)++ val (_, bare) = MessagingCodec.encodeDismiss("t1")+ assertTrue(!com.vayunmathur.auto.protocol.gal.MessagingDismiss.parseFrom(bare).hasMessageId())+ }++ @Test+ fun `a typed reply classifies with its text`() {+ val payload = MessagingAction.newBuilder()+ .setThreadId("t1")+ .setAction(MessagingActionType.MESSAGE_REPLY)+ .setReplyText("Sounds good")+ .build()+ .toByteArray()+ val inbound = MessagingCodec.decodeInbound(GalMessage.Notification.ACTION, payload)+ assertEquals(InboundMessagingAction.Reply("t1", "Sounds good"), inbound)+ }++ @Test+ fun `a mark-read classifies without text`() {+ val payload = MessagingAction.newBuilder()+ .setThreadId("t1")+ .setAction(MessagingActionType.MESSAGE_MARK_READ)+ .build()+ .toByteArray()+ assertEquals(+ InboundMessagingAction.MarkRead("t1"),+ MessagingCodec.decodeInbound(GalMessage.Notification.ACTION, payload),+ )+ }++ @Test+ fun `a voice-reply request maps to a mic turn`() {+ val payload = MessagingAction.newBuilder()+ .setThreadId("t1")+ .setAction(MessagingActionType.MESSAGE_VOICE_REPLY_BEGIN)+ .build()+ .toByteArray()+ assertEquals(+ InboundMessagingAction.VoiceReplyBegin("t1"),+ MessagingCodec.decodeInbound(GalMessage.Notification.ACTION, payload),+ )+ }++ @Test+ fun `garbage on ch14 is observed, never fatal`() {+ // Wrong type, truncated ACTION, and an uninitialized ACTION all decode+ // to null: the pump logs them and carries on.+ assertNull(MessagingCodec.decodeInbound(GalMessage.Notification.MESSAGE, byteArrayOf(1, 2, 3)))+ assertNull(MessagingCodec.decodeInbound(GalMessage.Notification.ACTION, byteArrayOf(0x08)))+ assertNull(+ MessagingCodec.decodeInbound(+ GalMessage.Notification.ACTION,+ // buildPartial: a full build() would throw at the call site for+ // the missing required `action`, never reaching the codec.+ MessagingAction.newBuilder().setThreadId("t1").buildPartial().toByteArray(),+ ),+ )+ }++ @Test+ fun `ch14 types are distinct from media and sensor ids`() {+ val ids = setOf(+ GalMessage.Notification.THREADS,+ GalMessage.Notification.MESSAGE,+ GalMessage.Notification.DISMISS,+ GalMessage.Notification.ACTION,+ )+ assertEquals(4, ids.size)+ assertTrue(ids.all { it in 0x8000..0xFFFF })+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ReconnectBackoffTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ReconnectBackoffTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ReconnectBackoffTest.ktnew file mode 100644index 0000000000..88cbbee258--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/ReconnectBackoffTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.auto.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The reconnect policy: exponential growth from the base, a hard cap, and a reset on+ * success. Jitter is injected so the caps assert exactly.+ */+class ReconnectBackoffTest {++ /** Always draws the maximum, so each delay equals its cap. */+ private fun maxBackoff() = ReconnectBackoff(jitter = { bound -> bound - 1 })++ @Test+ fun `first failure waits the base delay`() {+ assertEquals(500, maxBackoff().onFailure())+ }++ @Test+ fun `delays double until the cap`() {+ val backoff = maxBackoff()++ assertEquals(500, backoff.onFailure())+ assertEquals(1_000, backoff.onFailure())+ assertEquals(2_000, backoff.onFailure())+ assertEquals(4_000, backoff.onFailure())+ assertEquals(8_000, backoff.onFailure())+ assertEquals(16_000, backoff.onFailure())+ assertEquals(30_000, backoff.onFailure())+ assertEquals(30_000, backoff.onFailure())+ }++ @Test+ fun `long streaks saturate at the cap without overflowing`() {+ val backoff = maxBackoff()+ repeat(100) { backoff.onFailure() }++ assertEquals(30_000, backoff.onFailure())+ assertEquals(101, backoff.failures)+ }++ @Test+ fun `success resets the streak to the base`() {+ val backoff = maxBackoff()+ backoff.onFailure()+ backoff.onFailure()++ backoff.onSuccess()++ assertEquals(0, backoff.failures)+ assertEquals(500, backoff.onFailure())+ }++ @Test+ fun `delays stay inside zero and the cap whatever the draw`() {+ val minBackoff = ReconnectBackoff(jitter = { 0 })+ repeat(10) {+ assertEquals(0, minBackoff.onFailure())+ }++ val custom = ReconnectBackoff(+ baseDelayMs = 100,+ maxDelayMs = 250,+ jitter = { bound -> bound - 1 },+ )+ assertEquals(100, custom.onFailure())+ assertEquals(200, custom.onFailure())+ assertEquals(250, custom.onFailure())+ assertTrue(custom.onFailure() <= 250)+ }+}
auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorBus.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorBus.kt b/auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorBus.ktnew file mode 100644index 0000000000..9b42a05d9e--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorBus.kt@@ -0,0 +1,33 @@+package com.vayunmathur.auto.notifications++import com.vayunmathur.auto.protocol.gal.MessagingMessage+import com.vayunmathur.auto.protocol.gal.MessagingThread+import java.util.concurrent.CopyOnWriteArraySet++/**+ * Process-wide bus between the notification listener and the projection session.+ *+ * `MessageMirrorService` lives and dies with the system's listener binding,+ * while the ch14 owner lives with the GAL session; neither may hold the other.+ * The service posts snapshots here, and `ProjectionService` registers one+ * listener per session and unregisters it when the head unit goes away.+ * Thread-safe: posts arrive on the listener binder thread, sends leave on the+ * projection worker thread.+ */+object MessageMirrorBus {+ fun interface Listener {+ fun onMirror(thread: MessagingThread, message: MessagingMessage)+ }++ private val listeners = CopyOnWriteArraySet<Listener>()++ /** Registers [listener]; closing the return unregisters it. */+ fun register(listener: Listener): AutoCloseable {+ listeners += listener+ return AutoCloseable { listeners -= listener }+ }++ fun post(thread: MessagingThread, message: MessagingMessage) {+ for (listener in listeners) listener.onMirror(thread, message)+ }+}
auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorService.kt b/auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorService.ktnew file mode 100644index 0000000000..7ec8c9f5eb--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/notifications/MessageMirrorService.kt@@ -0,0 +1,94 @@+package com.vayunmathur.auto.notifications++import android.app.Notification+import android.service.notification.NotificationListenerService+import android.service.notification.StatusBarNotification+import android.util.Log+import androidx.core.app.NotificationCompat+import com.vayunmathur.auto.platform.MessagingPrefs+import com.vayunmathur.auto.protocol.gal.MessagingMessage+import com.vayunmathur.auto.protocol.gal.MessagingThread++/**+ * Mirrors phone message notifications onto the projection session's ch14 owner.+ *+ * Posts only `CATEGORY_MESSAGE` notifications (SMS and chat apps tag theirs;+ * everything else is skipped) that carry non-blank text, and only while the+ * user has both granted the system listener binding and flipped the in-app+ * consent switch: either gate off means fail-closed silence, never a send.+ * The system binds this service itself once the user enables MA Auto in the+ * notification-access settings; there is nothing to start or stop.+ */+class MessageMirrorService : NotificationListenerService() {++ override fun onNotificationPosted(sbn: StatusBarNotification) {+ if (!MessagingPrefs.isMirroringConsented(this)) return+ val notification = sbn.notification+ if (notification.category != Notification.CATEGORY_MESSAGE) return+ val (thread, message) = extract(sbn) ?: return+ MessageMirrorBus.post(thread, message)+ Log.d(TAG, "mirrored message for thread ${thread.threadId}")+ }++ override fun onNotificationRemoved(sbn: StatusBarNotification) {+ // Dismissals on the phone side stay local: without a per-thread read+ // store there is nothing truthful to tell the head unit.+ }++ /**+ * Pulls a ch14 snapshot out of a message notification, or null when it+ * carries nothing worth sending: no `MessagingStyle`, or a style with no+ * messages, or a latest message with blank text.+ */+ internal fun extract(sbn: StatusBarNotification): Pair<MessagingThread, MessagingMessage>? {+ val extras = NotificationCompat.getExtras(sbn.notification) ?: return null+ val messages = NotificationCompat.MessagingStyle.extractMessagingStyleFromNotificationExtras(extras)+ ?.messages+ ?.takeIf { it.isNotEmpty() }+ ?: return null+ val latest = messages.lastOrNull { !it.text.isNullOrBlank() } ?: return null+ val threadId = conversationKey(sbn)+ val thread = MessagingThread.newBuilder()+ .setThreadId(threadId)+ .setTitle(conversationTitle(sbn, latest))+ .setSender(latest.person?.name?.toString().orEmpty())+ .setLastMessageMs(latest.timestamp)+ .build()+ val message = MessagingMessage.newBuilder()+ .setThreadId(threadId)+ .setMessageId(messageKey(sbn, latest.timestamp))+ .setSender(latest.person?.name?.toString().orEmpty())+ .setBody(latest.text.toString())+ .setTimestampMs(latest.timestamp)+ .build()+ return thread to message+ }++ /**+ * Stable per-conversation key: the notification's conversation id when the+ * app shortcuts one (people-tagged messages), else the posting package plus+ * tag plus id. Stable across reposts of the same thread, distinct across+ * apps and threads -- which is what ch14 groups by.+ */+ internal fun conversationKey(sbn: StatusBarNotification): String {+ val shortcut = sbn.notification.shortcutId+ if (!shortcut.isNullOrEmpty()) return "${sbn.packageName}:$shortcut"+ return "${sbn.packageName}:${sbn.tag}:${sbn.id}"+ }++ private fun conversationTitle(sbn: StatusBarNotification, latest: NotificationCompat.MessagingStyle.Message): String {+ val styleTitle = NotificationCompat.getExtras(sbn.notification)+ ?.let { NotificationCompat.MessagingStyle.extractMessagingStyleFromNotificationExtras(it)?.conversationTitle }+ if (!styleTitle.isNullOrBlank()) return styleTitle.toString()+ val sender = latest.person?.name?.toString()+ if (!sender.isNullOrBlank()) return sender+ return sbn.packageName+ }++ private fun messageKey(sbn: StatusBarNotification, timestamp: Long): String =+ "${sbn.id}:$timestamp"++ private companion object {+ const val TAG = "MaAuto.MsgMirror"+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/Messaging.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/Messaging.kt b/auto/src/main/java/com/vayunmathur/auto/platform/Messaging.ktnew file mode 100644index 0000000000..484e3bdb9b--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/Messaging.kt@@ -0,0 +1,26 @@+package com.vayunmathur.auto.platform++/**+ * Something the messaging channel observed, forwarded to [AutoSessionState] for the phone UI.+ *+ * Streaming never waits on these: they are fire-and-forget observations, mirroring+ * [VideoEvent] and [MediaEvent].+ */+sealed interface MessagingEvent {+ /** A thread-list snapshot went out on ch14; [count] is threads in it. */+ data class ThreadsPosted(val count: Int) : MessagingEvent++ /** One message body went out on ch14 for [threadId]. */+ data class MessagePosted(val threadId: String) : MessagingEvent++ /** The head unit answered with reply text for [threadId]. */+ data class ReplyReceived(val threadId: String) : MessagingEvent++ /**+ * The head unit marked [threadId] read. Observed only: the phone keeps no+ * per-thread read state yet, so there is nothing to update. Kept as an+ * event (rather than dropped in the channel) so a future car card can+ * render it without re-plumbing the channel.+ */+ data class MarkedRead(val threadId: String) : MessagingEvent+}
auto/src/main/java/com/vayunmathur/auto/platform/MessagingAudio.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MessagingAudio.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MessagingAudio.ktnew file mode 100644index 0000000000..1f3211bfcb--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MessagingAudio.kt@@ -0,0 +1,36 @@+package com.vayunmathur.auto.platform++/**+ * The audio half of messaging, owned by audio-dev's Phase 3 channels.+ *+ * Notify/TTS rides the guidance/system sink (ch4) and a voice reply opens a+ * mic turn on the source channel (ch6). Those owners have not landed yet, so+ * `MessagingCarAppService` codes against this seam and ships with [NoOp]:+ * sends are counted and observed, audio is silently skipped.+ *+ * Assumptions (noted for the audio-dev handoff, sent via the ma-auto-parity+ * channel rather than waited on):+ * 1. TTS/notification audio goes out a ch4 sink; [speakOnCar] hands text to+ * whichever sink audio-dev designates.+ * 2. A voice reply is one ch6 mic turn for [beginVoiceReply]'s thread; the+ * transcription comes back as text on [onResult], which the caller treats+ * exactly like a typed head-unit reply.+ */+interface MessagingAudio {+ /** Reads [text] aloud on the car speakers. Fire-and-forget. */+ fun speakOnCar(text: String)++ /**+ * Opens a mic turn for a reply to [threadId]. [onResult] receives the+ * transcription and may be invoked from any thread; sinks must be+ * thread-safe (a `StateFlow` set, a queued send) rather than doing work+ * inline. Never invoked when the turn yields nothing.+ */+ fun beginVoiceReply(threadId: String, onResult: (String) -> Unit)++ /** Pre-audio-dev holder: observes the call shape, moves no audio. */+ object NoOp : MessagingAudio {+ override fun speakOnCar(text: String) = Unit+ override fun beginVoiceReply(threadId: String, onResult: (String) -> Unit) = Unit+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/MessagingPrefs.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MessagingPrefs.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MessagingPrefs.ktnew file mode 100644index 0000000000..1c414bd65b--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MessagingPrefs.kt@@ -0,0 +1,26 @@+package com.vayunmathur.auto.platform++import android.content.Context++/**+ * Persists the messaging-mirror consent switch.+ *+ * Consent is device-level, not session-level: it survives disconnects and+ * service restarts, and both the notification listener (which decides whether+ * to post at all) and the ch14 owner (which decides whether to send) read it+ * as the source of truth. Defaults to false -- mirroring is fail-closed.+ */+object MessagingPrefs {+ fun isMirroringConsented(context: Context): Boolean =+ prefs(context).getBoolean(KEY_CONSENT, false)++ fun setMirroringConsented(context: Context, consented: Boolean) {+ prefs(context).edit().putBoolean(KEY_CONSENT, consented).apply()+ }++ private fun prefs(context: Context) =+ context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)++ private const val FILE = "ma_auto_messaging"+ private const val KEY_CONSENT = "mirroring_consented"+}
auto/src/main/java/com/vayunmathur/auto/service/MessagingCarAppService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/MessagingCarAppService.kt b/auto/src/main/java/com/vayunmathur/auto/service/MessagingCarAppService.ktnew file mode 100644index 0000000000..5064b1a95e--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/service/MessagingCarAppService.kt@@ -0,0 +1,96 @@+package com.vayunmathur.auto.service++import android.util.Log+import com.vayunmathur.auto.notifications.MessageMirrorBus+import com.vayunmathur.auto.platform.MessagingAudio+import com.vayunmathur.auto.platform.MessagingEvent+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.InboundMessagingAction+import com.vayunmathur.auto.protocol.MessagingCodec+import com.vayunmathur.auto.protocol.gal.MessagingMessage+import com.vayunmathur.auto.protocol.gal.MessagingThread++/**+ * The messaging channel: mirrors phone threads onto ch14 and routes head-unit replies back.+ *+ * Bring-up needs nothing: ch14 opens in the generic wire-order pass like every other+ * service, and an unknown payload earns at worst a bare MessageError on ch14 while+ * video carries on. Posting starts on [onChannelOpen], never before -- sending on a+ * channel the head unit has not granted earns a 0xff.+ *+ * Notify/TTS goes out through [audio] (audio-dev's ch4 sink when it lands; silent+ * until then), and a voice-reply turn opens a ch6 mic turn whose transcription+ * returns as text and is treated exactly like a typed reply. Replies leave the+ * phone through [onReply]: this service knows GAL, not SMS -- sending is the+ * message app's job (direct reply via the notification, or the default-SMS path),+ * and the callback is where that lands.+ */+class MessagingCarAppService(+ private val connection: GalConnection,+ private val audio: MessagingAudio = MessagingAudio.NoOp,+ private val onEvent: (MessagingEvent) -> Unit = {},+ private val onReply: (threadId: String, text: String) -> Unit = { _, _ -> },+) {+ val channelId: Int get() = GalService.NOTIFICATION.id++ private var open = false+ private var mirror: AutoCloseable? = null+ private val threads = LinkedHashMap<String, MessagingThread>()++ /** The channel grant arrived; start mirroring the phone side. */+ fun onChannelOpen() {+ open = true+ Log.i(TAG, "messaging channel open; mirroring message threads")+ mirror = MessageMirrorBus.register { thread, message -> onPhoneMessage(thread, message) }+ }++ /** One message for this channel; anything else is ignored, never misparsed. */+ fun onMessage(channelId: Int, type: Int, payload: ByteArray) {+ if (channelId != this.channelId) {+ Log.w(TAG, "ignoring 0x${type.toString(16)} for channel $channelId")+ return+ }+ // Only ACTION arrives here; anything else (a head unit echoing our own+ // posts, a future extension) is observed and ignored.+ val action = MessagingCodec.decodeInbound(type, payload)+ if (action == null) {+ Log.d(TAG, "unhandled messaging message 0x${type.toString(16)}")+ return+ }+ when (action) {+ is InboundMessagingAction.Reply -> {+ onEvent(MessagingEvent.ReplyReceived(action.threadId))+ onReply(action.threadId, action.text)+ }+ is InboundMessagingAction.MarkRead -> onEvent(MessagingEvent.MarkedRead(action.threadId))+ is InboundMessagingAction.VoiceReplyBegin -> audio.beginVoiceReply(action.threadId) { text ->+ onEvent(MessagingEvent.ReplyReceived(action.threadId))+ onReply(action.threadId, text)+ }+ }+ }++ /** A phone notification arrived: snapshot the threads, post the body, read it aloud. */+ private fun onPhoneMessage(thread: MessagingThread, message: MessagingMessage) {+ if (!open) return+ threads[thread.threadId] = thread+ val (threadsType, threadsPayload) = MessagingCodec.encodeThreads(threads.values.toList())+ connection.send(channelId, threadsType, threadsPayload)+ onEvent(MessagingEvent.ThreadsPosted(threads.size))+ val (messageType, messagePayload) = MessagingCodec.encodeMessage(message)+ connection.send(channelId, messageType, messagePayload)+ onEvent(MessagingEvent.MessagePosted(thread.threadId))+ audio.speakOnCar(message.body)+ }++ fun release() {+ runCatching { mirror?.close() }+ mirror = null+ open = false+ }++ private companion object {+ const val TAG = "MaAuto.Messaging"+ }+}
auto/src/main/java/com/vayunmathur/auto/ui/MessagingConsentCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/MessagingConsentCard.kt b/auto/src/main/java/com/vayunmathur/auto/ui/MessagingConsentCard.ktnew file mode 100644index 0000000000..0c6ed32130--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/MessagingConsentCard.kt@@ -0,0 +1,89 @@+package com.vayunmathur.auto.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.MessagingPrefs+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.SpecialAccess+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberMessenger++/**+ * Gates message mirroring on two switches: the in-app consent and the system+ * notification-listener binding. Both must be on before a notification reaches+ * the car; either off means fail-closed silence. Navigation failures report on+ * the shared snackbar host -- never a Toast.+ */+@Composable+fun MessagingConsentCard(modifier: Modifier = Modifier) {+ val context = LocalContext.current+ val messenger = rememberMessenger()+ var listenerGranted by remember { mutableStateOf(SpecialAccess.hasNotificationListener(context)) }+ var consented by remember { mutableStateOf(MessagingPrefs.isMirroringConsented(context)) }+ Card(modifier.fillMaxWidth()) {+ Column(Modifier.padding(vertical = 8.dp)) {+ SettingsSection(title = stringResource(R.string.messaging_headline)) {+ Text(+ text = stringResource(R.string.messaging_body),+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),+ )+ SettingsSwitchRow(+ title = stringResource(R.string.messaging_consent),+ checked = consented,+ onCheckedChange = {+ consented = it+ MessagingPrefs.setMirroringConsented(context, it)+ // Re-read the system gate: the user may have revoked it+ // in settings since this screen was composed.+ listenerGranted = SpecialAccess.hasNotificationListener(context)+ },+ supportingText = stringResource(+ if (consented) R.string.messaging_consent_on+ else R.string.messaging_consent_off,+ ),+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.messaging_listener)) },+ supportingContent = {+ Text(+ stringResource(+ if (listenerGranted) R.string.messaging_listener_granted+ else R.string.messaging_listener_missing,+ ),+ )+ },+ trailingContent = {+ Button(onClick = {+ runCatching {+ SpecialAccess.requestNotificationListener(context)+ }.onFailure {+ messenger.show(+ context.getString(R.string.messaging_listener_missing),+ )+ }+ }) {+ Text(stringResource(R.string.messaging_open_settings))+ }+ },+ )+ }+ }+ }+}