maauto: sensor/guidance/nav-status stubs + codecs, tests
- Commit
e21897b25346b4ff7ab5f01bdc51d6b459cdd3be- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 22:04 UTC (2 months ago)
- Parents
1c0f358
Diff
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/NavStatusCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/NavStatusCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/NavStatusCodec.ktnew file mode 100644index 0000000000..535eeb943e--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/NavStatusCodec.kt@@ -0,0 +1,57 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.NavigationStatus++/**+ * Pure navigation-status channel (service 10) codecs.+ *+ * Android-free like everything else in this module, so the status encoding+ * is host-testable. The channel is phone -> head unit simplex: the phone+ * posts turn guidance for the cluster and display, and the head unit sends+ * nothing normative back -- inbound ch10 traffic is observed and ignored.+ *+ * MA sender-defined throughout: the teardown recovered the service+ * descriptor slot but never the channel message IDs, so STATUS (0x8001)+ * mirrors the aasdk/openauto phone-to-HU status. A head unit that does not+ * speak it answers with a bare MessageError (0xff) on ch10, which is+ * observed and non-fatal. Sends go out with+ * `GalConnection.send(channelId, type, payload)` -- always encrypted, never+ * CONTROL-flagged, like all service-channel traffic.+ *+ * Stub phase (Phase 5): one well-formed inactive post on the grant, then+ * quiet. Live turn updates land with Phase 6 maps-dev through [encodeStatus].+ */+object NavStatusCodec {++ /**+ * Phone -> HU: "no guidance". States the inactive state explicitly+ * (`guidance_active` false, 08 00 on the wire) rather than posting an+ * empty payload the head unit must interpret.+ */+ fun encodeInactive(): Pair<Int, ByteArray> =+ GalMessage.NavigationStatus.STATUS to NavigationStatus.newBuilder()+ .setGuidanceActive(false)+ .build()+ .toByteArray()++ /**+ * Phone -> HU: live turn guidance. Absent fields stay absent -- a post+ * with only [guidanceActive] set is a bare active/inactive flip, which is+ * all the stub ever needs beyond [encodeInactive].+ *+ * Maps seam (Phase 6, maps-dev): next road, distance metres and maneuver+ * token per turn, reposted as the route advances.+ */+ fun encodeStatus(+ guidanceActive: Boolean,+ nextRoad: String? = null,+ nextTurnDistanceM: Int? = null,+ maneuver: String? = null,+ ): Pair<Int, ByteArray> {+ val builder = NavigationStatus.newBuilder().setGuidanceActive(guidanceActive)+ if (nextRoad != null) builder.nextRoad = nextRoad+ if (nextTurnDistanceM != null) builder.nextTurnDistanceM = nextTurnDistanceM+ if (maneuver != null) builder.maneuver = maneuver+ return GalMessage.NavigationStatus.STATUS to builder.build().toByteArray()+ }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.ktnew file mode 100644index 0000000000..d96383b521--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.kt@@ -0,0 +1,241 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.DrivingStatusReading+import com.vayunmathur.auto.protocol.gal.LocationReading+import com.vayunmathur.auto.protocol.gal.NightReading+import com.vayunmathur.auto.protocol.gal.SensorBatch+import com.vayunmathur.auto.protocol.gal.SensorError+import com.vayunmathur.auto.protocol.gal.SensorEvent+import com.vayunmathur.auto.protocol.gal.SensorRequest+import com.vayunmathur.auto.protocol.gal.SensorResponse+import com.vayunmathur.auto.protocol.gal.SensorType+import com.vayunmathur.auto.protocol.gal.SpeedReading++/** Last-known location fix from a LOCATION batch event, or null before the first one. */+data class LocationFix(+ val latitudeE7: Long,+ val longitudeE7: Long,+ val accuracyM: Int?,+ val timestampMs: Long?,+)++/**+ * The phone-side sensor picture: last-known value per stub type.+ *+ * Stub defaults (Phase 5): parked until a DRIVING_STATUS event says otherwise,+ * standing still until a SPEED event arrives, night unknown (the owner follows+ * the phone's own night state -- see SensorChannel), location unknown until+ * the first LOCATION batch. An event that carries no payload changes nothing:+ * the owner keeps its last-known rather than clobbering it with a default.+ *+ * Maps seam (Phase 6, maps-dev): feed live batches through [withEvents] --+ * phone GPS into LOCATION, fused speed into SPEED -- and read the snapshot+ * for the car UI. Nothing here needs to change shape, only the source of+ * the events.+ */+data class SensorSnapshot(+ val parked: Boolean = true,+ val isNight: Boolean? = null,+ val location: LocationFix? = null,+ val speedMps: Double = 0.0,+) {+ /**+ * Folds one batch's events into a new snapshot. Payload-less events are+ * skipped; unknown sensor types never reach here (the codec drops them).+ */+ fun withEvents(events: List<SensorEvent>): SensorSnapshot {+ var next = this+ for (event in events) {+ next = when (event.sensorType) {+ SensorType.LOCATION -> if (event.hasLocation()) {+ val fix = event.location+ next.copy(+ location = LocationFix(+ latitudeE7 = fix.latitudeE7,+ longitudeE7 = fix.longitudeE7,+ accuracyM = if (fix.hasAccuracyM()) fix.accuracyM else null,+ timestampMs = if (fix.hasTimestampMs()) fix.timestampMs else null,+ ),+ )+ } else {+ next+ }+ SensorType.SPEED -> if (event.hasSpeed() && event.speed.hasSpeedMps()) {+ next.copy(speedMps = event.speed.speedMps)+ } else {+ next+ }+ SensorType.NIGHT_MODE -> if (event.hasNight() && event.night.hasIsNight()) {+ next.copy(isNight = event.night.isNight)+ } else {+ next+ }+ SensorType.DRIVING_STATUS_DATA -> if (event.hasDrivingStatus() &&+ event.drivingStatus.hasParked()+ ) {+ next.copy(parked = event.drivingStatus.parked)+ } else {+ next+ }+ else -> next+ }+ }+ return next+ }+}++/** A classified inbound ch7 message. Anything else on the channel is [Observed]. */+sealed interface InboundSensor {+ /** The head unit answered a subscription (0x8002); [status] 0 means subscribed. */+ data class Subscribed(val type: SensorType, val status: Int) : InboundSensor++ /** Streamed readings (0x8003); empty when the batch carried no events. */+ data class Readings(val events: List<SensorEvent>) : InboundSensor++ /**+ * A subscription or stream failure (0x8004).+ *+ * NOTE the alias: 0x8004 is MediaAck on media channels and the messaging+ * ACTION on ch14, so this only ever means SensorError on ch7. Owners must+ * scope by channel id -- the 0x04 CONTROL frame flag never enters routing.+ */+ data class Error(val type: SensorType, val status: Int) : InboundSensor++ /** Malformed bytes, a future extension, anything unclassified. Observed, never fatal. */+ data class Observed(val type: Int) : InboundSensor+}++/**+ * Pure sensor-channel (SENSOR_SOURCE, service 7) codecs.+ *+ * Android-free like everything else in this module, so subscribing, batch+ * decoding and the last-known fold are all host-testable. The car owns the+ * sensors: the phone SENDS [GalMessage.Sensor.SENSOR_REQUEST] to subscribe+ * and RECEIVES [GalMessage.Sensor.SENSOR_RESPONSE], [GalMessage.Sensor.SENSOR_BATCH]+ * and [GalMessage.Sensor.SENSOR_ERROR]. Sends go out with+ * `GalConnection.send(channelId, type, payload)` -- always encrypted, never+ * CONTROL-flagged, like all service-channel traffic.+ *+ * Direction ground truth (auto/docs/FINDINGS.md section 2, the `rvb`+ * endpoint): `xnu` request fields are (1 sensor_type, 2 min_update_period).+ * Every other field number here is MA sender-defined -- the teardown never+ * recovered the `xnv`/`xnr`/`xns` layouts -- so exact-bytes tests pin OUR+ * numbering to catch an accidental renumber here, not at a DHU.+ */+object SensorCodec {++ /**+ * The stub subscription set: the only types the stub subscribes to on the+ * ch7 grant. Parked, night, last-known location, speed 0 -- everything+ * maps-dev needs for the Phase 6 seam, nothing the DHU must stream for+ * the 5-minute ACTIVE verdict.+ */+ val STUB_SUBSCRIPTIONS: List<SensorType> = listOf(+ SensorType.LOCATION,+ SensorType.NIGHT_MODE,+ SensorType.SPEED,+ SensorType.DRIVING_STATUS_DATA,+ )++ /**+ * Phone -> HU: subscribe to [type]. The period is omitted for the head+ * unit's default rate -- only pass one to slow a chatty sensor down.+ */+ fun encodeSubscribe(type: SensorType, minPeriodMs: Long? = null): Pair<Int, ByteArray> {+ val builder = SensorRequest.newBuilder().setSensorType(type)+ if (minPeriodMs != null) builder.minUpdatePeriodMs = minPeriodMs+ return GalMessage.Sensor.SENSOR_REQUEST to builder.build().toByteArray()+ }++ /** Phone -> HU: unsubscribe (a request with period -1). */+ fun encodeUnsubscribe(type: SensorType): Pair<Int, ByteArray> =+ encodeSubscribe(type, GalMessage.Sensor.UNSUBSCRIBE_PERIOD)++ /**+ * Parses a HU -> phone subscription answer, throwing on malformed bytes+ * like every other generated parser here. Callers that must survive+ * hostile traffic use [decodeInbound] instead.+ */+ fun decodeResponse(payload: ByteArray): SensorResponse = SensorResponse.parseFrom(payload)++ /**+ * Classifies one inbound ch7 message, never throwing: malformed bytes,+ * uninitialized payloads (a required field dropped, e.g. an unknown enum+ * the lite runtime refused) and unknown types all decode to+ * [InboundSensor.Observed] -- the pump logs them and carries on.+ *+ * Route by channel id before calling: 0x8004 is aliased across services+ * (MediaAck on media channels, ACTION on ch14), so only ch7 traffic+ * belongs here.+ */+ fun decodeInbound(type: Int, payload: ByteArray): InboundSensor = when (type) {+ GalMessage.Sensor.SENSOR_RESPONSE -> runCatching { SensorResponse.parseFrom(payload) }+ .getOrNull()+ ?.takeIf { it.isInitialized }+ ?.let { InboundSensor.Subscribed(it.sensorType, if (it.hasStatus()) it.status else 0) }+ ?: InboundSensor.Observed(type)+ GalMessage.Sensor.SENSOR_BATCH -> runCatching { SensorBatch.parseFrom(payload) }+ .getOrNull()+ ?.takeIf { it.isInitialized }+ ?.let { InboundSensor.Readings(it.eventsList) }+ ?: InboundSensor.Observed(type)+ GalMessage.Sensor.SENSOR_ERROR -> runCatching { SensorError.parseFrom(payload) }+ .getOrNull()+ ?.takeIf { it.isInitialized }+ ?.let { InboundSensor.Error(it.sensorType, if (it.hasStatus()) it.status else 0) }+ ?: InboundSensor.Observed(type)+ else -> InboundSensor.Observed(type)+ }++ /** Builds one batch carrying location, for tests and head-unit stand-ins. */+ fun buildLocationBatch(+ latitudeE7: Long,+ longitudeE7: Long,+ accuracyM: Int? = null,+ timestampMs: Long? = null,+ ): ByteArray {+ val fix = LocationReading.newBuilder()+ .setLatitudeE7(latitudeE7)+ .setLongitudeE7(longitudeE7)+ if (accuracyM != null) fix.accuracyM = accuracyM+ if (timestampMs != null) fix.timestampMs = timestampMs+ return SensorBatch.newBuilder()+ .addEvents(+ SensorEvent.newBuilder()+ .setSensorType(SensorType.LOCATION)+ .setLocation(fix),+ )+ .build()+ .toByteArray()+ }++ /** Builds one batch carrying speed, for tests and head-unit stand-ins. */+ fun buildSpeedBatch(speedMps: Double): ByteArray = SensorBatch.newBuilder()+ .addEvents(+ SensorEvent.newBuilder()+ .setSensorType(SensorType.SPEED)+ .setSpeed(SpeedReading.newBuilder().setSpeedMps(speedMps)),+ )+ .build()+ .toByteArray()++ /** Builds one batch carrying night mode, for tests and head-unit stand-ins. */+ fun buildNightBatch(isNight: Boolean): ByteArray = SensorBatch.newBuilder()+ .addEvents(+ SensorEvent.newBuilder()+ .setSensorType(SensorType.NIGHT_MODE)+ .setNight(NightReading.newBuilder().setIsNight(isNight)),+ )+ .build()+ .toByteArray()++ /** Builds one batch carrying parked state, for tests and head-unit stand-ins. */+ fun buildDrivingStatusBatch(parked: Boolean): ByteArray = SensorBatch.newBuilder()+ .addEvents(+ SensorEvent.newBuilder()+ .setSensorType(SensorType.DRIVING_STATUS_DATA)+ .setDrivingStatus(DrivingStatusReading.newBuilder().setParked(parked)),+ )+ .build()+ .toByteArray()+}
auto/protocol/src/main/proto/gal/navigation.proto
diff --git a/auto/protocol/src/main/proto/gal/navigation.proto b/auto/protocol/src/main/proto/gal/navigation.protonew file mode 100644index 0000000000..1124ee7a05--- /dev/null+++ b/auto/protocol/src/main/proto/gal/navigation.proto@@ -0,0 +1,34 @@+// Google Automotive Link navigation-status channel (service 10,+// NAVIGATION_STATUS): phone -> head unit turn guidance for the cluster and+// head-unit display. The head unit sends nothing normative back; inbound+// ch10 traffic is observed and ignored.+//+// Provenance: MA sender-defined throughout -- the teardown recovered the+// service descriptor slot (`Service.navigation_status`, control.proto field+// 8) but never the channel message IDs. STATUS (0x8001) mirrors the+// aasdk/openauto phone-to-HU navigation status message; if the teardown ever+// recovers the real IDs they replace `GalMessage.NavigationStatus`. This is+// a DHU-tolerated stub by construction: an unknown ch10 payload earns at+// worst a bare MessageError (0xff) on ch10 while video and the bring-up+// carry on.+//+// Stub phase (Phase 5): the phone posts one well-formed inactive status on+// the grant ("no guidance") and stays quiet. Live turn updates land with+// Phase 6 maps-dev through NavStatusCodec.encodeStatus.++syntax = "proto2";++package gal;++option java_package = "com.vayunmathur.auto.protocol.gal";+option java_multiple_files = true;++// 0x8001, phone -> HU. All fields optional: the stub posts guidance_active+// explicitly false (08 00 on the wire) rather than an empty payload, so the+// "no guidance" state is stated, not implied.+message NavigationStatus {+ optional bool guidance_active = 1;+ optional string next_road = 2;+ optional int32 next_turn_distance_m = 3;+ optional string maneuver = 4;+}
auto/protocol/src/main/proto/gal/sensors.proto
diff --git a/auto/protocol/src/main/proto/gal/sensors.proto b/auto/protocol/src/main/proto/gal/sensors.protonew file mode 100644index 0000000000..48528893fe--- /dev/null+++ b/auto/protocol/src/main/proto/gal/sensors.proto@@ -0,0 +1,125 @@+// Google Automotive Link sensor channel (service 7, SENSOR_SOURCE): the car+// streams readings, the phone subscribes.+//+// Direction (auto/docs/FINDINGS.md section 2, the `rvb` endpoint): phone ->+// HU SensorRequest (0x8001, `xnu` {1 sensor_type, 2 min_update_period},+// synchronous with a 2000 ms timeout, -1 unsubscribes); HU -> phone+// SensorResponse (0x8002, `xnv`), SensorBatch (0x8003, `xnr`) and SensorError+// (0x8004, `xns`). 0x8004 here is SensorError, NOT MediaAck: scope every+// parse by channel id (VideoSinkChannel and InputChannel already do; the 0x04+// CONTROL frame flag never enters routing -- HANDOFF.md section 9).+//+// Provenance: the 26 sensor-type names and their order come from the APK's+// `xny` enum via the `rvb.j()` dumper (FINDINGS.md section 2), numbered+// 1-based in that order. The `xnu` field numbers (1, 2) are from the+// teardown; every other field number below is MA sender-defined -- the+// teardown never recovered the `xnv`/`xnr`/`xns` layouts. Exact-bytes tests+// pin OUR numbering so an accidental renumber fails here, not at a DHU that+// silently ignores us. If the teardown ever recovers those layouts, re-pin+// this file against them like gal/input.proto.+//+// Stub phase (Phase 5): the phone subscribes to LOCATION, NIGHT_MODE, SPEED+// and DRIVING_STATUS_DATA only -- parked, night-follows-phone, last-known+// location, speed 0 -- and observes whatever batches come back. Full live+// values (phone GPS feed, maps wiring) land with Phase 6 maps-dev through+// the SensorChannel onValues seam.++syntax = "proto2";++package gal;++option java_package = "com.vayunmathur.auto.protocol.gal";+option java_multiple_files = true;++// `xny`, in dumper order. Names are the FINDINGS.md names, not aasdk's.+enum SensorType {+ LOCATION = 1;+ COMPASS = 2;+ SPEED = 3;+ RPM = 4;+ ODOMETER = 5;+ FUEL = 6;+ PARKING_BRAKE = 7;+ GEAR = 8;+ OBDII_DIAGNOSTIC_CODE = 9;+ NIGHT_MODE = 10;+ ENVIRONMENT_DATA = 11;+ HVAC_DATA = 12;+ DRIVING_STATUS_DATA = 13;+ DEAD_RECKONING_DATA = 14;+ PASSENGER_DATA = 15;+ DOOR_DATA = 16;+ LIGHT_DATA = 17;+ TIRE_PRESSURE_DATA = 18;+ ACCELEROMETER_DATA = 19;+ GYROSCOPE_DATA = 20;+ GPS_SATELLITE_DATA = 21;+ TOLL_CARD = 22;+ VEHICLE_ENERGY_MODEL_DATA = 23;+ TRAILER_DATA = 24;+ RAW_VEHICLE_ENERGY_MODEL = 25;+ RAW_EV_TRIP_SETTINGS = 26;+}++// 0x8001, phone -> HU: subscribe. `xnu` fields 1-2, from the teardown.+// Omit the period for the head unit's default rate; -1 unsubscribes (see+// GalMessage.Sensor.UNSUBSCRIBE_PERIOD).+message SensorRequest {+ required SensorType sensor_type = 1;+ optional int64 min_update_period_ms = 2;+}++// 0x8002, HU -> phone: subscription answer. MA sender-defined: the teardown+// recovered the id but not the `xnv` layout. Status 0 means subscribed.+message SensorResponse {+ required SensorType sensor_type = 1;+ optional int32 status = 2;+}++// 0x8003, HU -> phone: streamed readings. MA sender-defined, same caveat.+message SensorBatch {+ repeated SensorEvent events = 1;+}++// One reading. The declared type attributes the event; the payload present+// carries the value. An event with no payload is counted but changes no+// value -- the owner keeps its last-known rather than clobbering it.+message SensorEvent {+ required SensorType sensor_type = 1;+ optional LocationReading location = 2;+ optional CompassReading compass = 3;+ optional SpeedReading speed = 4;+ optional NightReading night = 5;+ optional DrivingStatusReading driving_status = 6;+}++message LocationReading {+ optional int64 latitude_e7 = 1;+ optional int64 longitude_e7 = 2;+ optional int32 accuracy_m = 3;+ optional int64 timestamp_ms = 4;+}++message CompassReading {+ optional int32 heading_deg = 1;+}++message SpeedReading {+ optional double speed_mps = 1;+}++message NightReading {+ optional bool is_night = 1;+}++message DrivingStatusReading {+ optional bool parked = 1;+}++// 0x8004, HU -> phone: a subscription or stream failure. MA sender-defined,+// same caveat as SensorResponse. Observed, never fatal -- the bring-up and+// video carry on.+message SensorError {+ required SensorType sensor_type = 1;+ optional int32 status = 2;+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/NavStatusCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/NavStatusCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/NavStatusCodecTest.ktnew file mode 100644index 0000000000..422cf065ba--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/NavStatusCodecTest.kt@@ -0,0 +1,53 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.NavigationStatus+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals++/**+ * Pins the navigation-status channel (service 10) wire format.+ *+ * MA sender-defined throughout: the teardown never recovered the channel+ * message IDs, so these pin OUR numbering (STATUS 0x8001) to catch an+ * accidental renumber here rather than at a DHU that silently ignores us.+ * If the teardown ever recovers the real IDs, re-pin against them.+ */+class NavStatusCodecTest {++ @Test+ fun `the inactive stub states guidance off explicitly`() {+ // guidance_active false is 08 00 -- stated, not implied by absence.+ val (type, payload) = NavStatusCodec.encodeInactive()+ assertEquals(GalMessage.NavigationStatus.STATUS, type)+ assertContentEquals(byteArrayOf(0x08, 0x00), payload)+ }++ @Test+ fun `a live status round-trips its turn fields`() {+ val (type, payload) = NavStatusCodec.encodeStatus(+ guidanceActive = true,+ nextRoad = "El Camino Real",+ nextTurnDistanceM = 250,+ maneuver = "TURN_RIGHT",+ )+ assertEquals(GalMessage.NavigationStatus.STATUS, type)+ val parsed = NavigationStatus.parseFrom(payload)+ assertEquals(true, parsed.guidanceActive)+ assertEquals("El Camino Real", parsed.nextRoad)+ assertEquals(250, parsed.nextTurnDistanceM)+ assertEquals("TURN_RIGHT", parsed.maneuver)+ }++ @Test+ fun `absent turn fields stay absent`() {+ // A bare active flip posts only field 1; the head unit keeps its+ // last turn rather than clearing it on missing fields.+ val (_, payload) = NavStatusCodec.encodeStatus(guidanceActive = true)+ val parsed = NavigationStatus.parseFrom(payload)+ assertEquals(true, parsed.guidanceActive)+ assertEquals(false, parsed.hasNextRoad())+ assertEquals(false, parsed.hasNextTurnDistanceM())+ assertEquals(false, parsed.hasManeuver())+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.ktnew file mode 100644index 0000000000..43196204d5--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.kt@@ -0,0 +1,209 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.SensorEvent+import com.vayunmathur.auto.protocol.gal.SensorRequest+import com.vayunmathur.auto.protocol.gal.SensorResponse+import com.vayunmathur.auto.protocol.gal.SensorType+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the sensor-channel (service 7) wire format and the codec around it.+ *+ * Exact bytes only where the teardown is exact (the `xnu` subscribe with+ * fields 1-2, and the `xny` enum order); everywhere else round-trips pin OUR+ * field numbering so an accidental renumber fails here, not at a DHU that+ * silently ignores us.+ */+class SensorCodecTest {++ @Test+ fun `subscribe pins sensor type in field 1 and omits the period`() {+ // `xnu`: field 1 sensor_type, field 2 min_update_period. A bare+ // LOCATION subscribe is 08 01.+ val (type, payload) = SensorCodec.encodeSubscribe(SensorType.LOCATION)+ assertEquals(GalMessage.Sensor.SENSOR_REQUEST, type)+ assertContentEquals(byteArrayOf(0x08, 0x01), payload)+ val parsed = SensorRequest.parseFrom(payload)+ assertEquals(SensorType.LOCATION, parsed.sensorType)+ assertTrue(!parsed.hasMinUpdatePeriodMs())+ }++ @Test+ fun `subscribe carries an explicit period in field 2`() {+ val (_, payload) = SensorCodec.encodeSubscribe(SensorType.SPEED, minPeriodMs = 1_000)+ val parsed = SensorRequest.parseFrom(payload)+ assertEquals(SensorType.SPEED, parsed.sensorType)+ assertEquals(1_000L, parsed.minUpdatePeriodMs)+ }++ @Test+ fun `unsubscribe is a request with period minus one`() {+ val (type, payload) = SensorCodec.encodeUnsubscribe(SensorType.COMPASS)+ assertEquals(GalMessage.Sensor.SENSOR_REQUEST, type)+ assertEquals(+ GalMessage.Sensor.UNSUBSCRIBE_PERIOD,+ SensorRequest.parseFrom(payload).minUpdatePeriodMs,+ )+ }++ @Test+ fun `sensor type numbering matches the teardown order`() {+ // `xny` in `rvb.j()` dumper order; off-by-one here subscribes the+ // wrong sensor on a head unit that speaks the real layout.+ assertEquals(1, SensorType.LOCATION.number)+ assertEquals(2, SensorType.COMPASS.number)+ assertEquals(3, SensorType.SPEED.number)+ assertEquals(10, SensorType.NIGHT_MODE.number)+ assertEquals(13, SensorType.DRIVING_STATUS_DATA.number)+ assertEquals(26, SensorType.RAW_EV_TRIP_SETTINGS.number)+ }++ @Test+ fun `the stub subscribes to exactly the stub set`() {+ assertEquals(+ setOf(+ SensorType.LOCATION,+ SensorType.NIGHT_MODE,+ SensorType.SPEED,+ SensorType.DRIVING_STATUS_DATA,+ ),+ SensorCodec.STUB_SUBSCRIPTIONS.toSet(),+ )+ }++ @Test+ fun `a subscription answer classifies with its status`() {+ val payload = SensorResponse.newBuilder()+ .setSensorType(SensorType.SPEED)+ .setStatus(0)+ .build()+ .toByteArray()+ assertEquals(+ InboundSensor.Subscribed(SensorType.SPEED, 0),+ SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_RESPONSE, payload),+ )+ }++ @Test+ fun `a location batch folds into last-known`() {+ val batch = SensorCodec.buildLocationBatch(+ latitudeE7 = 377_699_060,+ longitudeE7 = -1_224_195_609,+ accuracyM = 8,+ timestampMs = 42L,+ )+ val inbound = SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_BATCH, batch)+ val events = (inbound as? InboundSensor.Readings)?.events+ ?: error("expected readings")+ val snapshot = SensorSnapshot().withEvents(events)+ assertEquals(377_699_060L, snapshot.location?.latitudeE7)+ assertEquals(-1_224_195_609L, snapshot.location?.longitudeE7)+ assertEquals(8, snapshot.location?.accuracyM)+ assertEquals(42L, snapshot.location?.timestampMs)+ // The stub defaults survive a location-only batch.+ assertTrue(snapshot.parked)+ assertEquals(0.0, snapshot.speedMps)+ assertNull(snapshot.isNight)+ }++ @Test+ fun `speed night and parked batches each move only their value`() {+ val start = SensorSnapshot()+ val speeded = start.withEvents(+ (SensorCodec.decodeInbound(+ GalMessage.Sensor.SENSOR_BATCH,+ SensorCodec.buildSpeedBatch(13.9),+ ) as InboundSensor.Readings).events,+ )+ assertEquals(13.9, speeded.speedMps, 1e-9)+ assertTrue(speeded.parked)++ val nighted = speeded.withEvents(+ (SensorCodec.decodeInbound(+ GalMessage.Sensor.SENSOR_BATCH,+ SensorCodec.buildNightBatch(true),+ ) as InboundSensor.Readings).events,+ )+ assertEquals(true, nighted.isNight)+ assertEquals(13.9, nighted.speedMps, 1e-9)++ val moved = nighted.withEvents(+ (SensorCodec.decodeInbound(+ GalMessage.Sensor.SENSOR_BATCH,+ SensorCodec.buildDrivingStatusBatch(parked = false),+ ) as InboundSensor.Readings).events,+ )+ assertEquals(false, moved.parked)+ assertEquals(true, moved.isNight)+ }++ @Test+ fun `a payload-less event keeps last-known instead of clobbering`() {+ val seeded = SensorSnapshot(speedMps = 5.0)+ val empty = SensorEvent.newBuilder()+ .setSensorType(SensorType.SPEED)+ .build()+ assertEquals(5.0, seeded.withEvents(listOf(empty)).speedMps, 1e-9)+ }++ @Test+ fun `a sensor error classifies with its type`() {+ val payload = com.vayunmathur.auto.protocol.gal.SensorError.newBuilder()+ .setSensorType(SensorType.LOCATION)+ .setStatus(-9)+ .build()+ .toByteArray()+ assertEquals(+ InboundSensor.Error(SensorType.LOCATION, -9),+ SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_ERROR, payload),+ )+ }++ @Test+ fun `0x8004 on ch7 is an error, never a media ack`() {+ // The alias guard: the same wire value parses as SensorError here --+ // owners that skip the channel-id check misparse this as a MediaAck.+ val error = com.vayunmathur.auto.protocol.gal.SensorError.newBuilder()+ .setSensorType(SensorType.SPEED)+ .build()+ .toByteArray()+ val inbound = SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_ERROR, error)+ assertTrue(inbound is InboundSensor.Error)+ assertEquals(GalMessage.Media.ACK, GalMessage.Sensor.SENSOR_ERROR)+ }++ @Test+ fun `garbage on ch7 is observed, never fatal`() {+ // Wrong type, truncated response, and an uninitialized response all+ // decode to Observed: the pump logs them and carries on.+ val observed = SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_BATCH, byteArrayOf(1, 2, 3))+ assertEquals(InboundSensor.Observed(GalMessage.Sensor.SENSOR_BATCH), observed)+ assertEquals(+ InboundSensor.Observed(GalMessage.Sensor.SENSOR_RESPONSE),+ SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_RESPONSE, byteArrayOf(0x08)),+ )+ assertEquals(+ InboundSensor.Observed(GalMessage.Sensor.SENSOR_RESPONSE),+ SensorCodec.decodeInbound(+ GalMessage.Sensor.SENSOR_RESPONSE,+ SensorResponse.newBuilder().buildPartial().toByteArray(),+ ),+ )+ }++ @Test+ fun `ch7 types sit in the service range`() {+ val ids = setOf(+ GalMessage.Sensor.SENSOR_REQUEST,+ GalMessage.Sensor.SENSOR_RESPONSE,+ GalMessage.Sensor.SENSOR_BATCH,+ GalMessage.Sensor.SENSOR_ERROR,+ )+ assertEquals(4, ids.size)+ assertTrue(ids.all { it in 0x8000..0xFFFF })+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/GuidanceChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/GuidanceChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/GuidanceChannel.ktnew file mode 100644index 0000000000..c2ab819fbf--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/GuidanceChannel.kt@@ -0,0 +1,110 @@+package com.vayunmathur.auto.platform++import android.util.Log+import com.vayunmathur.auto.protocol.AudioCodec+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.InboundAudio+import com.vayunmathur.auto.protocol.SelectedConfig+import com.vayunmathur.auto.protocol.gal.Service++/**+ * The guidance audio sink stub: claims ch3 through the shared sink handshake,+ * then stays idle.+ *+ * Bring-up mirrors the other sinks (`requestSetup` -> CONFIG observed) but+ * deliberately never sends START: an open, set-up-but-idle sink expects no+ * frames, while a started stream the phone never feeds would leave the head+ * unit waiting on audio that never comes. Silence here is the well-formed+ * answer -- "no guidance to play" stated by idleness rather than implied by+ * absence. Live TTS starts the stream through this same owner (audio-dev /+ * maps-dev seam: call [startStream], feed PCM, call [stopStream]).+ *+ * Reuses audio-dev's [AudioCodec] for the shared `jdk` sink shape (setup+ * encoding, config negotiation, inbound classification) rather than+ * re-encoding it: ch3 differs from ch4/5 only by service id, not wire+ * protocol. ch3 opens in the generic wire-order pass; the setup goes out on+ * the grant -- sending on a channel the head unit has not opened earns a+ * bare MessageError (0xff).+ *+ * Route by channel id: 0x8004 here would be a MediaAck, parsed by the shared+ * codec, never confused with the ch7 SensorError -- the 0x04 CONTROL frame+ * flag never enters routing (HANDOFF.md section 9).+ */+class GuidanceChannel(+ private val service: Service,+ private val connection: GalConnection,+ private val onEvent: (SensorEvent) -> Unit = {},+) {+ val channelId: Int get() = service.id++ private var open = false+ private var selected: SelectedConfig? = null+ private var sessionId = -1++ /** The grant arrived: claim the channel for audio. Called once per channel open. */+ fun onChannelOpen() {+ open = true+ val (type, payload) = AudioCodec.encodeSetup()+ connection.send(channelId, type, payload)+ Log.i(TAG, "guidance setup requested")+ onEvent(SensorEvent.GuidanceSetup)+ }++ /** 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+ }+ when (val inbound = AudioCodec.decodeSinkInbound(type, payload)) {+ is InboundAudio.Config -> {+ // Confirm against discovery like the other sinks, then stay+ // idle: confirmed-but-never-started is the stub state.+ val pick = selected ?: AudioCodec.selectConfig(service)+ selected = pick?.let { AudioCodec.confirmConfig(inbound.response, it, service) }+ Log.i(TAG, "guidance configured (accepted=${selected != null}); staying idle")+ onEvent(SensorEvent.GuidanceConfigured(accepted = selected != null))+ }+ is InboundAudio.Ack -> Log.d(TAG, "guidance ack (no stream running)")+ is InboundAudio.Sync -> Log.d(TAG, "guidance sync pulse")+ is InboundAudio.Observed -> Log.d(TAG, "unhandled guidance message 0x${type.toString(16)}")+ }+ }++ /**+ * Live-guidance seam (audio-dev / maps-dev): start streaming the+ * confirmed configuration. A no-op until a CONFIG confirmed one --+ * starting with nothing confirmed would send frames the head unit never+ * agreed to decode.+ */+ fun startStream(sessionId: Int = 0) {+ val config = selected ?: run {+ Log.w(TAG, "guidance start with no confirmed config; staying idle")+ return+ }+ this.sessionId = sessionId+ val (type, payload) = AudioCodec.encodeStart(sessionId, config.index)+ connection.send(channelId, type, payload)+ Log.i(TAG, "guidance stream started (session $sessionId, config ${config.index})")+ }++ /** Live-guidance seam: stop the stream; the channel stays open and idle. */+ fun stopStream() {+ if (sessionId < 0) return+ val (type, payload) = AudioCodec.encodeStop()+ connection.send(channelId, type, payload)+ sessionId = -1+ Log.i(TAG, "guidance stream stopped")+ }++ fun release() {+ runCatching { stopStream() }+ open = false+ selected = null+ }++ private companion object {+ const val TAG = "MaAuto.Guidance"+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/NavStatusChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/NavStatusChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/NavStatusChannel.ktnew file mode 100644index 0000000000..eef7728dca--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/NavStatusChannel.kt@@ -0,0 +1,78 @@+package com.vayunmathur.auto.platform++import android.util.Log+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.NavStatusCodec++/**+ * The navigation-status channel: posts phone-side turn guidance onto ch10.+ *+ * The channel is phone -> head unit simplex: the phone posts, the head unit+ * sends nothing normative back, so inbound ch10 traffic is observed and+ * ignored. ch10 opens in the generic wire-order pass; the stub post goes out+ * on the grant -- sending on a channel the head unit has not opened earns a+ * bare MessageError (0xff).+ *+ * Stub phase (Phase 5): one well-formed inactive post ("no guidance",+ * stated explicitly rather than implied), then quiet -- the well-formed+ * nack the spec calls for. Live turn updates land with Phase 6 maps-dev+ * through [postStatus]: next road, distance metres and maneuver token per+ * turn, reposted as the route advances.+ */+class NavStatusChannel(+ private val connection: GalConnection,+ private val onEvent: (SensorEvent) -> Unit = {},+) {+ val channelId: Int get() = GalService.NAVIGATION_STATUS.id++ private var open = false++ /** The grant arrived: post the inactive stub. Called once per channel open. */+ fun onChannelOpen() {+ open = true+ val (type, payload) = NavStatusCodec.encodeInactive()+ connection.send(channelId, type, payload)+ Log.i(TAG, "nav-status posted: no guidance")+ onEvent(SensorEvent.NavStatusPosted)+ }++ /** One message for this channel; the head unit sends nothing normative, so all inbound is observed. */+ fun onMessage(channelId: Int, type: Int, payload: ByteArray) {+ if (channelId != this.channelId) {+ Log.w(TAG, "ignoring 0x${type.toString(16)} for channel $channelId")+ return+ }+ Log.d(TAG, "unhandled nav-status message 0x${type.toString(16)}")+ }++ /**+ * Live-guidance seam (Phase 6, maps-dev): post a turn update. Posts+ * before the grant are dropped, never queued -- the grant post carries+ * the state and the next live post overwrites it.+ */+ fun postStatus(+ guidanceActive: Boolean,+ nextRoad: String? = null,+ nextTurnDistanceM: Int? = null,+ maneuver: String? = null,+ ) {+ if (!open) return+ val (type, payload) = NavStatusCodec.encodeStatus(+ guidanceActive,+ nextRoad,+ nextTurnDistanceM,+ maneuver,+ )+ connection.send(channelId, type, payload)+ onEvent(SensorEvent.NavStatusPosted)+ }++ fun release() {+ open = false+ }++ private companion object {+ const val TAG = "MaAuto.NavStatus"+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.ktnew file mode 100644index 0000000000..f658a24a3d--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.kt@@ -0,0 +1,124 @@+package com.vayunmathur.auto.platform++import android.util.Log+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalService+import com.vayunmathur.auto.protocol.InboundSensor+import com.vayunmathur.auto.protocol.SensorCodec+import com.vayunmathur.auto.protocol.SensorSnapshot+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * How the stub answers "is it night": the head unit's NIGHT_MODE stream wins+ * when it has spoken, otherwise the phone's own night state decides.+ *+ * Maps seam (Phase 6, maps-dev): replace the lambda with the Maps/theme+ * source and feed live batches through [SensorChannel.onValues] -- the+ * channel shape stays the same, only the sources change.+ */+fun interface NightSource {+ /** The phone's own night state, consulted until the HU reports NIGHT_MODE. */+ fun phoneNight(): Boolean+}++/**+ * The sensor source channel: subscribes to the stub set on the ch7 grant and+ * folds the head unit's batches into a last-known snapshot.+ *+ * Bring-up needs nothing beyond the generic open: ch7 opens in the wire-order+ * pass like every other service, and subscribes go out on the grant --+ * sending on a channel the head unit has not opened earns a bare MessageError+ * (0xff). One channel at a time is enforced by the pump's sequential open+ * order; subscriptions batch behind a single flush the same way.+ *+ * Route by channel id: 0x8004 is SensorError here but MediaAck on media+ * channels and ACTION on ch14, so only ch7 traffic belongs to [SensorCodec].+ * The 0x04 CONTROL frame flag does NOT mean "control channel" (HANDOFF.md+ * section 9) and never enters this decision.+ *+ * Full live values (Phase 6, maps-dev): feed phone GPS / fused speed through+ * [onValues] -- see [SensorSnapshot.withEvents] -- and read [snapshot] for+ * the car UI. The stub posts nothing upstream; it only subscribes.+ */+class SensorChannel(+ private val connection: GalConnection,+ private val night: NightSource = NightSource { false },+ private val onEvent: (SensorEvent) -> Unit = {},+ /** Live-value seam: batches from phone sensors (maps-dev) fold in like HU batches. */+ private val onValues: (SensorSnapshot) -> Unit = {},+) {+ val channelId: Int get() = GalService.SENSOR_SOURCE.id++ private val _snapshot = MutableStateFlow(SensorSnapshot())+ /** Last-known sensor values; parked / speed 0 / night-unknown until batches move them. */+ val snapshot: StateFlow<SensorSnapshot> = _snapshot.asStateFlow()++ private var open = false++ /**+ * The grant arrived: subscribe to the stub set. Called once per channel+ * open. Night follows the phone until the first NIGHT_MODE batch -- the+ * snapshot seeds from [night] now so the car UI has an answer before the+ * head unit streams anything.+ */+ fun onChannelOpen() {+ open = true+ val seeded = _snapshot.value.copy(isNight = night.phoneNight())+ _snapshot.value = seeded+ for (type in SensorCodec.STUB_SUBSCRIPTIONS) {+ val (requestType, payload) = SensorCodec.encodeSubscribe(type)+ connection.send(channelId, requestType, payload)+ Log.i(TAG, "sensor subscribe: $type")+ onEvent(SensorEvent.Subscribed(type.name))+ }+ }++ /** 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+ }+ when (val inbound = SensorCodec.decodeInbound(type, payload)) {+ is InboundSensor.Subscribed -> {+ Log.i(TAG, "sensor subscribed: ${inbound.type} status=${inbound.status}")+ onEvent(SensorEvent.SubscriptionAnswered(inbound.type.name, inbound.status))+ }+ is InboundSensor.Readings -> {+ // A NIGHT_MODE event with a payload overrides the phone seed;+ // payload-less events keep last-known inside withEvents.+ val next = _snapshot.value.withEvents(inbound.events)+ _snapshot.value = next+ onValues(next)+ Log.d(TAG, "sensor batch: ${inbound.events.size} events")+ onEvent(SensorEvent.BatchReceived(inbound.events.size))+ }+ is InboundSensor.Error -> {+ // Observed, never fatal: the bring-up and video carry on.+ Log.w(TAG, "sensor error: ${inbound.type} status=${inbound.status}")+ onEvent(SensorEvent.SensorError(inbound.type.name, inbound.status))+ }+ is InboundSensor.Observed -> Log.d(TAG, "unhandled sensor message 0x${type.toString(16)}")+ }+ }++ /** Unsubscribes the stub set; the pump calls this on teardown before release. */+ fun release() {+ if (!open) return+ open = false+ // Best-effort: the socket may already be going away in teardown, and+ // an unsubscribe is courtesy, not protocol -- never fail the parting.+ for (type in SensorCodec.STUB_SUBSCRIPTIONS) {+ runCatching {+ val (requestType, payload) = SensorCodec.encodeUnsubscribe(type)+ connection.send(channelId, requestType, payload)+ }+ }+ }++ private companion object {+ const val TAG = "MaAuto.Sensors"+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/SensorEvent.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/SensorEvent.kt b/auto/src/main/java/com/vayunmathur/auto/platform/SensorEvent.ktnew file mode 100644index 0000000000..6acb00f95b--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/SensorEvent.kt@@ -0,0 +1,32 @@+package com.vayunmathur.auto.platform++/**+ * Something a sensor, guidance or navigation-status channel observed,+ * forwarded to [AutoSessionState] for the phone UI.+ *+ * Like [VideoEvent], [MessagingEvent] and [InputEvent], these are+ * fire-and-forget observations: the bring-up never waits on them, and the+ * service forwards them without gating any protocol step on the UI.+ */+sealed interface SensorEvent {+ /** One stub SensorRequest went out on ch7; [type] is the sensor name. */+ data class Subscribed(val type: String) : SensorEvent++ /** The head unit answered a subscription; [status] 0 means subscribed. */+ data class SubscriptionAnswered(val type: String, val status: Int) : SensorEvent++ /** One SensorBatch arrived on ch7; [count] is events in it. */+ data class BatchReceived(val count: Int) : SensorEvent++ /** The head unit reported a sensor failure on ch7 (0x8004 SensorError). */+ data class SensorError(val type: String, val status: Int) : SensorEvent++ /** Guidance sink (ch3) setup went out on its grant. */+ data object GuidanceSetup : SensorEvent++ /** The head unit answered guidance setup (0x8003 CONFIG). */+ data class GuidanceConfigured(val accepted: Boolean) : SensorEvent++ /** The inactive nav-status post went out on the ch10 grant. */+ data object NavStatusPosted : SensorEvent+}