,C,,0,,,,…*CS`. The layout copies a production head unit's log; what `C` and `0` stand for is not public.
-- Speed: device 1013, `-1807745016`, float km/h (BYD SDK speed), read four times a second over adb — `service call autoservice 7 i32 1013 i32 -1807745016`. Gear: device 1011, `555745336`, 1 P, 2 R, 3 N, 4 D, read once a second — `service call autoservice 5 i32 1011 i32 555745336`.
-
-Checked in the car at walking speed: the gear followed D, R and P (4, 2, 1), and the speed arrives in whole km/h. With the setting on, the iPhone asked for vehicle speed (id 4) and DiPlay sent `$PASCD` over both the Bluetooth and the Wi-Fi link. Whether the iPhone uses the speed in a tunnel is still to be tested. Gyro and accelerometer (`$PAGCD`, `$PAACD`) are not sent because their layout is not public.
-
-## Video while parked (optional, needs ADB)
-
-iOS 27 can play video on the CarPlay screen while the car is parked ("video in car"): the iPhone hands the head unit a media URL and drives playback, and the head unit plays it in its own player. With "Video while parked · needs ADB" turned on, DiPlay offers this and plays the video full screen over CarPlay; a tap shows **Back to CarPlay** and play/pause. The switch is off by default and reconnects CarPlay.
-
-Video is allowed only while the gear reads P. DiPlay reads the gearbox once a second through the adb shell (gearbox device 1011, `service call autoservice 5 i32 1011 i32 555745336` → 1 P, 2 R, 3 N, 4 D) and tells the iPhone with `setVideoPlaybackAllowed`. Leaving P closes the player and the iPhone goes on with audio only; so does a gear that cannot be read (no ADB access). The steering-wheel keys drive the car's player while it is open: play/pause toggles it and next/previous skip 10 s. They do not go to the iPhone, which ends the video session on a CarPlay play/pause.
-
-What the iPhone expects, as observed with iOS 27 and checked against Apple's CarPlay Simulator (Additional Tools for Xcode 27) and its AirPlay web app:
-
-- `/info` carries `videoPlaybackInfo`: `videoPlaybackAllowed`, `featuresEx` (the legacy feature bits plus bits 0 and 64, base64 of the little-endian bit set) and `playbackCapabilities`. SETUP enables `videoPlayback` when the iPhone proposes it; without `videoPlaybackInfo` the iPhone tears the session down.
-- The iPhone opens a "CarPlayVideo Settings App" data stream (`BB493F61-…`), encrypted like the iAP tunnel; each `sync` package gets an empty `rply`. Playback runs over remote control sessions without a socket (`A6B27562-…` video setup, `E3DC3EA6-…` overlay UI, `controlType` 1), answered with a stream ID from 3 up. Tearing down one of them must not close the iAP tunnel (stream ID 1).
-- Playback messages arrive as `POST /command` with `X-Apple-StreamID` and `{params: {data: bplist}}`: `insertPlayQueueItem`, `setRate`, `seek`, `playbackInfo`, `property`, `setProperty`, `stop`. DiPlay answers `playbackInfo`, `seek` and `property` the way Apple's web app does and sends `playbackState` when the car pauses or resumes. `requestUI` with `videoplayback:` asks the car to show its player.
-
-What plays: plain HTTPS media, as Safari sends it, worked in the car, including pause, seeking from the iPhone and the wheel keys. Apple TV sends HLS encrypted with `cbcs` (SAMPLE-AES) and keys for FairPlay, Widevine and PlayReady only; over AirPlay the iPhone brokers just the FairPlay key (`unhandledURL`, `streamingKey`), which needs a licensed FairPlay receiver, so Apple TV+ does not play here. When the car's player cannot play an item, DiPlay tells the iPhone as Apple's receiver does (`{type: error, error: {domain, code}, uuid}`), shows a short note and returns to CarPlay. Netflix does not support AirPlay. In testing YouTube played audio only.
diff --git a/docs/PR3_REVIEW.md b/docs/PR3_REVIEW.md
deleted file mode 100644
index 87890503f5..0000000000
--- a/docs/PR3_REVIEW.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Release review — 27 September 2026
-
-# 0.2.0 — BYD navigation and connection improvements
-
-- Standalone windshield HUD arrows, distance and street names on the verified DiLink5.1 firmware; no ADB, root or computer helper.
-- Retain contributor cluster/SOME-IP navigation, route parsing, BYD CarPlay icon and display-size presets.
-- Fix Car hotspot startup by using scoped IPv6 when available and binding discovery/probing to the AP interface. Physically confirmed on the development car.
-- Drain asynchronously decoded audio during packet gaps and rebuild the music buffer after starvation. Wi-Fi Direct is much better in the user retest; occasional audio cutouts remain for a later version.
-- Preserve bounded music-buffer choices, USB read improvements and decoder recovery; fix USB request/close races and keep vendor output outside phone callbacks.
-- Save audio/video/receive timing and discovery diagnostics without road names or protocol payloads.
-- HUD cleanup on normal end/disconnect/off/stale input; interrupted sessions recover on the next app launch. Force-stop may leave guidance visible until reopening.
-- Thanks to @romanchukg-cloud and @georgiyrr for PR #3 and vehicle testing.
-
-## Validation scope
-
-The user physically confirmed live standalone HUD guidance and street names in both apps. The latest DiPlay test also confirmed Car hotspot startup and substantially improved Wi-Fi Direct performance. Occasional audio cutouts remain; the user explicitly deferred them to another version and authorized pushing, merging and releasing these changes. The release packages now permit the verified standalone backend while retaining the exact firmware/stock-receiver guard. See [BYD navigation](BYD_NAVIGATION.md).
-
-Earlier local review blockers for the standalone HUD path are resolved by physical tests. No claim is made that every vehicle, map app, force-stop sequence or USB failure mode was physically tested. Release checks include unit tests, build/lint, package/signature inspection and public-source credential checks. Android signing secrets and accessory private assets remain outside the repository/source archives.
-
-Review corrections retain codec release/reconfigure during video recovery, synchronize USB request publication with close, interpret vendor status codes correctly, and separate vendor work from phone control callbacks. Runtime authentication assets follow the established explicit local release packaging.
diff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.md
index dcbc109d5e..9d0d30a593 100644
--- a/docs/THIRD_PARTY_NOTICES.md
+++ b/docs/THIRD_PARTY_NOTICES.md
@@ -2,21 +2,13 @@
## Receiver
-DiPlay is a modified version of [xcertplay by shilapi](https://github.com/shilapi/xcertplay). The upstream receiver is licensed under GNU GPL version 3; the full text is in `LICENSE` and the original README is retained in `docs/UPSTREAM-README.md`.
+LoopLink is a fork of [DiPlay by shihabal3amri](https://github.com/shihabal3amri/DiPlay), which is a modified version of [xcertplay by shilapi](https://github.com/shilapi/xcertplay). The upstream receiver is licensed under GNU GPL version 3; the full text is in `LICENSE` and the original README is retained in `docs/UPSTREAM-README.md`.
Upstream credits [LIVI](https://github.com/f-io/LIVI) and [Showcase](https://github.com/amineross/showcase) for protocol research. Existing source comments and attribution are preserved.
## Home and settings UI
-`common/src/main/java/com/shilapi/xcertplay/DiPlayActivity.kt` adapts the palette, visual arrangement and interface copy of the [DiAuto project](https://github.com/shihabal3amri/DiAuto). DiAuto's source is licensed under AGPL version 3. The UI file is marked AGPL-3.0-only; its license text is included in `docs/licenses/DiAuto-AGPL-3.0.txt`.
-
-## CarPlay icon
-
-The unmodified icon was obtained from Apple's developer site at:
-
-https://developer.apple.com/assets/elements/icons/carplay/carplay-96x96_2x.png
-
-CarPlay and the CarPlay icon are Apple Inc. marks/assets. This asset is not covered by the project's open-source code license. Its use here does not imply Apple approval or certification.
+`common/src/main/java/com/shilapi/xcertplay/DiPlayActivity.kt` adapts the visual arrangement and interface copy of the [DiAuto project](https://github.com/shihabal3amri/DiAuto). DiAuto's source is licensed under AGPL version 3. The UI file is marked AGPL-3.0-only; its license text is included in `docs/licenses/DiAuto-AGPL-3.0.txt`.
## Runtime dependencies
@@ -30,14 +22,12 @@ Gradle dependency declarations and version catalog accompany the source. License
## Experimental authentication data
-The public preview APK includes an accessory certificate/key pair recovered from public Carlinkit C2Air Allwinner V821 firmware during the owner's local investigation. These data are not newly generated Apple-issued credentials for DiPlay and are not relicensed as project source code. They are bundled in the preview APK to reproduce the offline experiment; continued acceptance and suitability for general distribution are unresolved. The source archive does not contain the private key, and the separate Android APK-signing key is never distributed.
+The public preview APK includes an accessory certificate/key pair recovered from public Carlinkit C2Air Allwinner V821 firmware during the owner's local investigation. These data are not newly generated Apple-issued credentials for DiPlay or LoopLink and are not relicensed as project source code. They are bundled in the preview APK to reproduce the offline experiment; continued acceptance and suitability for general distribution are unresolved. The source archive does not contain the private key, and the separate Android APK-signing key is never distributed.
## Download website
The static site layout, CSS and generator adapt DiAuto (AGPL-3.0). The AGPL license text is included with the source.
-## BYD HUD maneuver icons
-
-Required Notice: Copyright AndyShaman (https://github.com/AndyShaman/BYDMate)
+## Branding and trademarks
-The maneuver PNGs under `shared/src/main/assets/byd-hud-icons` were imported from BYDMate. Its PolyForm Noncommercial 1.0.0 terms and required notice are included alongside the assets. These files are separate from the project code license; upstream describes them as donor assets and their original provenance is not independently established. The validated DiLink5.1 windshield path uses factory turn codes rather than these images.
+The LoopLink name and logo (`asset/looplink-logo.svg`, `asset/looplink-mark.svg` and the app icons made from them) belong to the LoopLink project. CarPlay and iPhone are trademarks of Apple Inc.; LoopLink is not an Apple-certified product and no Apple affiliation or endorsement is implied.
diff --git a/mobile/build.gradle.kts b/mobile/build.gradle.kts
index 0cd9cd6097..a52261640d 100644
--- a/mobile/build.gradle.kts
+++ b/mobile/build.gradle.kts
@@ -14,7 +14,7 @@ android {
}
defaultConfig {
- applicationId = "com.shihab.diplay"
+ applicationId = "io.loopbreak.looplink"
minSdk = 28
targetSdk = 37
versionCode = 27
@@ -39,8 +39,7 @@ android {
buildTypes {
debug {
- applicationIdSuffix = ".hudtest"
- versionNameSuffix = "-hud-test"
+ versionNameSuffix = "-debug"
}
release {
optimization {
diff --git a/mobile/src/debug/AndroidManifest.xml b/mobile/src/debug/AndroidManifest.xml
deleted file mode 100644
index bad1bcbc00..0000000000
--- a/mobile/src/debug/AndroidManifest.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/mobile/src/debug/java/com/shilapi/xcertplay/hud/StandaloneHudDemoActivity.kt b/mobile/src/debug/java/com/shilapi/xcertplay/hud/StandaloneHudDemoActivity.kt
deleted file mode 100644
index 5ee646ae4b..0000000000
--- a/mobile/src/debug/java/com/shilapi/xcertplay/hud/StandaloneHudDemoActivity.kt
+++ /dev/null
@@ -1,146 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.app.Activity
-import android.content.ComponentName
-import android.content.Intent
-import android.content.pm.ApplicationInfo
-import android.content.pm.PackageManager
-import android.os.Build
-import android.os.Bundle
-import android.os.Handler
-import android.os.Looper
-import android.os.Process
-import android.os.SystemClock
-import android.util.Log
-import android.widget.Button
-import android.widget.LinearLayout
-import android.widget.TextView
-import java.security.MessageDigest
-
-/** Parked, finite probe of stock IPC. No shell, socket, SDK privilege or helper. */
-class StandaloneHudDemoActivity : Activity() {
- private val handler = Handler(Looper.getMainLooper())
- private lateinit var status: TextView
- private var showing = false
- private var started = 0L
- private var lastTurn = 0
- private var running = false
- private val target = ComponentName("com.byd.clusterdebug", "com.byd.clusterdebug.BroadcastReceiverCAN")
- private val tick = object : Runnable {
- override fun run() {
- if (!running) return
- try {
- val elapsed = SystemClock.elapsedRealtime() - started
- if (elapsed >= 16_000) { clear("demo complete"); return }
- val turn = if (elapsed < 8_000) 1 else 2
- val distance = if (turn == 1) 500 else 800
- val road = if (turn == 1) "Muscat Road" else "Sultan Qaboos Street"
- transmit(BydStandalonePackets.guidance(if (turn == 1) 2 else 3, 0, distance, road)!!)
- if (turn != lastTurn) Log.i(TAG, "APP_GUIDANCE uid=${Process.myUid()} turn=$turn distance=$distance")
- lastTurn = turn
- status.text = (if (turn == 1) "LEFT — 500 m" else "RIGHT — 800 m") + "\n" + road
- handler.postDelayed(this, 1_000)
- } catch (error: Exception) {
- Log.e(TAG, "Demo failed", error)
- clear("send failed")
- }
- }
- }
-
- override fun onCreate(state: Bundle?) {
- super.onCreate(state)
- status = TextView(this).apply { textSize = 32f; text = "Standalone HUD test ready" }
- setContentView(LinearLayout(this).apply {
- orientation = LinearLayout.VERTICAL
- setPadding(40, 40, 40, 40)
- addView(status)
- addView(TextView(this@StandaloneHudDemoActivity).apply {
- text = "Parked test: Muscat Road / left 500 m, then Sultan Qaboos Street / right 800 m; 8 seconds each, then clear."
- textSize = 22f
- })
- addView(Button(this@StandaloneHudDemoActivity).apply {
- text = "Start 16-second test"
- setOnClickListener { startDemo() }
- })
- addView(Button(this@StandaloneHudDemoActivity).apply {
- text = "Clear HUD"
- setOnClickListener {
- try { validateTarget(); showing = true; clear("button") }
- catch (error: Exception) { status.text = "Clear unavailable: ${error.message}" }
- }
- })
- })
- try {
- validateTarget()
- Log.i(TAG, "PREFLIGHT_OK uid=${Process.myUid()} stock receiver verified")
- if (intent.getBooleanExtra("run", false) && state == null) handler.post { startDemo() }
- } catch (error: Exception) {
- status.text = "Test unavailable: ${error.message}"
- Log.e(TAG, "Preflight failed", error)
- }
- }
-
- private fun validateTarget() {
- check(packageName == "com.shihab.diplay.hudtest" && Process.myUid() >= 10000)
- check(Build.FINGERPRINT == "BYD-AUTO/IVI/IVI:13/TP1A.220624.014/eng.build20260722.221155:user/release-keys") {
- "This test is restricted to the inspected firmware"
- }
- val info = packageManager.getPackageInfo(target.packageName, PackageManager.GET_SIGNING_CERTIFICATES)
- check(info.longVersionCode == 10601004L) { "Different stock receiver version" }
- check(info.applicationInfo!!.flags and ApplicationInfo.FLAG_SYSTEM != 0)
- val certs = info.signingInfo!!.apkContentsSigners
- check(certs.size == 1 && MessageDigest.getInstance("SHA-256").digest(certs[0].toByteArray())
- .joinToString("") { "%02x".format(it.toInt() and 255) } ==
- "efe3ca8ada0d10c655c3df9910ad2ebc121a47d9a6358434eb24074309933efc")
- val receiver = packageManager.getReceiverInfo(target, 0)
- check(receiver.enabled && receiver.exported && receiver.permission.isNullOrEmpty())
- }
-
- private fun startDemo() {
- if (running) return
- try {
- validateTarget()
-
- BydNavigationOutputs.setDiagnosticHold(true)
- showing = true // Preserve cleanup even if a later operation fails.
- transmit(StandaloneHudPackets.start())
- started = SystemClock.elapsedRealtime()
- running = true
- lastTurn = 0
- Log.i(TAG, "APP_START uid=${Process.myUid()} helper=none")
- // Start and subsequent records target the same manifest receiver.
- handler.postDelayed(tick, 250)
- } catch (error: Exception) {
- Log.e(TAG, "Standalone preflight/start failed", error)
- status.text = "Test unavailable: ${error.message}"
- clear("start failed")
- }
- }
-
- private fun transmit(packet: String) {
- sendBroadcast(Intent("byd.hud.NAVIGATION_DEMO").setComponent(target)
- .putExtra("normal", packet).addFlags(Intent.FLAG_RECEIVER_FOREGROUND))
- }
-
- private fun clear(reason: String) {
- running = false
- handler.removeCallbacksAndMessages(null)
- if (showing) {
- try {
- transmit(StandaloneHudPackets.clear())
- // Broadcast delivery is not a hardware acknowledgement.
- Log.i(TAG, "APP_CLEAR_SENT uid=${Process.myUid()} reason=$reason")
- showing = false
- status.text = "Clear sent — check windshield"
- } catch (error: Exception) {
- Log.e(TAG, "Clear failed; retry with Clear HUD", error)
- status.text = "Clear failed — tap Clear HUD"
- }
- }
-
- }
-
- override fun onStop() { clear("activity stopped"); BydNavigationOutputs.setDiagnosticHold(false); super.onStop() }
- override fun onDestroy() { clear("activity destroyed"); super.onDestroy() }
- companion object { private const val TAG = "BYD-Standalone" }
-}
diff --git a/mobile/src/debug/java/com/shilapi/xcertplay/hud/StandaloneHudPackets.kt b/mobile/src/debug/java/com/shilapi/xcertplay/hud/StandaloneHudPackets.kt
deleted file mode 100644
index 18e3c7ec0f..0000000000
--- a/mobile/src/debug/java/com/shilapi/xcertplay/hud/StandaloneHudPackets.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/** Fixed navigation-only vectors matching the inspected IVI HAL. Debug builds only. */
-internal object StandaloneHudPackets {
- fun start(): String = "43,E0,00,3A,01,02"
- fun clear(): String = "43,E0,00,3A,01,01"
- fun guidance(turn: Int, distanceMeters: Int): String {
- require(turn in setOf(1, 2, 11)) { "Demo permits only left, right and straight" }
- require(distanceMeters in 0..9999) { "Invalid demo distance" }
- return (record(0x43F01018, distanceMeters) + record(0x43F01010, turn) +
- record(0x43F01030, turn)).joinToString(",") { "%02X".format(it.toInt() and 255) }
- }
- private fun record(feature: Int, value: Int): ByteArray = byteArrayOf(
- (feature ushr 24).toByte(), (feature ushr 16).toByte(),
- (feature ushr 8).toByte(), feature.toByte(), 4,
- (value ushr 24).toByte(), (value ushr 16).toByte(),
- (value ushr 8).toByte(), value.toByte(),
- )
-}
diff --git a/mobile/src/debug/java/com/shilapi/xcertplay/hud/StarterBridgeReceiver.kt b/mobile/src/debug/java/com/shilapi/xcertplay/hud/StarterBridgeReceiver.kt
deleted file mode 100644
index 4e716ee9aa..0000000000
--- a/mobile/src/debug/java/com/shilapi/xcertplay/hud/StarterBridgeReceiver.kt
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.BroadcastReceiver
-import android.content.Context
-import android.content.Intent
-
-/** Only the shell (DUMP permission) can provision this temporary test bridge. */
-class StarterBridgeReceiver : BroadcastReceiver() {
- override fun onReceive(context: Context, intent: Intent) {
- when (intent.action) {
- "byd.hud.STARTER_CONFIG" -> {
- BydStarterBridge.configure(context, intent.getStringExtra("token") ?: return)
- resultData = "Starter configured"
- }
- "byd.hud.STARTER_DEMO" -> BydStarterBridge.demonstrate(context)
- }
- }
-}
diff --git a/mobile/src/main/AndroidManifest.xml b/mobile/src/main/AndroidManifest.xml
index 89e1b4b3c4..1753e5a18c 100644
--- a/mobile/src/main/AndroidManifest.xml
+++ b/mobile/src/main/AndroidManifest.xml
@@ -6,10 +6,10 @@
android:allowBackup="false"
android:fullBackupContent="@xml/backup_rules"
android:dataExtractionRules="@xml/data_extraction_rules"
- android:icon="@drawable/ic_carplay"
+ android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:localeConfig="@xml/locales_config"
- android:roundIcon="@drawable/ic_carplay"
+ android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="@style/Theme.Xcertplay">
diff --git a/mobile/src/main/res/values/strings.xml b/mobile/src/main/res/values/strings.xml
index 401758ed7e..2314ad203a 100644
--- a/mobile/src/main/res/values/strings.xml
+++ b/mobile/src/main/res/values/strings.xml
@@ -1,3 +1,3 @@
- DiPlay
+ LoopLink
diff --git a/shared/BYD_HUD_ICONS_NOTICE.md b/shared/BYD_HUD_ICONS_NOTICE.md
deleted file mode 100644
index c448a16392..0000000000
--- a/shared/BYD_HUD_ICONS_NOTICE.md
+++ /dev/null
@@ -1,5 +0,0 @@
-BYD HUD maneuver icons were imported from AndyShaman/BYDMate, app/src/main/assets/navi/.
-Required Notice: Copyright AndyShaman (https://github.com/AndyShaman/BYDMate)
-PolyForm Noncommercial License 1.0.0: https://polyformproject.org/licenses/noncommercial/1.0.0/
-See LICENSE-BYDMate.txt. These assets are not relicensed under the application's code license.
-Upstream describes these as donor assets; original provenance is not independently established.
diff --git a/shared/src/main/assets/byd-hud-icons/0x0.png b/shared/src/main/assets/byd-hud-icons/0x0.png
deleted file mode 100644
index b97e9f34b8..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x0.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x1.png b/shared/src/main/assets/byd-hud-icons/0x1.png
deleted file mode 100644
index e1d280ebb7..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x1.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x10.png b/shared/src/main/assets/byd-hud-icons/0x10.png
deleted file mode 100644
index 4859cba1d8..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x10.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x11.png b/shared/src/main/assets/byd-hud-icons/0x11.png
deleted file mode 100644
index 64fa34480d..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x11.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x12.png b/shared/src/main/assets/byd-hud-icons/0x12.png
deleted file mode 100644
index ae73021732..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x12.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x13.png b/shared/src/main/assets/byd-hud-icons/0x13.png
deleted file mode 100644
index 98c801261b..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x13.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x14.png b/shared/src/main/assets/byd-hud-icons/0x14.png
deleted file mode 100644
index d143f6c284..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x14.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x15.png b/shared/src/main/assets/byd-hud-icons/0x15.png
deleted file mode 100644
index e1dbbaf153..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x15.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x16.png b/shared/src/main/assets/byd-hud-icons/0x16.png
deleted file mode 100644
index 679a1b16a2..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x16.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x17.png b/shared/src/main/assets/byd-hud-icons/0x17.png
deleted file mode 100644
index be7eda78e0..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x17.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x18.png b/shared/src/main/assets/byd-hud-icons/0x18.png
deleted file mode 100644
index d8fcfc9f3c..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x18.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x19.png b/shared/src/main/assets/byd-hud-icons/0x19.png
deleted file mode 100644
index 7d375d6da3..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x19.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x1a.png b/shared/src/main/assets/byd-hud-icons/0x1a.png
deleted file mode 100644
index 7f7a279715..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x1a.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x1b.png b/shared/src/main/assets/byd-hud-icons/0x1b.png
deleted file mode 100644
index 97bfec4020..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x1b.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x1c.png b/shared/src/main/assets/byd-hud-icons/0x1c.png
deleted file mode 100644
index 8135c2b202..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x1c.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x1d.png b/shared/src/main/assets/byd-hud-icons/0x1d.png
deleted file mode 100644
index e8650fa807..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x1d.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x1e.png b/shared/src/main/assets/byd-hud-icons/0x1e.png
deleted file mode 100644
index a756de6b7a..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x1e.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x1f.png b/shared/src/main/assets/byd-hud-icons/0x1f.png
deleted file mode 100644
index 2244f69283..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x1f.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x2.png b/shared/src/main/assets/byd-hud-icons/0x2.png
deleted file mode 100644
index e84e40e0d7..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x2.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x20.png b/shared/src/main/assets/byd-hud-icons/0x20.png
deleted file mode 100644
index 5dc92b5734..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x20.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x21.png b/shared/src/main/assets/byd-hud-icons/0x21.png
deleted file mode 100644
index 471581a1df..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x21.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x22.png b/shared/src/main/assets/byd-hud-icons/0x22.png
deleted file mode 100644
index 9cf6033caf..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x22.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x23.png b/shared/src/main/assets/byd-hud-icons/0x23.png
deleted file mode 100644
index 4a967fa4c0..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x23.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x24.png b/shared/src/main/assets/byd-hud-icons/0x24.png
deleted file mode 100644
index bb338da995..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x24.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x25.png b/shared/src/main/assets/byd-hud-icons/0x25.png
deleted file mode 100644
index a85994d4ac..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x25.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x26.png b/shared/src/main/assets/byd-hud-icons/0x26.png
deleted file mode 100644
index 5aeb50ac46..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x26.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x27.png b/shared/src/main/assets/byd-hud-icons/0x27.png
deleted file mode 100644
index b4eb01ac5a..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x27.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x28.png b/shared/src/main/assets/byd-hud-icons/0x28.png
deleted file mode 100644
index 58de35db90..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x28.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x29.png b/shared/src/main/assets/byd-hud-icons/0x29.png
deleted file mode 100644
index 5589efc3ac..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x29.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x2a.png b/shared/src/main/assets/byd-hud-icons/0x2a.png
deleted file mode 100644
index 5b3bf7e090..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x2a.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x2b.png b/shared/src/main/assets/byd-hud-icons/0x2b.png
deleted file mode 100644
index 1541d02f26..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x2b.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x2c.png b/shared/src/main/assets/byd-hud-icons/0x2c.png
deleted file mode 100644
index 69a3fbfa4b..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x2c.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x2d.png b/shared/src/main/assets/byd-hud-icons/0x2d.png
deleted file mode 100644
index 7229664b77..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x2d.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x2e.png b/shared/src/main/assets/byd-hud-icons/0x2e.png
deleted file mode 100644
index f3f7277298..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x2e.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x2f.png b/shared/src/main/assets/byd-hud-icons/0x2f.png
deleted file mode 100644
index 17f10e356a..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x2f.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x3.png b/shared/src/main/assets/byd-hud-icons/0x3.png
deleted file mode 100644
index 5a3120546e..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x3.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x30.png b/shared/src/main/assets/byd-hud-icons/0x30.png
deleted file mode 100644
index 1c10907d6e..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x30.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x31.png b/shared/src/main/assets/byd-hud-icons/0x31.png
deleted file mode 100644
index 797b44f2ca..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x31.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x4.png b/shared/src/main/assets/byd-hud-icons/0x4.png
deleted file mode 100644
index 3c893dc696..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x4.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x7.png b/shared/src/main/assets/byd-hud-icons/0x7.png
deleted file mode 100644
index 3bb1668d46..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x7.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x8.png b/shared/src/main/assets/byd-hud-icons/0x8.png
deleted file mode 100644
index 0c8f9ef694..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x8.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0x9.png b/shared/src/main/assets/byd-hud-icons/0x9.png
deleted file mode 100644
index 2155a022fa..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0x9.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0xa.png b/shared/src/main/assets/byd-hud-icons/0xa.png
deleted file mode 100644
index ee459858f8..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0xa.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0xb.png b/shared/src/main/assets/byd-hud-icons/0xb.png
deleted file mode 100644
index bf86f575f0..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0xb.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0xc.png b/shared/src/main/assets/byd-hud-icons/0xc.png
deleted file mode 100644
index f115360573..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0xc.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0xd.png b/shared/src/main/assets/byd-hud-icons/0xd.png
deleted file mode 100644
index d00600cf85..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0xd.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0xe.png b/shared/src/main/assets/byd-hud-icons/0xe.png
deleted file mode 100644
index debf3115ed..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0xe.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/0xf.png b/shared/src/main/assets/byd-hud-icons/0xf.png
deleted file mode 100644
index 9610bd829f..0000000000
Binary files a/shared/src/main/assets/byd-hud-icons/0xf.png and /dev/null differ
diff --git a/shared/src/main/assets/byd-hud-icons/LICENSE-BYDMate.txt b/shared/src/main/assets/byd-hud-icons/LICENSE-BYDMate.txt
deleted file mode 100644
index d264e3f478..0000000000
--- a/shared/src/main/assets/byd-hud-icons/LICENSE-BYDMate.txt
+++ /dev/null
@@ -1,81 +0,0 @@
-BYDMate - Trip and Charge Tracker for BYD DiLink 5.0
-Copyright (C) 2026 AndyShaman (https://github.com/AndyShaman)
-
-Licensed under the PolyForm Noncommercial License 1.0.0.
-Required Notice: Copyright AndyShaman (https://github.com/AndyShaman/BYDMate)
-
----
-
-# Polyform Noncommercial License 1.0.0
-
-
-
-## Acceptance
-
-In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
-
-## Copyright License
-
-The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
-
-## Distribution License
-
-The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
-
-## Notices
-
-You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
-
-> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
-
-## Changes and New Works License
-
-The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
-
-## Patent License
-
-The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
-
-## Noncommercial Purposes
-
-Any noncommercial purpose is a permitted purpose.
-
-## Personal Uses
-
-Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
-
-## Noncommercial Organizations
-
-Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
-
-## Fair Use
-
-You may have "fair use" rights for the software under the law. These terms do not limit them.
-
-## No Other Rights
-
-These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
-
-## Patent Defense
-
-If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
-
-## Violations
-
-The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
-
-## No Liability
-
-***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
-
-## Definitions
-
-The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
-
-**You** refers to the individual or entity agreeing to these terms.
-
-**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
-
-**Your licenses** are all the licenses granted to you for the software under these terms.
-
-**Use** means anything you do with the software requiring one of your licenses.
diff --git a/shared/src/main/assets/byd-hud-icons/NOTICE.txt b/shared/src/main/assets/byd-hud-icons/NOTICE.txt
deleted file mode 100644
index c448a16392..0000000000
--- a/shared/src/main/assets/byd-hud-icons/NOTICE.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-BYD HUD maneuver icons were imported from AndyShaman/BYDMate, app/src/main/assets/navi/.
-Required Notice: Copyright AndyShaman (https://github.com/AndyShaman/BYDMate)
-PolyForm Noncommercial License 1.0.0: https://polyformproject.org/licenses/noncommercial/1.0.0/
-See LICENSE-BYDMate.txt. These assets are not relicensed under the application's code license.
-Upstream describes these as donor assets; original provenance is not independently established.
diff --git a/shared/src/main/java/com/shilapi/xcertplay/adb/AdbKeys.kt b/shared/src/main/java/com/shilapi/xcertplay/adb/AdbKeys.kt
deleted file mode 100644
index 612e8e585e..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/adb/AdbKeys.kt
+++ /dev/null
@@ -1,85 +0,0 @@
-package com.shilapi.xcertplay.adb
-
-import android.content.Context
-import java.io.File
-import java.math.BigInteger
-import java.nio.ByteBuffer
-import java.nio.ByteOrder
-import java.security.KeyFactory
-import java.security.KeyPair
-import java.security.KeyPairGenerator
-import java.security.PrivateKey
-import java.security.PublicKey
-import java.security.Signature
-import java.security.interfaces.RSAPublicKey
-import java.security.spec.PKCS8EncodedKeySpec
-import java.security.spec.X509EncodedKeySpec
-import java.util.Base64
-
-/** DiPlay's own ADB key: adbd remembers it after the driver approves it once. */
-object AdbKeys {
- private const val DIR = "adb"
- private const val PRIVATE = "adbkey.private"
- private const val PUBLIC = "adbkey.public"
- private const val KEY_BITS = 2048
- private const val NAME = " diplay@headunit"
-
- // ADB signs the token as if it were a SHA-1 digest: the host prepends SHA-1's DigestInfo header.
- private val SHA1_DIGEST_INFO = byteArrayOf(
- 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14,
- )
-
- /** Loads the key from app-private storage, or makes one on first use. */
- @Synchronized
- fun load(context: Context): KeyPair {
- val dir = File(context.noBackupFilesDir, DIR)
- val privateFile = File(dir, PRIVATE)
- val publicFile = File(dir, PUBLIC)
- runCatching {
- val factory = KeyFactory.getInstance("RSA")
- return KeyPair(
- factory.generatePublic(X509EncodedKeySpec(publicFile.readBytes())),
- factory.generatePrivate(PKCS8EncodedKeySpec(privateFile.readBytes())),
- )
- }
- val pair = KeyPairGenerator.getInstance("RSA").apply { initialize(KEY_BITS) }.generateKeyPair()
- dir.mkdirs()
- privateFile.writeBytes(pair.private.encoded)
- publicFile.writeBytes(pair.public.encoded)
- return pair
- }
-
- fun sign(token: ByteArray, key: PrivateKey): ByteArray =
- Signature.getInstance("NONEwithRSA").run {
- initSign(key)
- update(SHA1_DIGEST_INFO + token)
- sign()
- }
-
- /**
- * The public key as adbd stores it (AOSP android_pubkey): modulus size in words, n0inv = -1/n mod
- * 2^32, the modulus and R^2 mod n (R = 2^2048) as little-endian numbers, then the exponent;
- * Base64, a name and a NUL.
- */
- fun publicKeyMessage(key: PublicKey): ByteArray {
- val rsa = key as RSAPublicKey
- val n = rsa.modulus
- val words = KEY_BITS / 32
- val r32 = BigInteger.ONE.shiftLeft(32)
- val n0inv = r32.subtract(n.mod(r32).modInverse(r32))
- val rr = BigInteger.ONE.shiftLeft(2 * KEY_BITS).mod(n)
- val blob = ByteBuffer.allocate(8 + 2 * KEY_BITS / 8 + 4).order(ByteOrder.LITTLE_ENDIAN).apply {
- putInt(words)
- putInt(n0inv.toInt())
- put(littleEndian(n, KEY_BITS / 8))
- put(littleEndian(rr, KEY_BITS / 8))
- putInt(rsa.publicExponent.toInt())
- }.array()
- return (Base64.getEncoder().encodeToString(blob) + NAME + "\u0000").toByteArray(Charsets.UTF_8)
- }
-
- private fun littleEndian(value: BigInteger, size: Int): ByteArray {
- val bigEndian = value.toByteArray().takeLast(size) // drops BigInteger's sign byte
- return ByteArray(size) { index -> bigEndian.getOrElse(bigEndian.size - 1 - index) { 0 } }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/adb/AdbPacket.kt b/shared/src/main/java/com/shilapi/xcertplay/adb/AdbPacket.kt
deleted file mode 100644
index e97111cc9c..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/adb/AdbPacket.kt
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.shilapi.xcertplay.adb
-
-import java.io.EOFException
-import java.io.IOException
-import java.io.InputStream
-import java.nio.ByteBuffer
-import java.nio.ByteOrder
-
-/** One ADB message: a 24-byte little-endian header followed by its payload. */
-internal class AdbPacket(val command: Int, val arg0: Int, val arg1: Int, val payload: ByteArray) {
- fun encode(): ByteArray = ByteBuffer.allocate(HEADER_BYTES + payload.size).order(ByteOrder.LITTLE_ENDIAN).apply {
- putInt(command)
- putInt(arg0)
- putInt(arg1)
- putInt(payload.size)
- putInt(payload.sumOf { it.toInt() and 0xff }) // adbd before protocol 0x01000001 checks this sum
- putInt(command.inv())
- put(payload)
- }.array()
-
- companion object {
- const val CNXN = 0x4e584e43
- const val AUTH = 0x48545541
- const val OPEN = 0x4e45504f
- const val OKAY = 0x59414b4f
- const val CLSE = 0x45534c43
- const val WRTE = 0x45545257
- const val STLS = 0x534c5453
-
- const val VERSION = 0x01000000
- const val MAX_PAYLOAD = 256 * 1024
- const val AUTH_TOKEN = 1
- const val AUTH_SIGNATURE = 2
- const val AUTH_PUBLIC_KEY = 3
-
- private const val HEADER_BYTES = 24
-
- fun read(input: InputStream): AdbPacket {
- val header = ByteBuffer.wrap(readFully(input, HEADER_BYTES)).order(ByteOrder.LITTLE_ENDIAN)
- val command = header.int
- val arg0 = header.int
- val arg1 = header.int
- val length = header.int
- header.int // payload sum
- if (header.int != command.inv() || length !in 0..MAX_PAYLOAD) throw IOException("bad ADB header")
- return AdbPacket(command, arg0, arg1, readFully(input, length))
- }
-
- private fun readFully(input: InputStream, count: Int): ByteArray {
- val bytes = ByteArray(count)
- var offset = 0
- while (offset < count) {
- val read = input.read(bytes, offset, count - offset)
- if (read < 0) throw EOFException("ADB stream ended")
- offset += read
- }
- return bytes
- }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/adb/LocalAdb.kt b/shared/src/main/java/com/shilapi/xcertplay/adb/LocalAdb.kt
deleted file mode 100644
index 742d83daa4..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/adb/LocalAdb.kt
+++ /dev/null
@@ -1,133 +0,0 @@
-package com.shilapi.xcertplay.adb
-
-import java.io.Closeable
-import java.io.IOException
-import java.io.InputStream
-import java.io.OutputStream
-import java.net.InetSocketAddress
-import java.net.Socket
-import java.net.SocketTimeoutException
-import java.security.KeyPair
-
-/**
- * A shell on the head unit's own adbd ("ADB over network", 127.0.0.1:5555), for the few commands an
- * ordinary app may not run, such as switching the BYD cluster's navigation mode. Speaks the plain
- * ADB protocol (AOSP adb/protocol.txt); the TLS variant used by Android 11+ wireless debugging is
- * not supported.
- *
- * adbd trusts a key once the driver approves it in the car's "Allow debugging?" dialog. Only
- * [connect] with `mayAsk = true` offers the key for approval. Background use never does, so the
- * dialog cannot appear while driving.
- */
-class LocalAdb(
- private val key: KeyPair,
- private val host: String = "127.0.0.1",
- private val port: Int = 5555,
-) : Closeable {
- enum class Access { READY, NOT_APPROVED, UNREACHABLE, UNSUPPORTED }
-
- private var socket: Socket? = null
- private var input: InputStream? = null
- private var output: OutputStream? = null
- private var nextStreamId = 1
-
- @Synchronized
- fun connect(mayAsk: Boolean): Access {
- if (socket?.isClosed == false) return Access.READY
- return try {
- val address = InetSocketAddress(host, port)
- val opened = Socket().apply {
- connect(address, CONNECT_TIMEOUT_MS)
- soTimeout = READ_TIMEOUT_MS
- tcpNoDelay = true
- }
- socket = opened
- input = opened.getInputStream()
- output = opened.getOutputStream()
- send(AdbPacket(AdbPacket.CNXN, AdbPacket.VERSION, AdbPacket.MAX_PAYLOAD, "host::\u0000".toByteArray()))
- handshake(mayAsk).also { if (it != Access.READY) closeQuietly() }
- } catch (_: SocketTimeoutException) {
- closeQuietly()
- if (mayAsk) Access.NOT_APPROVED else Access.UNREACHABLE
- } catch (_: IOException) {
- closeQuietly()
- Access.UNREACHABLE
- }
- }
-
- /** Runs [command] in adbd's shell and returns its output, or null if the link failed. */
- @Synchronized
- fun shell(command: String): String? {
- if (socket?.isClosed != false && connect(mayAsk = false) != Access.READY) return null
- return try {
- val local = nextStreamId++
- send(AdbPacket(AdbPacket.OPEN, local, 0, "shell:$command\u0000".toByteArray()))
- var remote = 0
- var finished = false
- val text = StringBuilder()
- while (!finished) {
- val packet = receive()
- when {
- packet.command == AdbPacket.OKAY && packet.arg1 == local -> remote = packet.arg0
- packet.command == AdbPacket.WRTE && packet.arg1 == local -> {
- text.append(String(packet.payload, Charsets.UTF_8))
- send(AdbPacket(AdbPacket.OKAY, local, packet.arg0, ByteArray(0)))
- }
- packet.command == AdbPacket.CLSE && packet.arg1 == local -> {
- if (remote != 0) send(AdbPacket(AdbPacket.CLSE, local, remote, ByteArray(0)))
- finished = true
- }
- // A stream left over from an earlier, interrupted command: close it and move on.
- packet.command == AdbPacket.WRTE ->
- send(AdbPacket(AdbPacket.CLSE, packet.arg1, packet.arg0, ByteArray(0)))
- }
- }
- text.toString().trim()
- } catch (_: IOException) {
- closeQuietly()
- null
- }
- }
-
- @Synchronized
- override fun close() = closeQuietly()
-
- private fun handshake(mayAsk: Boolean): Access {
- var packet = receive()
- if (packet.command == AdbPacket.STLS) return Access.UNSUPPORTED
- if (packet.command == AdbPacket.CNXN) return Access.READY
- if (packet.command != AdbPacket.AUTH || packet.arg0 != AdbPacket.AUTH_TOKEN) return Access.UNREACHABLE
- send(AdbPacket(AdbPacket.AUTH, AdbPacket.AUTH_SIGNATURE, 0, AdbKeys.sign(packet.payload, key.private)))
- packet = receive()
- if (packet.command == AdbPacket.CNXN) return Access.READY
- if (!mayAsk) return Access.NOT_APPROVED
- // adbd did not know the key: offer it, which opens the approval dialog on the car's screen.
- send(AdbPacket(AdbPacket.AUTH, AdbPacket.AUTH_PUBLIC_KEY, 0, AdbKeys.publicKeyMessage(key.public)))
- socket?.soTimeout = APPROVAL_TIMEOUT_MS
- packet = receive()
- socket?.soTimeout = READ_TIMEOUT_MS
- return if (packet.command == AdbPacket.CNXN) Access.READY else Access.NOT_APPROVED
- }
-
- private fun send(packet: AdbPacket) {
- val out = output ?: throw IOException("not connected")
- out.write(packet.encode())
- out.flush()
- }
-
- private fun receive(): AdbPacket = AdbPacket.read(input ?: throw IOException("not connected"))
-
- private fun closeQuietly() {
- runCatching { socket?.close() }
- socket = null
- input = null
- output = null
- nextStreamId = 1
- }
-
- private companion object {
- const val CONNECT_TIMEOUT_MS = 2_000
- const val READ_TIMEOUT_MS = 5_000
- const val APPROVAL_TIMEOUT_MS = 60_000
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayConfig.kt b/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayConfig.kt
index a4fc278318..2d4d4702f1 100644
--- a/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayConfig.kt
+++ b/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayConfig.kt
@@ -38,7 +38,6 @@ data class AirPlayConfig(
val btMac: String,
val sourceVersion: String,
val main: AirPlayDisplayConfig,
- val cluster: AirPlayDisplayConfig? = null,
val rightHandDrive: Boolean = false,
val port: Int = 7000,
val entertainmentSampleRate: Int = 48000,
diff --git a/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayInfoPlist.kt b/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayInfoPlist.kt
index 2f7fadf4db..9d8012b053 100644
--- a/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayInfoPlist.kt
+++ b/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlayInfoPlist.kt
@@ -28,7 +28,6 @@ object AirPlayInfoPlist {
val displays = arrayListOf(
displayEntry(config.main, STREAM_TYPE_MAIN_SCREEN, MAIN_UUID),
)
- config.cluster?.let { displays.add(displayEntry(it, STREAM_TYPE_ALT_SCREEN, ALT_UUID)) }
val info = linkedMapOf(
"sourceVersion" to config.sourceVersion,
diff --git a/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlaySession.kt b/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlaySession.kt
index 05533fc116..a22a7ffdbd 100644
--- a/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlaySession.kt
+++ b/shared/src/main/java/com/shilapi/xcertplay/airplay/AirPlaySession.kt
@@ -73,10 +73,6 @@ class AirPlaySession(
internal var deviceBtMac = ""
internal val activeStreams = linkedSetOf()
- /** Counts the iPhone's cluster stream setups; 0 while no cluster stream is up. */
- @Volatile var clusterStream = 0
- private set
- private var clusterStreamSetups = 0
private val closed = AtomicBoolean(false)
private val notified = AtomicBoolean(false)
@@ -132,19 +128,6 @@ class AirPlaySession(
if (notified.compareAndSet(false, true)) listener.onSessionEnded(this)
}
- /**
- * Asks the iPhone to draw CarPlay's cluster UI on the alt screen (showUI with the display's URL,
- * then a keyframe) or to stop drawing it (stopUI). The stream stays up either way; CarKit handles
- * both as car-initiated commands for a screen UUID.
- */
- fun setClusterUiShown(shown: Boolean): Boolean {
- val uuid = AirPlayInfoPlist.ALT_UUID
- if (!shown) return sendCommand(mapOf("type" to "stopUI", "params" to mapOf("uuid" to uuid)))
- val url = config.cluster?.initialUrl ?: return false
- return sendCommand(mapOf("type" to "showUI", "params" to mapOf("uuid" to uuid, "url" to url))) &&
- sendCommand(mapOf("type" to "forceKeyFrame", "params" to mapOf("uuid" to uuid)))
- }
-
fun sendCommand(command: Map): Boolean = synchronized(eventWriteLock) {
sendCommandLocked(command)
}
@@ -518,7 +501,6 @@ class AirPlaySession(
debugLog("airplay screen stream type=$type dataPort=${port ?: "rejected"}")
if (port != null) {
activeStreams.add(type)
- if (type == STREAM_TYPE_ALT_SCREEN) clusterStream = ++clusterStreamSetups
result.add(linkedMapOf("type" to type, "dataPort" to port))
}
}
@@ -596,7 +578,6 @@ class AirPlaySession(
} else {
types.forEach { type -> if (activeStreams.remove(type)) media.onTeardown(this, type) }
}
- if (STREAM_TYPE_ALT_SCREEN !in activeStreams) clusterStream = 0
return RtspMessage.Response(status = 200)
}
@@ -770,7 +751,6 @@ internal fun setupEnabledFeatures(config: AirPlayConfig, proposed: List<*>?): Li
if (config.hevc) features.add("hevc")
features.add("iAPChannel")
features.add("viewAreas")
- if (config.cluster != null) features.add("altScreen")
if (config.videoInCar && proposed.orEmpty().contains(VideoInCar.FEATURE)) features.add(VideoInCar.FEATURE)
return features
}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/airplay/CarPlayClusterDisplay.kt b/shared/src/main/java/com/shilapi/xcertplay/airplay/CarPlayClusterDisplay.kt
deleted file mode 100644
index 860d89df22..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/airplay/CarPlayClusterDisplay.kt
+++ /dev/null
@@ -1,102 +0,0 @@
-package com.shilapi.xcertplay.airplay
-
-/**
- * CarPlay's instrument-cluster screen (stream type 111).
- *
- * The iPhone lists the cluster content it offers in its /info request (`altScreenURLs`); without
- * an initial URL it streams a black frame. The cluster has no input. Apple Maps keeps the car
- * position inside the safe area while the map still fills the panel, so the safe area is set to
- * the part of the panel the cluster leaves uncovered.
- */
-object CarPlayClusterDisplay {
- const val MAP_URL = "maps:/car/instrumentcluster/map"
-
- /**
- * What the dashboard shows: one of the cluster contents the iPhone lists in `altScreenURLs`.
- * On the tested car the turn card needed 0–5 kbit/s against 0.3–4 Mbit/s for the map, and
- * "instrumentcluster" drew the map with the turn card on it.
- */
- enum class Content(val url: String) {
- MAP(MAP_URL),
- TURN_CARD("maps:/car/instrumentcluster/instructioncard"),
- INSTRUMENTS("maps:/car/instrumentcluster"),
- }
-
- /**
- * Where the car marker goes, as percent of the panel (left, top, right, bottom). Measured on a
- * DiLink 5.0 cluster with a calibration grid. In "Full screen navi" BYD draws a status row,
- * turn/ADAS icons, the ADAS lane view (from x 68 %), speed and power readouts and a bottom band
- * over the map; "Small screen navi" crops the panel to a centre window of about x 31–68 %,
- * y 16–89 %. This centre area is clear in both modes, so no per-mode setting is needed.
- */
- val SAFE_AREA_PERCENT = AirPlayInsets(top = 16, bottom = 25, left = 35, right = 36)
-
- /** The driver can move the marker from that centre, in steps of 10 % of the panel. */
- const val MARKER_STEP_PERCENT = 10
- val horizontalSteps = -4..4 // negative = left
- val verticalSteps = -3..3 // negative = up
-
- /** Where the car marker lands, in percent of the panel (x from the left, y from the top). */
- fun markerPercent(horizontalStep: Int, verticalStep: Int): Pair {
- val area = SAFE_AREA_PERCENT
- val x = (area.left + 100 - area.right) / 2.0 + horizontalStep.coerceIn(horizontalSteps) * MARKER_STEP_PERCENT
- val y = (area.top + 100 - area.bottom) / 2.0 + verticalStep.coerceIn(verticalSteps) * MARKER_STEP_PERCENT
- return x.coerceIn(MARKER_MARGIN, 100 - MARKER_MARGIN) to y.coerceIn(MARKER_MARGIN, 100 - MARKER_MARGIN)
- }
-
- private const val MARKER_MARGIN = 5.0
-
- /**
- * Stream size in percent of the panel. The cluster scales the stream up, so a smaller stream
- * gives a larger map: 83 % is clearly larger and still sharp; 50 % was visibly blurry.
- */
- const val STREAM_SCALE_PERCENT = 83
- val scalePresets = listOf(100, STREAM_SCALE_PERCENT, 67)
-
- private const val WIDTH_PHYSICAL_MM = 292 // a 12.3-inch 8:3 cluster panel; Apple Maps ignores it here
- private const val FPS = 30
-
- fun config(
- widthPixels: Int,
- heightPixels: Int,
- scalePercent: Int = STREAM_SCALE_PERCENT,
- horizontalStep: Int = 0,
- verticalStep: Int = 0,
- content: Content = Content.MAP,
- ): AirPlayDisplayConfig {
- // Height rounds to a multiple of 8 and width follows it, so the panel's aspect is kept
- // (83 % of 1920x720 gives exactly 1600x600). The cluster scales the stream to the panel.
- val scale = scalePercent.coerceIn(25, 100)
- val height = roundTo8(heightPixels * scale / 100.0)
- val width = roundTo8(height * widthPixels.toDouble() / heightPixels)
- return AirPlayDisplayConfig(
- widthPixels = width,
- heightPixels = height,
- widthPhysicalMm = WIDTH_PHYSICAL_MM,
- heightPhysicalMm = Math.round(WIDTH_PHYSICAL_MM * height.toDouble() / width).toInt(),
- fps = FPS,
- primaryInputDevice = 0,
- features = 0,
- initialUrl = content.url,
- safeArea = safeArea(width, height, horizontalStep, verticalStep),
- safeAreaDrawOutside = true,
- )
- }
-
- // The safe area keeps its measured size around the marker and shrinks only where the marker
- // comes close to a panel edge, so the marker always sits at its centre.
- private fun safeArea(width: Int, height: Int, horizontalStep: Int, verticalStep: Int): AirPlayInsets {
- val area = SAFE_AREA_PERCENT
- val (x, y) = markerPercent(horizontalStep, verticalStep)
- val halfWidth = minOf((100 - area.left - area.right) / 2.0, x, 100 - x)
- val halfHeight = minOf((100 - area.top - area.bottom) / 2.0, y, 100 - y)
- return AirPlayInsets(
- top = (height * (y - halfHeight) / 100).toInt(),
- bottom = (height * (100 - y - halfHeight) / 100).toInt(),
- left = (width * (x - halfWidth) / 100).toInt(),
- right = (width * (100 - x - halfWidth) / 100).toInt(),
- )
- }
-
- private fun roundTo8(value: Double): Int = (Math.round(value / 8) * 8).toInt().coerceAtLeast(8)
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/airplay/CarPlayMediaButton.kt b/shared/src/main/java/com/shilapi/xcertplay/airplay/CarPlayMediaButton.kt
index 616a71c344..1234f2a4c0 100644
--- a/shared/src/main/java/com/shilapi/xcertplay/airplay/CarPlayMediaButton.kt
+++ b/shared/src/main/java/com/shilapi/xcertplay/airplay/CarPlayMediaButton.kt
@@ -5,8 +5,8 @@ import android.view.KeyEvent
/**
* Hardware media keys → CarPlay media HID presses (indices into [AirPlayHid]'s media report).
*
- * Hardware play and pause keys both map to the toggle: BYD picks PLAY or PAUSE from its own idea of
- * the play state, and a wrong guess would make the button do nothing. Explicit play and pause
+ * Hardware play and pause keys both map to the toggle: a head unit may pick PLAY or PAUSE from its own
+ * idea of the play state, and a wrong guess would make the button do nothing. Explicit play and pause
* commands from media controllers use [PLAY] and [PAUSE].
*/
object CarPlayMediaButton {
@@ -16,19 +16,8 @@ object CarPlayMediaButton {
const val NEXT = 4
const val PREVIOUS = 5
- /** BYD's steering-wheel play/pause key; the firmware normally rewrites it to MEDIA_PLAY/PAUSE. */
- const val KEYCODE_BYD_AUTO_MEDIA_PLAY_PAUSE = 353
-
- /** BYD's steering-wheel voice key: a short press, and the code the wheel sends for a long press. */
- const val KEYCODE_BYD_AUTO_MEDIA_VOICE = 304
- const val KEYCODE_BYD_AUTO_MEDIA_VOICE_LONG = 312
-
- /**
- * Whether [keyCode] is a voice key that opens Siri. The BYD wheel sends each press as an
- * instant down/up pair, so a long press arrives as its own key rather than as a held one.
- */
- fun opensSiri(keyCode: Int): Boolean = keyCode == KeyEvent.KEYCODE_VOICE_ASSIST ||
- keyCode == KEYCODE_BYD_AUTO_MEDIA_VOICE || keyCode == KEYCODE_BYD_AUTO_MEDIA_VOICE_LONG
+ /** Whether [keyCode] is a voice key that opens Siri. */
+ fun opensSiri(keyCode: Int): Boolean = keyCode == KeyEvent.KEYCODE_VOICE_ASSIST
/** The CarPlay press for [keyCode], or null when the key is not a media key CarPlay handles. */
fun forKeyCode(keyCode: Int): Int? = when (keyCode) {
@@ -37,8 +26,7 @@ object CarPlayMediaButton {
KeyEvent.KEYCODE_MEDIA_PLAY,
KeyEvent.KEYCODE_MEDIA_PAUSE,
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
- KeyEvent.KEYCODE_HEADSETHOOK,
- KEYCODE_BYD_AUTO_MEDIA_PLAY_PAUSE -> PLAY_PAUSE
+ KeyEvent.KEYCODE_HEADSETHOOK -> PLAY_PAUSE
else -> null
}
}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydAdbAccess.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydAdbAccess.kt
deleted file mode 100644
index 8d036a4ef3..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydAdbAccess.kt
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import com.shilapi.xcertplay.adb.AdbKeys
-import com.shilapi.xcertplay.adb.LocalAdb
-
-/** What the settings page shows about the ADB link that DiPlay's optional BYD features need. */
-object BydAdbAccess {
- enum class State { READY, NOT_APPROVED, ADB_OFF, PAIRING_ONLY }
-
- class Status(
- val state: State,
- val dashboardMode: BydClusterNaviMode? = null,
- val dashboardShowsMap: Boolean = true,
- val batteryPercent: Double? = null,
- val rangeKm: Int? = null,
- )
-
- /** Blocking: run off the main thread. [mayAsk] lets the car show its approval dialog for DiPlay's key. */
- fun check(context: Context, mayAsk: Boolean): Status {
- LocalAdb(AdbKeys.load(context)).use { adb ->
- val state = when (adb.connect(mayAsk)) {
- LocalAdb.Access.READY -> State.READY
- LocalAdb.Access.NOT_APPROVED -> State.NOT_APPROVED
- LocalAdb.Access.UNREACHABLE -> State.ADB_OFF
- LocalAdb.Access.UNSUPPORTED -> State.PAIRING_ONLY
- }
- if (state != State.READY) return Status(state)
- return readStatus(context, adb::shell)
- }
- }
-
- /** Read and publish the same battery data that the settings page reports as ready. */
- internal fun readStatus(context: Context, shell: (String) -> String?): Status {
- val mode = BydClusterNaviMode.parseRead(shell(BydClusterNaviMode.READ_COMMAND))
- val battery = BydBattery.read(shell)
- battery?.let { BydBatteryStatus.accept(context, it) }
- return Status(State.READY, mode, mode?.showsMap != false, battery?.percent, battery?.rangeKm)
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydAdbShell.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydAdbShell.kt
deleted file mode 100644
index 3c90761e66..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydAdbShell.kt
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import android.os.SystemClock
-import android.util.Log
-import com.shilapi.xcertplay.adb.AdbKeys
-import com.shilapi.xcertplay.adb.LocalAdb
-
-/**
- * A lazily opened adb shell on the head unit for background reads. It never asks for approval, so
- * the car's dialog cannot appear while driving; a refused or missing adbd is retried every 30 s.
- */
-internal class BydAdbShell(private val tag: String) {
- private var adb: LocalAdb? = null
- private var retryAtMillis = 0L
- private var unavailableLogged = false
-
- @Synchronized
- fun run(context: Context, command: String): String? {
- val now = SystemClock.elapsedRealtime()
- if (now < retryAtMillis) return null
- val client = adb ?: LocalAdb(AdbKeys.load(context)).also { adb = it }
- val access = client.connect(mayAsk = false)
- if (access != LocalAdb.Access.READY) {
- retryAtMillis = now + RETRY_MILLIS
- if (!unavailableLogged) {
- unavailableLogged = true
- Log.w(tag, "ADB access $access")
- }
- return null
- }
- unavailableLogged = false
- return client.shell(command)
- }
-
- @Synchronized
- fun close() {
- adb?.close()
- adb = null
- }
-
- private companion object {
- const val RETRY_MILLIS = 30_000L
- }
-}
-
-/** Reads `service call` replies such as `Result: Parcel(00000000 00000002 '........')`. */
-internal object BydParcel {
- /** The value after a zero exception code, as its 32 raw bits. */
- fun value(output: String?): Int? {
- val words = words(output)
- if (words.size < 2 || words[0] != 0L) return null
- return words[1].toInt()
- }
-
- fun words(output: String?): List {
- val body = output?.substringAfter("Parcel(", "")?.substringBefore('\'') ?: return emptyList()
- return body.trim().split(Regex("\\s+")).mapNotNull { word ->
- word.takeIf { it.length == 8 }?.toLongOrNull(16)
- }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydBattery.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydBattery.kt
deleted file mode 100644
index ff21948f3f..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydBattery.kt
+++ /dev/null
@@ -1,151 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import android.util.Log
-import android.os.SystemClock
-import com.shilapi.xcertplay.transport.VehicleStatusProvider
-import com.shilapi.xcertplay.transport.VehicleStatusSnapshot
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-import kotlin.math.roundToInt
-import kotlin.math.roundToLong
-
-/** The traction battery as BYD's statistic, power and charging devices report it. */
-internal data class BydBatteryReading(
- val percent: Double,
- val rangeKm: Int,
- val remainingKwh: Double,
- val charging: Boolean,
-)
-
-/**
- * Reads the traction battery through the adb shell (autoservice binder), where apps would need a BYD
- * signature. Verified on DiLink 5.0 (Android 12); the percentage and remaining-energy ids follow
- * BYDMate's validated map, the range id is Statistic.ELEC_DRIVING_RANGE for this platform.
- */
-internal object BydBattery {
- private const val PERCENT = "service call autoservice 7 i32 1014 i32 1246777400" // float %
- private const val RANGE = "service call autoservice 5 i32 1014 i32 1246765118" // km
- private const val REMAINING = "service call autoservice 7 i32 1005 i32 882901008" // float kWh
- private const val BMS_STATE = "service call autoservice 5 i32 1009 i32 876609560" // 1 = charging
- private const val BMS_CHARGING = 1
-
- /** One reading, or null when any value is missing or outside what a battery can report. */
- fun read(shell: (String) -> String?): BydBatteryReading? {
- val percent = BydParcel.value(shell(PERCENT))?.let(::float)?.takeIf { it in 0.0..100.0 } ?: return null
- val range = BydParcel.value(shell(RANGE))?.takeIf { it in 0..3000 } ?: return null
- val remaining = BydParcel.value(shell(REMAINING))?.let(::float)?.takeIf { it in 0.0..300.0 } ?: return null
- val bms = BydParcel.value(shell(BMS_STATE))
- return BydBatteryReading(percent, range, remaining, bms == BMS_CHARGING)
- }
-
- /**
- * What the iPhone gets. Full charge and full range are scaled up from the current values; below
- * 20 % the rounding of the percentage would make that scale jumpy, so [fullKwh] from an earlier,
- * higher reading is used when there is one.
- */
- fun snapshot(reading: BydBatteryReading, lowPercent: Int, fullKwh: Double?): VehicleStatusSnapshot {
- val fraction = reading.percent / 100
- val full = fullKwh ?: if (fraction > 0) reading.remainingKwh / fraction else reading.remainingKwh
- return VehicleStatusSnapshot(
- rangeKm = reading.rangeKm,
- rangeWarning = reading.percent <= lowPercent,
- batteryPercent = reading.percent,
- currentChargeWh = (reading.remainingKwh * 1000).roundToLong(),
- maxChargeWh = (full * 1000).roundToLong(),
- maxRangeKm = if (fraction > 0) (reading.rangeKm / fraction).roundToInt() else reading.rangeKm,
- charging = reading.charging,
- )
- }
-
- /** A full-charge estimate from [reading], when the percentage is high enough to trust it. */
- fun fullKwh(reading: BydBatteryReading): Double? =
- if (reading.percent >= 20) reading.remainingKwh / (reading.percent / 100) else null
-
- private fun float(bits: Int): Double = java.lang.Float.intBitsToFloat(bits).toDouble()
-}
-
-/**
- * Optional, needs ADB over network: tells the iPhone the car's charge and range, so Apple Maps can
- * warn about a low charge and suggest chargers. Reads the battery every 30 s while the iPhone asks
- * for vehicle status; the iAP2 loop only takes the last reading, so it never waits for adb.
- */
-internal object BydBatteryStatus : VehicleStatusProvider {
- private const val TAG = "DiPlay-BYD-Battery"
- private const val READ_MILLIS = 30_000L
- private const val IDLE_MILLIS = 2 * 60_000L
-
- private val shell = BydAdbShell(TAG)
- @Volatile private var context: Context? = null
- private var started = false
- private val cache = BydBatteryCache(::now)
- @Volatile internal var readBattery: (Context) -> BydBatteryReading? = { app ->
- BydBattery.read { shell.run(app, it) }
- }
- private val executor = Executors.newSingleThreadScheduledExecutor { runnable ->
- Thread(runnable, "diplay-battery").apply { isDaemon = true }
- }
- @Volatile private var askedMillis = 0L
-
- @Synchronized
- fun start(appContext: Context) {
- context = appContext.applicationContext
- askedMillis = now()
- if (started) {
- // A reconnect after idle must not wait for the next 30-second tick.
- executor.execute(::poll)
- } else {
- started = true
- executor.scheduleWithFixedDelay(::poll, 0, READ_MILLIS, TimeUnit.MILLISECONDS)
- }
- }
-
- override fun snapshot(): VehicleStatusSnapshot? {
- askedMillis = now()
- val app = context ?: return null
- return cache.snapshot(BydOutputSettings.lowChargePercent(app))
- }
-
- private fun poll() {
- val app = context ?: return
- // Nobody asked for a while: the session ended. Keep adb closed until the next one.
- if (now() - askedMillis > IDLE_MILLIS) return shell.close()
- val reading = readBattery(app) ?: return
- accept(app, reading)
- }
-
- /** Publish a settings check before telling the user that the battery is ready. No ADB I/O. */
- fun accept(appContext: Context, reading: BydBatteryReading) {
- context = appContext.applicationContext
- if (cache.accept(reading)) {
- Log.i(TAG, "battery ${reading.percent} % range ${reading.rangeKm} km ${reading.remainingKwh} kWh charging=${reading.charging}")
- }
- }
-
- private fun now() = SystemClock.elapsedRealtime()
-}
-
-/** Atomically publishes the reading, timestamp and capacity estimate across both ADB readers. */
-internal class BydBatteryCache(private val now: () -> Long) {
- private var latest: BydBatteryReading? = null
- private var latestMillis = 0L
- private var fullKwh: Double? = null
-
- @Synchronized
- fun accept(reading: BydBatteryReading): Boolean {
- val changed = latest?.let {
- it.percent.roundToInt() != reading.percent.roundToInt() || it.charging != reading.charging
- } != false
- BydBattery.fullKwh(reading)?.let { fullKwh = it }
- latest = reading
- latestMillis = now()
- return changed
- }
-
- @Synchronized
- fun snapshot(lowPercent: Int): VehicleStatusSnapshot? {
- val reading = latest ?: return null
- if (now() - latestMillis > 3 * 60_000L) return null
- return BydBattery.snapshot(reading, lowPercent, fullKwh)
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterBridge.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterBridge.kt
deleted file mode 100644
index a06316d950..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterBridge.kt
+++ /dev/null
@@ -1,156 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import android.content.Intent
-import android.content.pm.PackageManager
-import android.util.Log
-import com.shilapi.xcertplay.iap2.wire.Iap2Frame
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-
-/**
- * Publishes CarPlay arrows and distance to the BYD instrument cluster through the stock
- * AMap adapter (com.byd.amapservice), independently of the SOME/IP windshield HUD path.
- */
-internal object BydClusterBridge {
- private const val TAG = "DiPlay-BYD-Cluster"
- private const val AMAP_PACKAGE = "com.byd.amapservice"
- private const val AMAP_ACTION = "AUTONAVI_STANDARD_BROADCAST_SEND"
- private const val KEY_GUIDANCE = 10001
- private const val KEY_STATE = 10019
- private const val STATE_ENDED = 9
- private const val KEEPALIVE_TICKS = 5
- private const val FLAG_RECEIVER_INCLUDE_BACKGROUND = 0x01000000 // hidden Intent flag, as sent by stock clients
-
- private val lock = Any()
- private val route = BydHudRouteState()
- private var context: Context? = null
- private var available = false
- private var factory: BydFactoryNavigationOutput? = null
- private var senderStarted = false
- private var lastSent: BydClusterFrame? = null
- private var ticksSinceSend = 0
- private var guidanceLogged = false
-
- fun initialize(appContext: Context) = synchronized(lock) {
- if (context != null) return@synchronized
- context = appContext.applicationContext
- available = try {
- appContext.packageManager.getPackageInfo(AMAP_PACKAGE, 0)
- true
- } catch (_: PackageManager.NameNotFoundException) {
- false
- }
- if (!available && appContext.packageName.endsWith(".hudtest")) {
- factory = BydFactoryNavigationOutput(appContext.applicationContext)
- available = true
- }
- Log.i(TAG, "cluster adapter available=$available factoryTest=${factory != null}")
- if (available && !senderStarted) {
- senderStarted = true
- Executors.newSingleThreadScheduledExecutor { runnable ->
- Thread(runnable, "diplay-byd-cluster").apply { isDaemon = true }
- }.scheduleAtFixedRate(::tick, 1, 1, TimeUnit.SECONDS)
- }
- }
-
- fun onFrame(frame: Iap2Frame) = synchronized(lock) {
- if (!available) return@synchronized
- when (route.accept(frame.messageId, frame.payload)) {
- BydHudRouteChange.GUIDANCE -> sendCurrentLocked(force = false)
- BydHudRouteChange.CLEAR -> if (lastSent != null) sendEndLocked()
- BydHudRouteChange.NONE -> Unit
- }
- }
-
- fun clear() = synchronized(lock) {
- route.clear() // Prevent the keepalive from restoring guidance after cleanup.
- if (available && lastSent != null) sendEndLocked()
- }
-
- private fun tick() = synchronized(lock) {
- // Guidance can expire without a frame (a list that stays empty), so check every second.
- if (lastSent != null && route.currentApple() == null) sendEndLocked()
- else if (++ticksSinceSend >= KEEPALIVE_TICKS) sendCurrentLocked(force = true)
- }
-
- private fun sendCurrentLocked(force: Boolean) {
- if (context?.let(BydOutputSettings::enabled) != true) {
- if (lastSent != null) sendEndLocked()
- return
- }
- val frame = route.currentApple()?.let(BydClusterFrame::from)
- if (frame == null) {
- if (lastSent != null) sendEndLocked()
- return
- }
- if (!force && frame == lastSent) return
- factory?.let {
- it.update(frame.icon, frame.roundaboutExit, frame.distanceMeters)
- lastSent = frame
- ticksSinceSend = 0
- return
- }
- val intent = baseIntent(KEY_GUIDANCE).apply {
- putExtra("TYPE", 0)
- putExtra("EXTRA_STATE", 0)
- putExtra("EXTRA_IS_FOREGROUND", 0)
- putExtra("NEW_ICON", frame.icon)
- putExtra("ROUNG_ABOUT_NUM", frame.roundaboutExit)
- putExtra("SEG_REMAIN_DIS", frame.distanceMeters)
- putExtra("NEXT_ROAD_NAME", frame.road)
- putExtra("ROUTE_REMAIN_DIS", frame.routeRemainingMeters)
- putExtra("ROUTE_REMAIN_TIME", frame.routeRemainingSeconds)
- }
- if (broadcastLocked(intent)) {
- lastSent = frame
- ticksSinceSend = 0
- if (!guidanceLogged) {
- guidanceLogged = true
- Log.i(TAG, "cluster guidance sent $frame")
- }
- }
- }
-
- private fun sendEndLocked() {
- factory?.let {
- it.clear()
- lastSent = null
- guidanceLogged = false
- return
- }
- val intent = baseIntent(KEY_STATE).apply {
- putExtra("EXTRA_STATE", STATE_ENDED)
- putExtra("EXTRA_IS_FOREGROUND", 1)
- putExtra("NEW_ICON", -1)
- putExtra("SEG_REMAIN_DIS", -1)
- putExtra("NEXT_ROAD_NAME", "")
- putExtra("ROUTE_REMAIN_DIS", -1)
- putExtra("ROUTE_REMAIN_TIME", -1)
- }
- if (!broadcastLocked(intent)) return
- lastSent = null
- guidanceLogged = false
- Log.i(TAG, "cluster guidance ended")
- }
-
- // IS_BYD_MAP=true is required: the adapter drops foreign frames while it believes the stock map navigates.
- private fun baseIntent(keyType: Int) = Intent(AMAP_ACTION).apply {
- setPackage(AMAP_PACKAGE)
- addFlags(FLAG_RECEIVER_INCLUDE_BACKGROUND)
- putExtra("KEY_TYPE", keyType)
- putExtra("IS_BYD_MAP", true)
- putExtra("IS_BYD_BAIDU_MAP", false)
- }
-
- private fun broadcastLocked(intent: Intent): Boolean {
- val appContext = context ?: return false
- return try {
- appContext.sendBroadcast(intent)
- true
- } catch (error: RuntimeException) {
- Log.w(TAG, "cluster broadcast failed", error)
- false
- }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterFrame.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterFrame.kt
deleted file mode 100644
index 76af981e09..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterFrame.kt
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/** One instrument-cluster frame in the AMap broadcast vocabulary accepted by com.byd.amapservice. */
-internal data class BydClusterFrame(
- val icon: Int,
- val roundaboutExit: Int,
- val distanceMeters: Int,
- val road: String = "",
- val routeRemainingMeters: Int = -1,
- val routeRemainingSeconds: Int = -1,
-) {
- companion object {
- private const val LEFT = 2
- private const val RIGHT = 3
- private const val SLIGHT_LEFT = 4
- private const val SLIGHT_RIGHT = 5
- private const val SHARP_LEFT = 6
- private const val SHARP_RIGHT = 7
- private const val U_TURN_LEFT = 8
- private const val STRAIGHT = 9
- private const val ROUNDABOUT_ENTER = 11
- private const val ROUNDABOUT_EXIT = 12
- private const val DESTINATION = 15
- private const val ROUNDABOUT_ENTER_CLOCKWISE = 17
- private const val ROUNDABOUT_EXIT_CLOCKWISE = 18
- private const val U_TURN_RIGHT = 19
-
- /** Apple iAP2 RouteGuidanceManeuverType -> AMap NEW_ICON (+ ROUNG_ABOUT_NUM). */
- fun from(maneuver: BydAppleManeuver): BydClusterFrame {
- val leftHandTraffic = maneuver.drivingSide == 1
- val distance = maneuver.distanceMeters.coerceAtLeast(0)
- val type = maneuver.type
- val road = maneuver.road
- val remainingMeters = maneuver.remainingMeters?.coerceIn(0, Int.MAX_VALUE.toLong())?.toInt() ?: -1
- val remainingSeconds = maneuver.remainingSeconds?.coerceIn(0, Int.MAX_VALUE.toLong())?.toInt() ?: -1
- if (type in 28..46) {
- val icon = if (leftHandTraffic) ROUNDABOUT_ENTER_CLOCKWISE else ROUNDABOUT_ENTER
- return BydClusterFrame(icon, type - 27, distance, road, remainingMeters, remainingSeconds)
- }
- val icon = when (type) {
- 1, 20 -> LEFT
- 2, 21 -> RIGHT
- 47 -> SHARP_LEFT
- 48 -> SHARP_RIGHT
- 13, 22, 49, 52 -> SLIGHT_LEFT
- 14, 23, 50, 53 -> SLIGHT_RIGHT
- 4, 18, 19, 26 -> if (leftHandTraffic) U_TURN_RIGHT else U_TURN_LEFT
- 6 -> if (leftHandTraffic) ROUNDABOUT_ENTER_CLOCKWISE else ROUNDABOUT_ENTER
- 7 -> if (leftHandTraffic) ROUNDABOUT_EXIT_CLOCKWISE else ROUNDABOUT_EXIT
- 10, 12, 24, 25, 27 -> DESTINATION
- 3, 5, 8, 9, 11, 51 -> STRAIGHT
- else -> 0 // Unknown/no maneuver must not become a false straight arrow.
- }
- return BydClusterFrame(icon, 0, distance, road, remainingMeters, remainingSeconds)
- }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterMapPause.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterMapPause.kt
deleted file mode 100644
index 27f0c1c8cd..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterMapPause.kt
+++ /dev/null
@@ -1,67 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import android.util.Log
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.atomic.AtomicBoolean
-
-/**
- * Optional, needs ADB over network: the iPhone draws and streams the cluster map for the whole
- * session, but the cluster shows it only in Small and Full screen navi. DiPlay reads the mode the
- * driver picked on the wheel every second and asks the iPhone to stop drawing the map while the
- * cluster hides it (Off, Turn on by navi, where it shows arrows only), and to draw it again when the
- * driver picks Small or Full. Without ADB access, or when the mode cannot be read, the map streams
- * as before.
- */
-internal object BydClusterMapPause {
- private const val TAG = "DiPlay-BYD-ClusterMap"
- private const val READ_MILLIS = 1_000L
-
- private val tickerStarted = AtomicBoolean(false)
- private val shell = BydAdbShell(TAG)
- @Volatile private var context: Context? = null
-
- // Only the ticker thread touches this, so nothing blocking ever runs under a lock that
- // initialize() or the UI needs.
- private var lastMode: BydClusterNaviMode? = null
-
- /** Whether DiPlay's map window is on the cluster. */
- @Volatile var clusterMapShown = false
-
- /** The running CarPlay session, told every second whether the iPhone should draw the cluster map. */
- @Volatile var streamControl: ((Boolean) -> Unit)? = null
-
- /** Reads the mode over adb. Blocking, and only called on the ticker thread; tests replace it. */
- @Volatile internal var readMode: (Context) -> BydClusterNaviMode? = { app ->
- BydClusterNaviMode.parseRead(shell.run(app, BydClusterNaviMode.READ_COMMAND))
- }
-
- /** Never waits for the ticker: an adb read in flight does not hold up opening or reconnecting. */
- fun initialize(appContext: Context) {
- context = appContext.applicationContext
- if (tickerStarted.compareAndSet(false, true)) {
- Executors.newSingleThreadScheduledExecutor { runnable ->
- Thread(runnable, "diplay-cluster-map").apply { isDaemon = true }
- }.scheduleAtFixedRate(::tick, READ_MILLIS, READ_MILLIS, TimeUnit.MILLISECONDS)
- }
- }
-
- private fun tick() {
- val app = context ?: return
- val control = streamControl
- if (control == null || !clusterMapShown || !BydOutputSettings.clusterStreamPause(app)) {
- control?.invoke(true)
- shell.close()
- lastMode = null
- return
- }
- val mode = readMode(app)
- if (mode != lastMode) {
- lastMode = mode
- Log.i(TAG, "cluster mode ${mode?.label ?: "unknown"}")
- }
- // An unknown mode keeps the map streaming, as without ADB.
- control(mode?.showsMap != false)
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterNaviMode.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterNaviMode.kt
deleted file mode 100644
index 8f9ea24e52..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydClusterNaviMode.kt
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/**
- * The cluster's navigation mode, the one the driver picks in the steering-wheel menu. BYD keeps it
- * in instrument property INSTRUMENT_NAVI_TYPE; apps need a BYD signature for it, the adb shell
- * reads it through the autoservice binder. Verified on DiLink 5.0 (Android 12).
- */
-enum class BydClusterNaviMode(val code: Int, val label: String) {
- OFF(1, "Off"),
- TURN_ON_BY_NAVI(2, "Turn on by navi"),
- SMALL(3, "Small screen navi"),
- FULL(4, "Full screen navi");
-
- /** Small and Full screen navi show the projection (DiPlay's map); Off and Turn on by navi do not. */
- val showsMap: Boolean get() = this == SMALL || this == FULL
-
- companion object {
- private const val INSTRUMENT_DEVICE = 1007
- private const val NAVI_TYPE_GET = 0x40C03032
- private const val GET_INT = 5
-
- const val READ_COMMAND = "service call autoservice $GET_INT i32 $INSTRUMENT_DEVICE i32 $NAVI_TYPE_GET"
-
- fun fromCode(code: Int): BydClusterNaviMode? = entries.firstOrNull { it.code == code }
-
- /** `Result: Parcel(00000000 00000002 '........')`: no exception, then the value. */
- fun parseRead(output: String?): BydClusterNaviMode? = BydParcel.value(output)?.let(::fromCode)
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydFactoryNavigationOutput.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydFactoryNavigationOutput.kt
deleted file mode 100644
index 2ca37cc89d..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydFactoryNavigationOutput.kt
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import android.util.Log
-import java.lang.reflect.InvocationTargetException
-
-/** Temporary HUD-test output using the installed factory SDK and the app's own identity. */
-internal class BydFactoryNavigationOutput(private val context: Context) {
- private var device: Any? = null
- private var disabled = false
- private var showing = false
- private var logged = false
-
- fun update(icon: Int, exit: Int, distance: Int) {
- if (disabled || !context.packageName.endsWith(".bydhudtest") && !context.packageName.endsWith(".hudtest")) return
- val turn = BydFactoryTurnCode.map(icon, exit) ?: run { clear(); return }
- if (distance !in 0..16777214) { clear(); return }
- try {
- val sdk = device ?: Class.forName("android.hardware.bydauto.instrument.BYDAutoInstrumentDevice")
- .getMethod("getInstance", Context::class.java).invoke(null, context).also { device = it }
- if (!showing) {
- checkResult("start", sdk.javaClass.getMethod("sendAutoNaviStatus", Int::class.javaPrimitiveType).invoke(sdk, 2))
- showing = true
- }
- val idsClass = Class.forName("android.hardware.bydauto.BYDAutoFeatureIds\$Instrument")
- val ids = arrayOf("INSTRUMENT_FRONT_CROSSING_DISTANCE_SET", "INSTRUMENT_GUIDE_INFO_SIMPLE_SET", "INSTRUMENT_GUIDE_INFO_AND_ROAD_AHEAD_DISTANCE_SET")
- .map { idsClass.getField(it).getInt(null) }.toIntArray()
- val valueClass = Class.forName("android.hardware.bydauto.BYDAutoEventValue")
- val value = valueClass.getConstructor().newInstance()
- valueClass.getField("intArrayValue").set(value, intArrayOf(distance, turn, turn))
- checkResult("guidance", sdk.javaClass.getMethod("set", IntArray::class.java, valueClass).invoke(sdk, ids, value))
- if (!logged) {
- Log.i(TAG, "Factory navigation accepted turn=$turn distance=$distance; visible HUD output unconfirmed")
- logged = true
- }
- } catch (error: Exception) {
- // If start succeeded but guidance failed, end our own navigation state once.
- clear()
- disabled = true
- val cause = (error as? InvocationTargetException)?.targetException ?: error
- Log.w(TAG, "Factory navigation disabled: ${cause.javaClass.simpleName}: ${cause.message}")
- }
- }
-
- fun clear() {
- if (!showing) return
- showing = false
- logged = false
- try {
- val sdk = device ?: return
- checkResult("end", sdk.javaClass.getMethod("sendAutoNaviStatus", Int::class.javaPrimitiveType).invoke(sdk, 1))
- Log.i(TAG, "Factory navigation ended")
- } catch (error: Exception) {
- disabled = true
- val cause = (error as? InvocationTargetException)?.targetException ?: error
- Log.w(TAG, "Factory navigation cleanup failed: ${cause.message}")
- }
- }
-
- private fun checkResult(operation: String, result: Any?) {
- check(result == 0) { "$operation returned $result" }
- }
-
- companion object { private const val TAG = "BYD-Factory-Navi" }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydFactoryTurnCode.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydFactoryTurnCode.kt
deleted file mode 100644
index c9ef9f751e..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydFactoryTurnCode.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/** Factory navigation's NEW_ICON -> instrument code mapping, verified against installed firmware. */
-internal object BydFactoryTurnCode {
- private val codes = intArrayOf(0, 0, 1, 2, 3, 5, 7, 8, 9, 11, 45, 13, 24, 46, 47, 48, 49, 14, 23, 10, 12, 15, 18, 20, 22, 16, 17, 19, 21)
- fun map(icon: Int, exit: Int): Int? {
- if (icon !in 2..28) return null
- if (exit in 1..10) {
- if (icon == 11 || icon == 12) return exit + 24
- if (icon == 17 || icon == 18) return exit + 34
- }
- return codes[icon]
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudBridge.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudBridge.kt
deleted file mode 100644
index 05df27aaa2..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudBridge.kt
+++ /dev/null
@@ -1,259 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.ComponentName
-import android.content.Context
-import android.content.Intent
-import android.content.ServiceConnection
-import android.os.Binder
-import android.os.IBinder
-import android.os.Parcel
-import android.util.Log
-import com.shilapi.xcertplay.iap2.wire.Iap2Frame
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-
-/** Publishes CarPlay route arrows, distance and street to BYD's native windshield HUD. */
-internal object BydHudBridge {
- private const val TAG = "DiPlay-BYD-HUD"
- private const val SOMEIP_PACKAGE = "com.ts.car.someip.service"
- private const val SOMEIP_CLASS = "com.ts.car.someip.service.manager.SomeIpServerService"
- private const val SOMEIP_ACTION = "com.ts.car.someip.SomeIpServerService"
- private const val SOMEIP_TOKEN = "ts.car.someip.sdk.ISomeIpServerInterface"
- private const val CALLBACK_TOKEN = "ts.car.someip.sdk.ISomeIpCallback"
- private const val SERVICE_ID = BydHudProtocol.SERVICE_TOPIC
- private const val HUD_TOPIC = BydHudProtocol.NAVIGATION_TOPIC
- private const val TX_REGISTER_CALLBACK = 1
- private const val TX_START_SERVICE = 4
- private const val TX_FIRE_EVENT = 6
- private const val ICON_ASSET_DIR = "byd-hud-icons"
-
- private val callbacks = Executors.newSingleThreadExecutor { task ->
- Thread(task, "diplay-hud-callback").apply { isDaemon = true }
- }
- private val lock = Any()
- private val route = BydHudRouteState()
- private var context: Context? = null
- private var binder: IBinder? = null
- private var binding = false
- private var started = false
- private var senderStarted = false
- private var guidanceSentLogged = false
- private var showing = false
- private var lastSendResult: Int? = null
- private var icons: Map? = null
-
- // The gateway pings registered callbacks and drops registrations that do not answer like an AIDL stub.
- private val callback = object : Binder() {
- override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean = when (code) {
- INTERFACE_TRANSACTION -> { reply?.writeString(CALLBACK_TOKEN); true }
- FIRST_CALL_TRANSACTION -> {
- data.enforceInterface(CALLBACK_TOKEN)
- reply?.writeNoException()
- reply?.writeInt(0)
- true
- }
- FIRST_CALL_TRANSACTION + 1 -> {
- data.enforceInterface(CALLBACK_TOKEN)
- val ready = data.readInt() != 0
- Log.i(TAG, "SOME/IP HAL ready=$ready")
- reply?.writeNoException()
- true
- }
- FIRST_CALL_TRANSACTION + 2 -> {
- data.enforceInterface(CALLBACK_TOKEN)
- reply?.writeNoException()
- reply?.writeInt(0) // No response to an unsupported request.
- reply?.writeInt(0) // No modified input parcel.
- true
- }
- else -> super.onTransact(code, data, reply, flags)
- }
- }
-
- fun initialize(appContext: Context) = synchronized(lock) {
- if (context == null) context = appContext.applicationContext
- bindLocked()
- if (!senderStarted) {
- senderStarted = true
- Executors.newSingleThreadScheduledExecutor { runnable ->
- Thread(runnable, "diplay-byd-hud").apply { isDaemon = true }
- }.scheduleWithFixedDelay(::tick, BydHudProtocol.REPEAT_MILLIS, BydHudProtocol.REPEAT_MILLIS, TimeUnit.MILLISECONDS)
- }
- }
-
- fun onFrame(frame: Iap2Frame) = synchronized(lock) {
- val change = route.accept(frame.messageId, frame.payload)
- if (frame.messageId == BydHudRouteState.ROUTE_GUIDANCE_UPDATE ||
- frame.messageId == BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE
- ) {
- Log.d(TAG, "route frame=0x${frame.messageId.toString(16)} change=$change guidance=${route.current()}")
- }
- when (change) {
- BydHudRouteChange.GUIDANCE -> sendCurrentLocked()
- BydHudRouteChange.CLEAR -> clearHudLocked()
- BydHudRouteChange.NONE -> Unit
- }
- }
-
- /** Clears the HUD immediately; called when DiPlay is about to be killed. */
- fun clearNow() = clear()
-
- fun clear() = synchronized(lock) {
- route.clear()
- clearHudLocked()
- }
-
- private fun tick() = synchronized(lock) {
- if (binder == null && !binding) bindLocked()
- sendCurrentLocked()
- }
-
- private fun enabled(): Boolean = context?.let(BydOutputSettings::enabled) ?: false
-
- private fun sendCurrentLocked() {
- if (binder == null || !started) return
- if (!enabled()) {
- clearHudLocked()
- return
- }
- val guidance = route.current()
- if (guidance == null) {
- clearHudLocked()
- return
- }
- val payload = BydHudPayload.guidance(
- distanceMeters = guidance.distanceMeters,
- maneuver = guidance.maneuver,
- icon = iconFor(guidance.gaode),
- road = guidance.road,
- )
- val accepted = sendLocked(payload)
- if (accepted && !guidanceSentLogged) {
- guidanceSentLogged = true
- Log.i(TAG, "HUD profile (300ms repeat, fixed field2=2): gateway accepted guidance; rendering unconfirmed")
- }
- if (accepted) showing = true
- }
-
- private fun clearHudLocked() {
- if (!showing) return
- if (!sendLocked(BydHudPayload.clear())) return
- showing = false
- guidanceSentLogged = false
- }
-
- // Arrow-less maneuvers (roundabouts, destination) are only visible through the field-8 icon.
- private fun iconFor(gaode: Int): ByteArray? {
- if (gaode <= 0) return null
- val loaded = icons ?: loadIcons().also { icons = it }
- return loaded[gaode]
- }
-
- private fun loadIcons(): Map {
- val assets = context?.assets ?: return emptyMap()
- return runCatching {
- assets.list(ICON_ASSET_DIR).orEmpty().mapNotNull { name ->
- val code = name.removePrefix("0x").removeSuffix(".png").toIntOrNull(16) ?: return@mapNotNull null
- code to assets.open("$ICON_ASSET_DIR/$name").use { it.readBytes() }
- }.toMap()
- }.onFailure { Log.w(TAG, "HUD icons unavailable", it) }.getOrDefault(emptyMap())
- }
-
- private fun bindLocked() {
- val appContext = context ?: return
- if (binder != null || binding) return
- try {
- // The gateway's onUnbind requires a MIME type; a typeless bind crashes the whole SOME/IP process.
- val intent = Intent(SOMEIP_ACTION).apply {
- setClassName(SOMEIP_PACKAGE, SOMEIP_CLASS)
- type = appContext.packageName
- }
- binding = appContext.bindService(intent, connection, Context.BIND_AUTO_CREATE)
- Log.i(TAG, "bindService=$binding")
- } catch (error: Throwable) {
- binding = false
- Log.w(TAG, "cannot bind SOME/IP service", error)
- }
- }
-
- private fun onGatewayCallback(action: () -> Unit) {
- callbacks.execute {
- synchronized(lock) {
- runCatching(action).onFailure { Log.w(TAG, "gateway callback failed", it) }
- }
- }
- }
-
- private val connection = object : ServiceConnection {
- override fun onServiceConnected(name: ComponentName, service: IBinder) = onGatewayCallback {
- binder = service
- binding = true
- val registered = transactLocked(TX_REGISTER_CALLBACK, returnsValue = false) { it.writeStrongBinder(callback) }
- val startResult = if (registered == 0) transactLocked(TX_START_SERVICE) { it.writeLong(SERVICE_ID) } else -1
- // Firmware explicitly treats 13 as an already-started service.
- started = BydHudProtocol.serviceStarted(startResult)
- Log.i(TAG, "SOME/IP connected, callback=$registered startResult=$startResult started=$started")
- showing = false
- sendCurrentLocked()
- }
-
- // BIND_AUTO_CREATE reconnects after a gateway restart without a second binding.
- override fun onServiceDisconnected(name: ComponentName) = onGatewayCallback {
- binder = null
- started = false
- }
-
- override fun onBindingDied(name: ComponentName) = onGatewayCallback { resetBindingLocked() }
- override fun onNullBinding(name: ComponentName) = onGatewayCallback { resetBindingLocked() }
- }
-
- private inline fun transactLocked(code: Int, returnsValue: Boolean = true, write: (Parcel) -> Unit): Int {
- val target = binder ?: return -1
- val data = Parcel.obtain()
- val reply = Parcel.obtain()
- return try {
- data.writeInterfaceToken(SOMEIP_TOKEN)
- write(data)
- check(target.transact(code, data, reply, 0)) { "Unsupported transaction $code" }
- reply.readException()
- if (returnsValue) reply.readInt() else 0
- } catch (error: Throwable) {
- Log.w(TAG, "SOME/IP transaction $code failed", error)
- -1
- } finally {
- reply.recycle()
- data.recycle()
- }
- }
-
- private fun sendLocked(payload: ByteArray): Boolean {
- if (binder == null) return false
- val result = transactLocked(TX_FIRE_EVENT) {
- it.writeInt(1)
- it.writeLong(HUD_TOPIC)
- it.writeLong(System.currentTimeMillis())
- it.writeInt(payload.size)
- it.writeByteArray(payload)
- }
- if (lastSendResult != result) {
- Log.i(TAG, "HUD fireEvent result=$result bytes=${payload.size}")
- lastSendResult = result
- }
- if (result != 0) {
- if (binder?.isBinderAlive != true) resetBindingLocked()
- }
- return BydHudProtocol.eventAccepted(result)
- }
-
- private fun resetBindingLocked() {
- val appContext = context
- if (appContext != null && binding) {
- runCatching { appContext.unbindService(connection) }
- }
- binder = null
- binding = false
- started = false
- showing = false
- guidanceSentLogged = false
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudPayload.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudPayload.kt
deleted file mode 100644
index dcbd3d3f04..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudPayload.kt
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import java.io.ByteArrayOutputStream
-
-/** Wire shape emitted by BYD HUD's DirectTbtPayload; field order matters to the HUD firmware. */
-internal object BydHudPayload {
- private const val MIN_DISTANCE_METERS = 11 // the glass garbles 0..10 m readouts
- private const val MAX_TEXT_BYTES = 200
-
- fun guidance(
- distanceMeters: Int,
- maneuver: Int,
- icon: ByteArray? = null,
- road: String = "",
- eta: String = "",
- ): ByteArray =
- ByteArrayOutputStream(64 + (icon?.size ?: 0)).apply {
- // HUD experiment A: match the fixed guidance value observed by BYDMate.
- field(2, 2)
- field(6, 1)
- bytes(7, ByteArray(0))
- bytes(8, icon ?: ByteArray(0))
- field(9, displayDistance(distanceMeters).toLong())
- bytes(10, text(road))
- field(16, 2)
- bytes(26, text(eta))
- field(28, maneuver.coerceAtLeast(0).toLong())
- }.toByteArray().wrap()
-
- fun clear(): ByteArray = ByteArrayOutputStream(12).apply {
- field(2, 2)
- field(6, 255)
- field(16, 1)
- }.toByteArray().wrap()
-
- private fun displayDistance(meters: Int): Int = meters.coerceAtLeast(0).coerceAtLeast(MIN_DISTANCE_METERS)
-
- private fun text(value: String): ByteArray {
- val encoded = value.toByteArray(Charsets.UTF_8)
- if (encoded.size <= MAX_TEXT_BYTES) return encoded
- // Cut on a character boundary so the HUD never receives a broken UTF-8 sequence.
- var end = MAX_TEXT_BYTES
- while (end > 0 && (encoded[end].toInt() and 0xc0) == 0x80) end--
- return encoded.copyOf(end)
- }
-
- private fun ByteArrayOutputStream.field(number: Int, value: Long) {
- writeVarint(number.toLong() shl 3)
- writeVarint(value)
- }
-
- private fun ByteArrayOutputStream.bytes(number: Int, value: ByteArray) {
- writeVarint((number.toLong() shl 3) or 2)
- writeVarint(value.size.toLong())
- write(value)
- }
-
- private fun ByteArray.wrap(): ByteArray = ByteArrayOutputStream(size + 4).apply {
- write(0x0a)
- writeVarint(size.toLong())
- write(this@wrap)
- }.toByteArray()
-
- private fun ByteArrayOutputStream.writeVarint(initialValue: Long) {
- var value = initialValue
- do {
- var next = (value and 0x7f).toInt()
- value = value ushr 7
- if (value != 0L) next = next or 0x80
- write(next)
- } while (value != 0L)
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudProtocol.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudProtocol.kt
deleted file mode 100644
index be4f0a406d..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudProtocol.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/** Shared wire contract; keep DiPlay and DiAuto copies identical apart from their package. */
-internal object BydHudProtocol {
- const val SERVICE_TOPIC = 0x000B010A00010000L
- const val NAVIGATION_TOPIC = 0x0004010A00018001L
- const val REPEAT_MILLIS = 300L
- fun serviceStarted(code: Int): Boolean = code == 0 || code == 13
- fun eventAccepted(code: Int): Boolean = code == 0
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudRouteState.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudRouteState.kt
deleted file mode 100644
index 6c709ce24f..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydHudRouteState.kt
+++ /dev/null
@@ -1,207 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-internal data class BydHudGuidance(
- val distanceMeters: Int,
- /** Native HUD arrow (field 28). */
- val maneuver: Int,
- /** Gaode maneuver code: selects the HUD icon (field 8). */
- val gaode: Int = 0,
- val road: String = "",
- val arrivalEpochSeconds: Long? = null,
-)
-
-internal data class BydAppleManeuver(
- val distanceMeters: Int,
- val type: Int,
- val drivingSide: Int,
- val road: String = "",
- val remainingSeconds: Long? = null,
- val remainingMeters: Long? = null,
- val arrivalEpochSeconds: Long? = null,
-)
-
-internal enum class BydHudRouteChange {
- NONE,
- GUIDANCE,
- CLEAR,
-}
-
-/** Decodes the iAP2 route-guidance subset needed by the BYD windshield HUD and cluster. */
-internal class BydHudRouteState(private val nanoTime: () -> Long = System::nanoTime) {
- private data class Maneuver(val type: Int, val drivingSide: Int, val afterRoad: String)
-
- private val maneuvers = mutableMapOf()
- private var routeActive = false
- private var activeIndex = -1
- private var distanceMeters = 0
- private var currentRoad = ""
- private var arrivalEpochSeconds: Long? = null
- private var remainingSeconds: Long? = null
- private var remainingMeters: Long? = null
- private var emptyListSinceNs: Long? = null
- private var lastRouteUpdateNs: Long? = null
-
- fun accept(messageId: Int, payload: ByteArray): BydHudRouteChange {
- if (!validTlvs(payload)) return BydHudRouteChange.NONE
- return when (messageId) {
- ROUTE_GUIDANCE_UPDATE -> parseRouteUpdate(payload)
- ROUTE_GUIDANCE_MANEUVER_UPDATE -> parseManeuverUpdate(payload)
- else -> BydHudRouteChange.NONE
- }
- }
-
- fun current(): BydHudGuidance? {
- val maneuver = activeManeuver() ?: return null
- val gaode = BydManeuverCodes.gaode(maneuver.type, maneuver.drivingSide)
- return BydHudGuidance(
- distanceMeters = distanceMeters,
- maneuver = BydManeuverCodes.hudArrow(gaode),
- gaode = gaode,
- road = roadFor(maneuver),
- arrivalEpochSeconds = arrivalEpochSeconds,
- )
- }
-
- /** Next maneuver as Apple sent it, for outputs with a richer icon set than the HUD. */
- fun currentApple(): BydAppleManeuver? {
- val maneuver = activeManeuver() ?: return null
- return BydAppleManeuver(
- distanceMeters, maneuver.type, maneuver.drivingSide,
- roadFor(maneuver), remainingSeconds, remainingMeters, arrivalEpochSeconds,
- )
- }
-
- fun clear(): Boolean {
- val wasActive = routeActive
- routeActive = false
- activeIndex = -1
- distanceMeters = 0
- currentRoad = ""
- arrivalEpochSeconds = null
- remainingSeconds = null
- remainingMeters = null
- emptyListSinceNs = null
- lastRouteUpdateNs = null
- maneuvers.clear()
- return wasActive
- }
-
- private fun activeManeuver(): Maneuver? {
- if (!routeActive || activeIndex < 0) return null
- val updated = lastRouteUpdateNs ?: return null
- if (nanoTime() - updated >= STALE_ROUTE_NS) return null
- val emptySince = emptyListSinceNs
- if (emptySince != null && nanoTime() - emptySince >= EMPTY_LIST_HIDE_NS) return null
- return maneuvers[activeIndex]
- }
-
- // The road the driver turns onto is what the next instruction is about; fall back to the current one.
- private fun roadFor(maneuver: Maneuver): String = maneuver.afterRoad.ifEmpty { currentRoad }
-
- private fun parseRouteUpdate(data: ByteArray): BydHudRouteChange {
- lastRouteUpdateNs = nanoTime()
- var state: Int? = null
- var distance: Int? = null
- var firstManeuver: Int? = null
- var listPresent = false
- forEachTlv(data) { type, value, valueLength ->
- when {
- type == 0x01 && valueLength >= 1 -> state = data[value].toInt() and 0xff
- type == 0x03 -> currentRoad = utf8(data, value, valueLength)
- type == 0x05 && valueLength >= 8 -> arrivalEpochSeconds = u64(data, value).takeIf { it > 0 }
- type == 0x06 && valueLength >= 8 -> remainingSeconds = u64(data, value).takeIf { it >= 0 }
- type == 0x07 && valueLength >= 4 -> remainingMeters = u32(data, value)
- type == 0x0a && valueLength >= 4 -> {
- distance = u32(data, value).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
- }
- type == 0x0d -> {
- listPresent = true
- if (valueLength >= 2) firstManeuver = u16(data, value)
- }
- }
- }
-
- // Only NoRouteSet (0) and Arrived (2) end the route.
- if (state == 0 || state == 2) {
- return if (clear()) BydHudRouteChange.CLEAR else BydHudRouteChange.NONE
- }
- // The iPhone briefly sends an empty current list every few seconds and while rerouting. Keep the last
- // maneuver (and the cached 0x5202 details, which are never resent) and hide it only if the list stays
- // empty; the bridges' 1 s tick clears the outputs once current() turns null.
- if (listPresent && firstManeuver == null) {
- if (emptyListSinceNs == null) emptyListSinceNs = nanoTime()
- return BydHudRouteChange.NONE
- }
- if (firstManeuver != null) emptyListSinceNs = null
- if (state != null) routeActive = true
- if (firstManeuver != null) {
- activeIndex = firstManeuver!!
- routeActive = true
- }
- if (distance != null) distanceMeters = distance!!.coerceAtLeast(0)
- return if (current() != null) BydHudRouteChange.GUIDANCE else BydHudRouteChange.NONE
- }
-
- private fun parseManeuverUpdate(data: ByteArray): BydHudRouteChange {
- var index: Int? = null
- var type: Int? = null
- var drivingSide = 0
- var afterRoad = ""
- forEachTlv(data) { id, value, valueLength ->
- when {
- id == 0x01 && valueLength >= 2 -> index = u16(data, value)
- id == 0x03 && valueLength >= 1 -> type = data[value].toInt() and 0xff
- id == 0x04 -> afterRoad = utf8(data, value, valueLength)
- id == 0x08 && valueLength >= 1 -> drivingSide = data[value].toInt() and 0xff
- }
- }
- if (index != null && type != null) maneuvers[index!!] = Maneuver(type!!, drivingSide, afterRoad)
- return if (current() != null) BydHudRouteChange.GUIDANCE else BydHudRouteChange.NONE
- }
-
- private inline fun forEachTlv(data: ByteArray, block: (Int, Int, Int) -> Unit) {
- var offset = 0
- while (offset < data.size) {
- val length = u16(data, offset)
- block(u16(data, offset + 2), offset + TLV_HEADER_BYTES, length - TLV_HEADER_BYTES)
- offset += length
- }
- }
-
- private fun validTlvs(data: ByteArray): Boolean {
- var offset = 0
- while (offset < data.size) {
- if (offset + TLV_HEADER_BYTES > data.size) return false
- val length = u16(data, offset)
- if (length < TLV_HEADER_BYTES || length > data.size - offset) return false
- offset += length
- }
- return offset == data.size
- }
-
- private fun u16(data: ByteArray, offset: Int): Int =
- ((data[offset].toInt() and 0xff) shl 8) or (data[offset + 1].toInt() and 0xff)
-
- private fun u32(data: ByteArray, offset: Int): Long =
- ((data[offset].toLong() and 0xff) shl 24) or
- ((data[offset + 1].toLong() and 0xff) shl 16) or
- ((data[offset + 2].toLong() and 0xff) shl 8) or
- (data[offset + 3].toLong() and 0xff)
-
- private fun u64(data: ByteArray, offset: Int): Long = (u32(data, offset) shl 32) or u32(data, offset + 4)
-
- // iAP2 utf8 parameters are NUL-terminated.
- private fun utf8(data: ByteArray, offset: Int, length: Int): String {
- var end = offset
- while (end < offset + length && data[end] != 0.toByte()) end++
- return String(data, offset, end - offset, Charsets.UTF_8).trim()
- }
-
- companion object {
- const val ROUTE_GUIDANCE_UPDATE = 0x5201
- const val ROUTE_GUIDANCE_MANEUVER_UPDATE = 0x5202
- private const val TLV_HEADER_BYTES = 4
- private const val STALE_ROUTE_NS = 30_000_000_000L
- private const val EMPTY_LIST_HIDE_NS = 3_000_000_000L
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydManeuverCodes.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydManeuverCodes.kt
deleted file mode 100644
index 7c21e738bd..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydManeuverCodes.kt
+++ /dev/null
@@ -1,68 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/**
- * Apple iAP2 RouteGuidanceManeuverType -> Gaode maneuver code, the vocabulary of the BYD HUD
- * icon set (assets/byd-hud-icons/0x.png) and of the native HUD arrow.
- */
-internal object BydManeuverCodes {
- const val NONE = 0
- const val LEFT = 1
- const val RIGHT = 2
- const val SLIGHT_LEFT = 3
- const val SLIGHT_RIGHT = 4
- const val SHARP_LEFT = 7
- const val SHARP_RIGHT = 8
- const val U_TURN_LEFT = 9
- const val U_TURN_RIGHT = 10
- const val STRAIGHT = 11
- const val ROUNDABOUT_ENTER = 13
- const val ROUNDABOUT_EXIT = 24
- const val DESTINATION = 48
-
- private const val ROUNDABOUT_EXIT_BASE = 24 // + exit 1..10, right-hand traffic
- private const val ROUNDABOUT_EXIT_BASE_LEFT_HAND = 34 // + exit 1..10, left-hand traffic
-
- /** [drivingSide] 1 is Apple's left-hand driving. */
- fun gaode(appleType: Int, drivingSide: Int): Int {
- val leftHand = drivingSide == 1
- if (appleType in 28..46) {
- val exit = appleType - 27
- return when {
- exit > 10 -> ROUNDABOUT_ENTER
- leftHand -> ROUNDABOUT_EXIT_BASE_LEFT_HAND + exit
- else -> ROUNDABOUT_EXIT_BASE + exit
- }
- }
- return when (appleType) {
- 1, 20 -> LEFT
- 2, 21 -> RIGHT
- 47 -> SHARP_LEFT
- 48 -> SHARP_RIGHT
- 13, 22, 49, 52 -> SLIGHT_LEFT
- 14, 23, 50, 53 -> SLIGHT_RIGHT
- 4, 18, 19, 26 -> if (leftHand) U_TURN_RIGHT else U_TURN_LEFT
- 6 -> ROUNDABOUT_ENTER
- 7 -> ROUNDABOUT_EXIT
- 10, 12, 24, 25, 27 -> DESTINATION
- 3, 5, 8, 9, 11, 51 -> STRAIGHT
- else -> NONE
- }
- }
-
- /**
- * Native HUD arrow (field 28): 1 left, 2 right, 3 slight left, 5 slight right, 7/8 U-turn,
- * 11 straight, 99 blank. Anything else renders as a phantom left arrow, so glyph-less
- * maneuvers (roundabouts, destination) are blank and rely on the field-8 icon; 0 clears.
- */
- fun hudArrow(gaode: Int): Int = when (gaode) {
- NONE -> 0
- LEFT, SHARP_LEFT -> 1
- RIGHT, SHARP_RIGHT -> 2
- SLIGHT_LEFT -> 3
- SLIGHT_RIGHT -> 5
- U_TURN_LEFT -> 7
- U_TURN_RIGHT -> 8
- STRAIGHT -> 11
- else -> 99
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydNavigationOutputs.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydNavigationOutputs.kt
deleted file mode 100644
index a1102f78bf..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydNavigationOutputs.kt
+++ /dev/null
@@ -1,67 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import com.shilapi.xcertplay.iap2.wire.Iap2Frame
-
-/** Nonblocking boundary between phone control messages and vendor services. */
-object BydNavigationOutputs {
- /** Recover a journaled interrupted output when the app opens, even before a phone reconnects. */
- fun onAppOpened(context: Context) {
- if (BydStandaloneHudOutput.available(context)) start(context)
- // Read the battery early, so a reading is ready when CarPlay identifies (see batteryStatus).
- if (BydOutputSettings.batteryToIphone(context)) BydBatteryStatus.start(context)
- }
- fun setDiagnosticHold(hold: Boolean) { BydStandaloneHudOutput.syntheticHold = hold }
- @Volatile private var useStandalone = false
- private val standalone = NavigationOutputWorker("diplay-standalone-output", BydStandaloneNavigationBridge::clear)
- private val hud = NavigationOutputWorker("diplay-hud-output", BydHudBridge::clear)
- private val cluster = NavigationOutputWorker("diplay-cluster-output", BydClusterBridge::clear)
-
- /** The host reports whether its CarPlay map window is on the cluster (see [BydClusterMapPause]). */
- fun setClusterMapShown(shown: Boolean) { BydClusterMapPause.clusterMapShown = shown }
-
- /** The running CarPlay session: told every second whether the cluster currently shows the map. */
- fun setClusterStreamControl(control: (Boolean) -> Unit) { BydClusterMapPause.streamControl = control }
-
- fun clearClusterStreamControl(control: (Boolean) -> Unit) {
- if (BydClusterMapPause.streamControl == control) BydClusterMapPause.streamControl = null
- }
-
- /**
- * The car's battery for the iPhone's vehicle status; starts reading it over adb. The electric
- * vehicle is declared only once a reading is there (see withVehicleStatusFrom).
- */
- fun batteryStatus(context: Context): com.shilapi.xcertplay.transport.VehicleStatusProvider =
- BydBatteryStatus.also { it.start(context) }
-
- /** The car's wheel speed and gear for the iPhone's dead reckoning; read over adb while asked for. */
- fun wheelSpeed(context: Context): com.shilapi.xcertplay.transport.VehicleSpeedSource =
- BydWheelSpeedSource.attach(context)
- /** Whether the car is in P (read over adb), or null when it cannot tell. Blocking. */
- fun parked(context: Context): Boolean? = BydParkedState.parked(context.applicationContext)
-
- fun start(context: Context) {
- val app = context.applicationContext
- useStandalone = BydStandaloneHudOutput.available(app)
- if (useStandalone) standalone.start { BydStandaloneNavigationBridge.initialize(app) }
- else {
- hud.start { BydHudBridge.initialize(app) }
- cluster.start { BydClusterBridge.initialize(app) }
- }
- BydClusterMapPause.initialize(app)
- }
-
- internal fun onFrame(frame: Iap2Frame) {
- if (frame.messageId != BydHudRouteState.ROUTE_GUIDANCE_UPDATE &&
- frame.messageId != BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE) return
- val owned = frame // Iap2Frame is immutable and defensively copies its payload.
- if (useStandalone) standalone.submit { BydStandaloneNavigationBridge.onFrame(owned) }
- else {
- hud.submit { BydHudBridge.onFrame(owned) }
- cluster.submit { BydClusterBridge.onFrame(owned) }
- }
- }
-
- /** Best effort while alive; Android does not guarantee callbacks before force-stop. */
- fun endNow() { standalone.clear(); hud.clear(); cluster.clear() }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydOutputSettings.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydOutputSettings.kt
deleted file mode 100644
index 73524e4a33..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydOutputSettings.kt
+++ /dev/null
@@ -1,72 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import com.shilapi.xcertplay.transport.EvChargingConnectors
-
-/**
- * One user switch for BYD navigation output. On the tested car the windshield HUD mirrors what the
- * instrument cluster receives, so separate HUD/cluster switches cannot behave independently.
- */
-object BydOutputSettings {
- private const val PREFS = "diplay_byd_outputs"
- private const val KEY_ENABLED = "navigation_enabled"
- private const val KEY_CLUSTER_STREAM_PAUSE = "cluster_stream_pause"
- private const val KEY_BATTERY_TO_IPHONE = "battery_to_iphone"
- private const val KEY_LOW_CHARGE_PERCENT = "low_charge_percent"
- private const val KEY_CHARGING_CONNECTORS = "charging_connectors"
- private const val KEY_WHEEL_SPEED_TO_IPHONE = "wheel_speed_to_iphone"
- private const val KEY_VIDEO_WHILE_PARKED = "video_while_parked"
- const val DEFAULT_LOW_CHARGE_PERCENT = 20
- val lowChargePresets = listOf(10, 15, 20, 25, 30)
-
- fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY_ENABLED, true)
-
- fun setEnabled(context: Context, enabled: Boolean) = prefs(context).edit().putBoolean(KEY_ENABLED, enabled).apply()
-
- /** Ask the iPhone to stop drawing the cluster map while the cluster hides it (needs ADB over network). */
- fun clusterStreamPause(context: Context): Boolean = prefs(context).getBoolean(KEY_CLUSTER_STREAM_PAUSE, false)
-
- fun setClusterStreamPause(context: Context, enabled: Boolean) =
- prefs(context).edit().putBoolean(KEY_CLUSTER_STREAM_PAUSE, enabled).apply()
-
- /** Tell the iPhone the car's charge and range (needs ADB over network); applies on the next connection. */
- fun batteryToIphone(context: Context): Boolean = prefs(context).getBoolean(KEY_BATTERY_TO_IPHONE, false)
-
- fun setBatteryToIphone(context: Context, enabled: Boolean) =
- prefs(context).edit().putBoolean(KEY_BATTERY_TO_IPHONE, enabled).apply()
-
- /** The charging inlets the iPhone is told about; applies on the next connection. */
- fun chargingConnectors(context: Context): EvChargingConnectors =
- prefs(context).getString(KEY_CHARGING_CONNECTORS, null)
- ?.let { saved -> EvChargingConnectors.entries.firstOrNull { it.name == saved } }
- ?: EvChargingConnectors.CCS2_TYPE2
-
- fun setChargingConnectors(context: Context, connectors: EvChargingConnectors) =
- prefs(context).edit().putString(KEY_CHARGING_CONNECTORS, connectors.name).apply()
-
- /** Send wheel speed and gear with the car's GPS (needs ADB over network); applies on the next connection. */
- fun wheelSpeedToIphone(context: Context): Boolean = prefs(context).getBoolean(KEY_WHEEL_SPEED_TO_IPHONE, false)
-
- fun setWheelSpeedToIphone(context: Context, enabled: Boolean) =
- prefs(context).edit().putBoolean(KEY_WHEEL_SPEED_TO_IPHONE, enabled).apply()
- /** Offer iOS 27 video in car, played only while the gear reads P (needs ADB over network). */
- fun videoWhileParked(context: Context): Boolean = prefs(context).getBoolean(KEY_VIDEO_WHILE_PARKED, false)
-
- fun setVideoWhileParked(context: Context, enabled: Boolean) =
- prefs(context).edit().putBoolean(KEY_VIDEO_WHILE_PARKED, enabled).apply()
-
- /** At or below this charge the iPhone gets the low-range warning. */
- fun lowChargePercent(context: Context): Int = prefs(context).getInt(KEY_LOW_CHARGE_PERCENT, DEFAULT_LOW_CHARGE_PERCENT)
-
- fun setLowChargePercent(context: Context, percent: Int) =
- prefs(context).edit().putInt(KEY_LOW_CHARGE_PERCENT, percent).apply()
-
- /** Whether the head unit has a BYD navigation receiver, so settings can hide a switch that cannot work. */
- fun available(context: Context): Boolean =
- BydStandaloneHudOutput.available(context) || installed(context, "com.byd.amapservice") || installed(context, "com.ts.car.someip.service")
-
- private fun installed(context: Context, pkg: String): Boolean =
- runCatching { context.packageManager.getPackageInfo(pkg, 0) }.isSuccess
-
- private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydParkedState.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydParkedState.kt
deleted file mode 100644
index df34e24035..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydParkedState.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-
-/**
- * Whether the car is in P, read through the adb shell (autoservice binder) where apps would need a
- * BYD signature. The id is BYD SDK 1.0.5's gearbox device: 1 P, 2 R, 3 N, 4 D.
- */
-internal object BydParkedState {
- const val GEAR = "service call autoservice 5 i32 1011 i32 555745336"
- private const val PARK = 1
-
- private val shell = BydAdbShell("DiPlay-BYD-Parked")
-
- /** Null when the gear cannot be read (no ADB over network, or another car). Blocking. */
- fun parked(context: Context): Boolean? = parked(shell.run(context, GEAR))
-
- fun parked(output: String?): Boolean? = BydParcel.value(output)?.takeIf { it in 1..4 }?.let { it == PARK }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneHudOutput.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneHudOutput.kt
deleted file mode 100644
index 38efe04fed..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneHudOutput.kt
+++ /dev/null
@@ -1,67 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.ComponentName
-import android.content.Context
-import android.content.Intent
-import android.content.pm.ApplicationInfo
-import android.content.pm.PackageManager
-import android.os.Build
-import android.os.Process
-import android.util.Log
-import java.security.MessageDigest
-
-/** Ordinary-app IPC to the real stock receiver. No shell, local socket or permission grant. */
-internal class BydStandaloneHudOutput private constructor(context: Context) {
- private val app = context.applicationContext
- private val prefs = app.getSharedPreferences("byd_standalone_hud", Context.MODE_PRIVATE)
- private val session = BydStandaloneSession(
- send = { packet ->
- app.sendBroadcast(Intent("byd.hud.NAVIGATION").setComponent(TARGET)
- .putExtra("normal", packet).addFlags(Intent.FLAG_RECEIVER_FOREGROUND))
- Log.d(TAG, "dispatch uid=${Process.myUid()} bytes=${packet.split(',').size}")
- },
- rememberPendingClear = { pending ->
- check(prefs.edit().putBoolean("pending_clear", pending).commit()) { "Cannot persist HUD cleanup" }
- },
- needsRecovery = prefs.getBoolean("pending_clear", false),
- )
-
- init {
- Log.i(TAG, "Standalone navigation ready uid=${Process.myUid()} helper=none")
- // Retain the journal if dispatch fails; the next scheduled tick retries.
- runCatching { session.clear() }.onFailure { Log.w(TAG, "Startup clear will retry", it) }
- }
-
- fun update(icon: Int, exit: Int, distanceMeters: Int, road: String) =
- session.update(icon, exit, distanceMeters, road)
- fun clear() = session.clear()
-
- companion object {
- private const val TAG = "BYD-Standalone-Live"
- private val TARGET = ComponentName("com.byd.clusterdebug", "com.byd.clusterdebug.BroadcastReceiverCAN")
- @Volatile var syntheticHold = false
-
- fun create(context: Context): BydStandaloneHudOutput? =
- if (available(context)) BydStandaloneHudOutput(context) else null
-
- /** Enable production and diagnostic packages only on the physically tested firmware. */
- fun available(context: Context): Boolean {
- if (Build.VERSION.SDK_INT < 28 || context.packageName !in setOf(
- "com.andrerinas.headunitrevived", "com.shihab.diplay",
- "com.andrerinas.headunitrevived.bydhudtest", "com.shihab.diplay.hudtest")) return false
- if (Build.FINGERPRINT != "BYD-AUTO/IVI/IVI:13/TP1A.220624.014/eng.build20260722.221155:user/release-keys") return false
- return runCatching {
- val manager = context.packageManager
- val info = manager.getPackageInfo(TARGET.packageName, PackageManager.GET_SIGNING_CERTIFICATES)
- val receiver = manager.getReceiverInfo(TARGET, 0)
- val signers = info.signingInfo?.apkContentsSigners ?: return false
- info.longVersionCode == 10601004L &&
- info.applicationInfo!!.flags and ApplicationInfo.FLAG_SYSTEM != 0 &&
- receiver.enabled && receiver.exported && receiver.permission.isNullOrEmpty() &&
- signers.size == 1 && MessageDigest.getInstance("SHA-256").digest(signers[0].toByteArray())
- .joinToString("") { "%02x".format(it.toInt() and 255) } ==
- "efe3ca8ada0d10c655c3df9910ad2ebc121a47d9a6358434eb24074309933efc"
- }.getOrDefault(false)
- }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneNavigationBridge.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneNavigationBridge.kt
deleted file mode 100644
index e3e5aa9be2..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneNavigationBridge.kt
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import android.util.Log
-import com.shilapi.xcertplay.iap2.wire.Iap2Frame
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-
-internal object BydStandaloneNavigationBridge {
- private val lock = Any()
- private val route = BydHudRouteState()
- private var context: Context? = null
- private var output: BydStandaloneHudOutput? = null
- private var started = false
-
- fun initialize(appContext: Context) = synchronized(lock) {
- context = appContext.applicationContext
- if (output == null) output = BydStandaloneHudOutput.create(appContext)
- if (output != null && !started) {
- started = true
- Executors.newSingleThreadScheduledExecutor { task ->
- Thread(task, "diplay-standalone-navi").apply { isDaemon = true }
- }.scheduleWithFixedDelay(::tick, 0, 500, TimeUnit.MILLISECONDS)
- }
- }
-
- fun onFrame(frame: Iap2Frame) = synchronized(lock) {
- route.accept(frame.messageId, frame.payload)
- Unit
- }
-
- fun clear() = synchronized(lock) {
- route.clear() // A keepalive must never resurrect ended guidance.
- output?.clear()
- Unit
- }
-
- private fun tick() = synchronized(lock) {
- if (BydStandaloneHudOutput.syntheticHold) return@synchronized
- try {
- val frame = if (context?.let(BydOutputSettings::enabled) == true)
- route.currentApple()?.let(BydClusterFrame::from) else null
- if (frame == null) output?.clear()
- else output?.update(frame.icon, frame.roundaboutExit, frame.distanceMeters, frame.road)
- } catch (error: Exception) {
- Log.w("DiPlay-Standalone", "HUD update/cleanup will retry", error)
- }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandalonePackets.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandalonePackets.kt
deleted file mode 100644
index 21b4396dff..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandalonePackets.kt
+++ /dev/null
@@ -1,64 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/** Navigation records traced from the installed IVI HAL; no arbitrary feature input. */
-object BydStandalonePackets {
- const val MAX_DISTANCE_METERS = 16777214
- fun start(): String = "43,E0,00,3A,01,02"
- fun clear(): String = "43,E0,00,3A,01,01"
- fun guidance(icon: Int, exit: Int, distanceMeters: Int, road: String? = null): String? {
- val turn = BydFactoryTurnCode.map(icon, exit) ?: return null
- if (distanceMeters !in 0..MAX_DISTANCE_METERS) return null
- return (record(0x43F01018, distanceMeters) + record(0x43F01010, turn) +
- record(0x43F01030, turn)).toHex() + (road?.let { "," + streetName(it) } ?: "")
- }
- /** Exact non-RCS encodeReqSplitString format from the inspected IVI HAL.
- * The HAL caps this feature at 96 bytes. Each record carries seven content bytes,
- * a sequence byte, and the original feature incremented by 0x1000.
- */
- fun streetName(road: String): String {
- val text = buildString {
- var index = 0
- while (index < road.length && length < 48) {
- val char = road[index++]
- when {
- char.isHighSurrogate() -> {
- if (index < road.length && road[index].isLowSurrogate()) {
- if (length > 46) break
- append(char).append(road[index++])
- }
- }
- char.isLowSurrogate() -> Unit
- char.isISOControl() || char.isWhitespace() -> append(' ')
- else -> append(char)
- }
- }
- }.trim().ifEmpty { " " } // setString rejects zero bytes; a space replaces stale text.
- val bytes = text.toByteArray(Charsets.UTF_16LE)
- val contentSize = bytes.size + 2
- val content = ByteArray(((contentSize + 6) / 7) * 7) { 0xFF.toByte() }
- content[0] = bytes.size.toByte()
- bytes.copyInto(content, 1)
- content[bytes.size + 1] = bytes.sumOf { it.toInt() and 255 }.toByte()
- val packet = ByteArray(content.size / 7 * 13)
- for (index in 0 until content.size / 7) {
- val feature = 0x43FA1008 + (index shl 12)
- val offset = index * 13
- packet[offset] = (feature ushr 24).toByte()
- packet[offset + 1] = (feature ushr 16).toByte()
- packet[offset + 2] = (feature ushr 8).toByte()
- packet[offset + 3] = feature.toByte()
- packet[offset + 4] = 8
- packet[offset + 5] = (feature ushr 12).toByte()
- content.copyInto(packet, offset + 6, index * 7, (index + 1) * 7)
- }
- return packet.toHex()
- }
- private fun ByteArray.toHex(): String = joinToString(",") { "%02X".format(it.toInt() and 255) }
-
- private fun record(feature: Int, value: Int): ByteArray = byteArrayOf(
- (feature ushr 24).toByte(), (feature ushr 16).toByte(),
- (feature ushr 8).toByte(), feature.toByte(), 4,
- (value ushr 24).toByte(), (value ushr 16).toByte(),
- (value ushr 8).toByte(), value.toByte(),
- )
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneSession.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneSession.kt
deleted file mode 100644
index 992a61e45d..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStandaloneSession.kt
+++ /dev/null
@@ -1,51 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-/** Single-worker lifecycle; all vehicle writes and persistence stay off the phone thread. */
-internal class BydStandaloneSession(
- private val send: (String) -> Unit,
- private val rememberPendingClear: (Boolean) -> Unit,
- needsRecovery: Boolean = false,
- private val nanoTime: () -> Long = System::nanoTime,
-) {
- private var showing = needsRecovery
- private var recovering = needsRecovery
- private var lastPacket: String? = null
- private var lastSendNs = 0L
-
- fun update(icon: Int, exit: Int, distanceMeters: Int, road: String? = null) {
- if (recovering) clear()
- val packet = BydStandalonePackets.guidance(icon, exit, distanceMeters, road)
- if (packet == null) { clear(); return }
- try {
- if (!showing) {
- // Commit before publishing a start, so the next app launch can recover a crash.
- rememberPendingClear(true)
- showing = true
- send(BydStandalonePackets.start())
- }
- val now = nanoTime()
- if (lastPacket != packet || now - lastSendNs >= 1_000_000_000L) {
- send(packet)
- lastPacket = packet
- lastSendNs = now
- }
- } catch (error: Exception) {
- // A failed update may follow a successful start; clear before trying again.
- recovering = showing
- runCatching { clear() }
- throw error
- }
- }
-
- fun clear() {
- if (!showing) return
- recovering = true
- send(BydStandalonePackets.clear())
- // sendBroadcast returning is dispatch success, not hardware acknowledgement.
- rememberPendingClear(false)
- showing = false
- recovering = false
- lastPacket = null
- lastSendNs = 0L
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStarterBridge.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydStarterBridge.kt
deleted file mode 100644
index be610d4353..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydStarterBridge.kt
+++ /dev/null
@@ -1,120 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import java.net.Socket
-import java.net.InetSocketAddress
-import android.os.SystemClock
-import android.util.Log
-import java.io.DataInputStream
-import java.io.DataOutputStream
-import java.util.concurrent.Executors
-import java.util.concurrent.TimeUnit
-
-/** Test-only client of the user's explicitly ADB-started, navigation-only local bridge. */
-object BydStarterBridge {
- private const val TAG = "BYD-Starter-Bridge"
- private const val MAGIC = 0x42594431
- private data class Frame(val turn: Int, val distance: Int, val receivedMs: Long)
- @Volatile private var latest: Frame? = null
- @Volatile private var demoStartMs: Long? = null
- @Volatile private var token: ByteArray? = null
- private var started = false
- private var socket: Socket? = null
- private var output: DataOutputStream? = null
- private var input: DataInputStream? = null
- private var retryAfterMs = 0L
- private var lastNotice: String? = null
-
- @Synchronized fun initialize(context: Context) {
- if (context.packageName !in setOf("com.andrerinas.headunitrevived.bydhudtest", "com.shihab.diplay.hudtest") || started) return
- val saved = context.getSharedPreferences("hud_starter", Context.MODE_PRIVATE).getString("token", null)
- token = decodeToken(saved)
- started = true
- Executors.newSingleThreadScheduledExecutor { task ->
- Thread(task, "byd-starter-client").apply { isDaemon = true }
- }.scheduleWithFixedDelay(::tick, 0, 500, TimeUnit.MILLISECONDS)
- }
-
- @Synchronized fun configure(context: Context, secret: String) {
- check(context.packageName in setOf("com.andrerinas.headunitrevived.bydhudtest", "com.shihab.diplay.hudtest"))
- val parsed = requireNotNull(decodeToken(secret)) { "Invalid starter token" }
- context.getSharedPreferences("hud_starter", Context.MODE_PRIVATE).edit().putString("token", secret).apply()
- initialize(context)
- token = parsed
- Log.i(TAG, "Temporary starter credentials received")
- }
-
- private fun decodeToken(secret: String?): ByteArray? = secret?.takeIf { it.matches(Regex("[0-9a-f]{64}")) }
- ?.let { value -> ByteArray(32) { value.substring(it * 2, it * 2 + 2).toInt(16).toByte() } }
-
- fun update(icon: Int, exit: Int, distance: Int) {
- val turn = BydFactoryTurnCode.map(icon, exit)
- latest = if (turn != null && distance in 0..16777214) Frame(turn, distance, SystemClock.elapsedRealtime()) else null
- }
-
- fun clear(cancelDemo: Boolean = true) { latest = null; if (cancelDemo) demoStartMs = null }
-
- /** Called only by the DUMP-protected debug receiver after the parked-demo request. */
- fun demonstrate(context: Context) {
- initialize(context)
- demoStartMs = SystemClock.elapsedRealtime()
- Log.i(TAG, "Parked demo requested: left 500m, right 800m, then clear")
- }
-
- private fun tick() {
- try {
- val now = SystemClock.elapsedRealtime()
- val demo = demoStartMs
- val frame = if (demo != null) {
- when {
- now - demo < 8_000 -> Frame(1, 500, now)
- now - demo < 16_000 -> Frame(2, 800, now)
- now - demo < 20_000 -> null // Explicitly show cleanup before resuming phone guidance.
- else -> { demoStartMs = null; null }
- }
- } else latest?.takeIf { now - it.receivedMs < 6_000 }
- if (frame == null) {
- if (socket != null) {
- send(0, 0, 0)
- notice("Guidance cleared")
- close()
- }
- return
- }
- if (socket == null) {
- if (now < retryAfterMs) return
- val secret = token ?: return
- val next = Socket()
- try {
- next.connect(InetSocketAddress("127.0.0.1", 42671), 1_000)
- next.soTimeout = 1_500
- output = DataOutputStream(next.outputStream).also { it.write(secret); it.flush() }
- input = DataInputStream(next.inputStream)
- socket = next
- } catch (error: Exception) { next.close(); throw error }
- }
- send(1, frame.turn, frame.distance)
- notice("Connected to ADB starter; navigation writes acknowledged")
- } catch (error: Exception) {
- close() // EOF makes the helper clear any guidance it owns.
- retryAfterMs = SystemClock.elapsedRealtime() + 3_000
- notice("Waiting for ADB starter (${error.javaClass.simpleName}: ${error.message})")
- }
- }
-
- private fun send(operation: Int, turn: Int, distance: Int) {
- val out = checkNotNull(output)
- out.writeInt(MAGIC); out.writeInt(operation); out.writeInt(turn); out.writeInt(distance); out.flush()
- val result = checkNotNull(input).readInt()
- check(result == 0) { "Starter rejected command: $result" }
- }
-
- private fun close() {
- try { socket?.close() } catch (_: Exception) { }
- socket = null; input = null; output = null
- }
-
- private fun notice(message: String) {
- if (message != lastNotice) { Log.i(TAG, message); lastNotice = message }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/BydWheelSpeed.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/BydWheelSpeed.kt
deleted file mode 100644
index c5e36928e3..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/BydWheelSpeed.kt
+++ /dev/null
@@ -1,105 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import android.content.Context
-import android.os.SystemClock
-import android.util.Log
-import com.shilapi.xcertplay.transport.VehicleGear
-import com.shilapi.xcertplay.transport.VehicleSpeedReading
-import com.shilapi.xcertplay.transport.VehicleSpeedSample
-import com.shilapi.xcertplay.transport.VehicleSpeedSource
-import java.util.concurrent.Executors
-import java.util.concurrent.ScheduledExecutorService
-import java.util.concurrent.TimeUnit
-
-/**
- * Speed and gear through the adb shell (autoservice binder), where apps would need a BYD signature.
- * The ids are BYD SDK 1.0.5's speed (km/h) and gearbox devices; on DiLink 5.0 they read 0.0 and 1
- * while parked.
- */
-internal object BydWheelSpeed {
- const val SPEED = "service call autoservice 7 i32 1013 i32 -1807745016" // float km/h
- const val GEAR = "service call autoservice 5 i32 1011 i32 555745336" // 1 P, 2 R, 3 N, 4 D
-
- fun metersPerSecond(output: String?): Double? {
- val kmh = BydParcel.value(output)?.let { java.lang.Float.intBitsToFloat(it).toDouble() } ?: return null
- return if (kmh in 0.0..300.0) kmh / 3.6 else null
- }
-
- fun gear(output: String?): VehicleGear? = when (BydParcel.value(output)) {
- 1 -> VehicleGear.PARK
- 2 -> VehicleGear.REVERSE
- 3 -> VehicleGear.NEUTRAL
- 4 -> VehicleGear.DRIVE
- else -> null
- }
-}
-
-/**
- * Optional, needs ADB over network: wheel speed for the iPhone's dead reckoning in tunnels. Reads the
- * speed four times a second and the gear once a second, only while the iPhone asks for location.
- */
-internal object BydWheelSpeedSource : VehicleSpeedSource {
- private const val TAG = "DiPlay-BYD-Speed"
- private const val READ_MILLIS = 250L
- private const val GEAR_EVERY_READS = 4
- private const val MAX_SAMPLES = 40
-
- private val shell = BydAdbShell(TAG)
- private var context: Context? = null
- private var executor: ScheduledExecutorService? = null
- private val samples = ArrayList()
- private var gear: VehicleGear? = null
- private var reads = 0
- private var firstSampleLogged = false
-
- fun attach(appContext: Context) = apply { context = appContext.applicationContext }
-
- @Synchronized
- override fun start() {
- if (executor != null) return
- samples.clear()
- gear = null
- reads = 0
- firstSampleLogged = false
- executor = Executors.newSingleThreadScheduledExecutor { runnable ->
- Thread(runnable, "diplay-wheel-speed").apply { isDaemon = true }
- }.also { it.scheduleWithFixedDelay(::poll, 0, READ_MILLIS, TimeUnit.MILLISECONDS) }
- Log.i(TAG, "wheel speed started")
- }
-
- override fun stop() {
- val running = synchronized(this) { executor.also { executor = null } } ?: return
- // Close adb on the reader thread, after any read in flight, then let the thread end.
- running.execute { shell.close() }
- running.shutdown()
- Log.i(TAG, "wheel speed stopped")
- }
-
- @Synchronized
- override fun drain(): VehicleSpeedReading? {
- val current = gear ?: return null
- if (samples.isEmpty()) return null
- return VehicleSpeedReading(current, samples.toList()).also { samples.clear() }
- }
-
- private fun poll() {
- val app = context ?: return
- if (reads++ % GEAR_EVERY_READS == 0) {
- BydWheelSpeed.gear(shell.run(app, BydWheelSpeed.GEAR))?.let { next ->
- val changed = synchronized(this) { (gear != next).also { gear = next } }
- if (changed) Log.i(TAG, "gear $next")
- }
- }
- val before = SystemClock.elapsedRealtime()
- val speed = BydWheelSpeed.metersPerSecond(shell.run(app, BydWheelSpeed.SPEED)) ?: return
- val sample = VehicleSpeedSample((before + SystemClock.elapsedRealtime()) / 2, speed)
- synchronized(this) {
- if (samples.size == MAX_SAMPLES) samples.removeAt(0)
- samples += sample
- }
- if (!firstSampleLogged) {
- firstSampleLogged = true
- Log.i(TAG, "first wheel speed ${"%.1f".format(speed * 3.6)} km/h")
- }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/hud/NavigationOutputWorker.kt b/shared/src/main/java/com/shilapi/xcertplay/hud/NavigationOutputWorker.kt
deleted file mode 100644
index 917b8a0b9d..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/hud/NavigationOutputWorker.kt
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import java.util.concurrent.ArrayBlockingQueue
-import java.util.concurrent.ThreadPoolExecutor
-import java.util.concurrent.TimeUnit
-
-/** Each output owns a worker: a blocked vendor service cannot block the phone or the other output. */
-internal class NavigationOutputWorker(name: String, private val clearOutput: () -> Unit) {
- private val executor = ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
- ArrayBlockingQueue(128), { task -> Thread(task, name).apply { isDaemon = true } })
- private var accepting = false
-
- @Synchronized fun start(initialize: () -> Unit) {
- if (accepting) return
- accepting = true
- executor.queue.clear()
- executor.execute { runCatching { clearOutput(); initialize() } }
- }
-
- @Synchronized fun submit(action: () -> Unit) {
- if (!accepting) return
- try {
- executor.execute { runCatching(action) }
- } catch (_: java.util.concurrent.RejectedExecutionException) {
- // Incremental protocol frames cannot safely be dropped individually. Stop this output
- // until the next session, and clear after any in-flight vendor call returns.
- clear()
- }
- }
-
- @Synchronized fun clear() {
- accepting = false
- executor.queue.clear()
- executor.execute { runCatching(clearOutput) }
- }
-}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/network/LocalOnlyHotspotManager.kt b/shared/src/main/java/com/shilapi/xcertplay/network/LocalOnlyHotspotManager.kt
index b53ca4affd..a3901cc76f 100644
--- a/shared/src/main/java/com/shilapi/xcertplay/network/LocalOnlyHotspotManager.kt
+++ b/shared/src/main/java/com/shilapi/xcertplay/network/LocalOnlyHotspotManager.kt
@@ -189,7 +189,7 @@ class LocalOnlyHotspotManager(context: Context, private val onDiagnostic: (Strin
try {
val builder = SoftApConfiguration.Builder()
SoftApConfiguration.Builder::class.java.getMethod("setSsid", String::class.java)
- .invoke(builder, "DiPlay-${UUID.randomUUID().toString().take(6)}")
+ .invoke(builder, "LoopLink-${UUID.randomUUID().toString().take(6)}")
SoftApConfiguration.Builder::class.java.getMethod("setPassphrase", String::class.java, Int::class.javaPrimitiveType)
.invoke(builder, UUID.randomUUID().toString().replace("-", "").take(20), SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
// Request the station's 5 GHz channel, or 36 without a 5 GHz station.
diff --git a/shared/src/main/java/com/shilapi/xcertplay/orchestration/CarPlayController.kt b/shared/src/main/java/com/shilapi/xcertplay/orchestration/CarPlayController.kt
index 90e6b6ebca..06021d52a6 100644
--- a/shared/src/main/java/com/shilapi/xcertplay/orchestration/CarPlayController.kt
+++ b/shared/src/main/java/com/shilapi/xcertplay/orchestration/CarPlayController.kt
@@ -27,8 +27,6 @@ import com.shilapi.xcertplay.airplay.AirPlayMediaHandler
import com.shilapi.xcertplay.airplay.AirPlaySession
import com.shilapi.xcertplay.airplay.AirPlaySessionListener
import com.shilapi.xcertplay.airplay.PairingStore
-import com.shilapi.xcertplay.airplay.VideoInCar
-import com.shilapi.xcertplay.hud.BydNavigationOutputs
import com.shilapi.xcertplay.iap2.session.Iap2Session
import com.shilapi.xcertplay.mfi.Iap2MfiAuthenticationClient
import com.shilapi.xcertplay.mfi.MfiAuthenticationClient
@@ -151,8 +149,6 @@ class CarPlayController(
require(!config.locationReportingEnabled || locationProvider != null) {
"A location provider is required when location reporting is enabled"
}
- BydNavigationOutputs.start(context.applicationContext)
- BydNavigationOutputs.setClusterStreamControl(::applyClusterUi)
}
private enum class Phase { IDLE, MFI, WIRELESS, IPHONE, REENUMERATION, DATAPATHS, CONTROL }
@@ -193,17 +189,12 @@ class CarPlayController(
@Volatile private var mux: Iap2UsbMuxHost? = null
@Volatile private var csm: Iap2Session? = null
@Volatile private var activeSession: AirPlaySession? = null
- private val clusterUiLock = Any()
- private var clusterUiStream: Pair? = null
- private var clusterUiShown = true
private val playbackStatus = com.shilapi.xcertplay.media.CarPlayPlaybackStatus()
/** Told when the iPhone starts or stops playing media; may run on any thread. */
@Volatile var playbackListener: ((Boolean) -> Unit)? = null
/** Video in car; set before [start] to offer it to the iPhone (with AirPlayConfig.videoInCar). */
- @Volatile var videoListener: CarPlayVideoListener? = null
- @Volatile private var videoGate: VideoInCarGate? = null
/** Answers the iPhone on a video in car remote control session; a network write, any thread. */
fun sendVideoMessage(streamId: Long, message: Map): Boolean =
@@ -245,11 +236,6 @@ class CarPlayController(
private val sessionListener = object : AirPlaySessionListener {
override fun onSessionActive(session: AirPlaySession) {
- if (activeSession !== session) {
- BydNavigationOutputs.start(appContext)
- // The gear may have changed since /info.
- if (videoListener != null) session.setVideoPlaybackAllowed(VideoInCar.allowed)
- }
activeSession = session
debugLog(
"AirPlay session active controller=${session.controllerId ?: "unknown"} " +
@@ -261,8 +247,6 @@ class CarPlayController(
override fun onSessionEnded(session: AirPlaySession) {
if (activeSession === session) {
activeSession = null
- BydNavigationOutputs.endNow()
- videoListener?.onVideoSessionEnded()
synchronized(playbackStatus) { playbackStatus.clear() }?.let { playing -> playbackListener?.invoke(playing) }
}
debugLog("AirPlay session ended peer=${session.host}")
@@ -295,15 +279,6 @@ class CarPlayController(
uiListener?.onHostUiRequested(session)
}
- override fun onRemoteControlMessage(session: AirPlaySession, streamId: Long, message: Map) {
- if (activeSession === session) videoListener?.onVideoMessage(streamId, message)
- }
-
- override fun onVideoPlaybackUiRequested(session: AirPlaySession) {
- debugLog("CarPlay requested the car's video player")
- if (activeSession === session) videoListener?.onVideoUiRequested()
- }
-
override fun onCommand(session: AirPlaySession, type: String, params: Map) {
debugLog(
"AirPlay command type=$type params=${params.keys.sorted().joinToString(",")}",
@@ -351,13 +326,6 @@ class CarPlayController(
synchronized(this) {
if (closed) return
}
- videoListener?.let { listener ->
- videoGate = VideoInCarGate(listener::readParked) { allowed ->
- val sent = activeSession?.setVideoPlaybackAllowed(allowed)
- debugLog("video in car allowed=$allowed sent=${sent ?: "no session"}")
- listener.onVideoAllowedChanged(allowed)
- }.also { it.start() }
- }
if (config.transport == CarPlayTransport.WIRED) {
permissionCloseable = iphoneHost.registerPermissionReceiver(::onIphonePermission)
attachCloseable = iphoneHost.registerAttachReceiver(::onIphoneAttached)
@@ -424,9 +392,6 @@ class CarPlayController(
if (closed) return
closed = true
}
- videoGate?.close()
- BydNavigationOutputs.endNow()
- BydNavigationOutputs.clearClusterStreamControl(::applyClusterUi)
closeReceivers()
availabilityPollGeneration.incrementAndGet()
wirelessGeneration.incrementAndGet()
@@ -471,21 +436,6 @@ class CarPlayController(
}
}
- // Each new cluster stream starts with the map drawn (its initialURL); send only real changes.
- private fun applyClusterUi(shown: Boolean) = synchronized(clusterUiLock) {
- val session = activeSession ?: return@synchronized
- val stream = session.clusterStream.takeIf { it > 0 } ?: return@synchronized
- if (clusterUiStream != session to stream) {
- clusterUiStream = session to stream
- clusterUiShown = true
- }
- if (shown == clusterUiShown) return@synchronized
- if (session.setClusterUiShown(shown)) {
- clusterUiShown = shown
- debugLog("Cluster map: ${if (shown) "showUI, the cluster shows the map" else "stopUI, the cluster hides the map"}")
- }
- }
-
/** Waits for USB, iAP2, MFi and VPN teardown; intended for a non-main lifecycle thread. */
fun awaitClosed(timeoutMillis: Long): Boolean {
require(timeoutMillis >= 0) { "timeoutMillis must not be negative" }
@@ -497,9 +447,7 @@ class CarPlayController(
}
}
- // HUD (SOME/IP) and cluster (AMap broadcast) keep separate state so one failing cannot stall the other.
private fun onRouteFrame(frame: com.shilapi.xcertplay.iap2.wire.Iap2Frame) {
- BydNavigationOutputs.onFrame(frame)
synchronized(playbackStatus) { playbackStatus.accept(frame) }?.let { playing -> playbackListener?.invoke(playing) }
}
diff --git a/shared/src/main/java/com/shilapi/xcertplay/orchestration/CarPlayVideoListener.kt b/shared/src/main/java/com/shilapi/xcertplay/orchestration/CarPlayVideoListener.kt
deleted file mode 100644
index 129dd6b01d..0000000000
--- a/shared/src/main/java/com/shilapi/xcertplay/orchestration/CarPlayVideoListener.kt
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.shilapi.xcertplay.orchestration
-
-import com.shilapi.xcertplay.airplay.VideoInCar
-import java.io.Closeable
-
-/** iOS 27 video in car, played by the host in the car's own player (see [VideoInCar]). */
-interface CarPlayVideoListener {
- /** Whether the car is in P, or null when it cannot tell. Blocking; read once a second while CarPlay runs. */
- fun readParked(): Boolean?
-
- /** Video became allowed or not; when not, the player must close. Any thread. */
- fun onVideoAllowedChanged(allowed: Boolean)
-
- /** A playback message from the iPhone, e.g. insertPlayQueueItem, setRate, seek, stop. Any thread. */
- fun onVideoMessage(streamId: Long, message: Map)
-
- /** The iPhone asks the car to show its video player (requestUI "videoplayback:"). Any thread. */
- fun onVideoUiRequested()
-
- /** The CarPlay session ended; the player must close. Any thread. */
- fun onVideoSessionEnded()
-}
-
-/**
- * Keeps [VideoInCar.allowed] in step with the car: allowed only while the gear reads P, so an unknown
- * gear (no ADB) keeps video off. Changes go to [onChanged].
- */
-internal class VideoInCarGate(
- private val readParked: () -> Boolean?,
- private val onChanged: (Boolean) -> Unit,
-) : Closeable {
- @Volatile private var closed = false
-
- fun start() {
- Thread({
- while (!closed) {
- update(runCatching(readParked).getOrNull())
- try {
- Thread.sleep(POLL_MILLIS)
- } catch (_: InterruptedException) {
- return@Thread
- }
- }
- }, "diplay-video-gate").apply { isDaemon = true }.start()
- }
-
- internal fun update(parked: Boolean?) {
- val allowed = parked == true
- if (allowed == VideoInCar.allowed || closed) return
- VideoInCar.allowed = allowed
- onChanged(allowed)
- }
-
- override fun close() {
- closed = true
- VideoInCar.allowed = false
- }
-
- private companion object {
- const val POLL_MILLIS = 1_000L
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/adb/LocalAdbTest.kt b/shared/src/test/java/com/shilapi/xcertplay/adb/LocalAdbTest.kt
deleted file mode 100644
index a4717f1728..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/adb/LocalAdbTest.kt
+++ /dev/null
@@ -1,130 +0,0 @@
-package com.shilapi.xcertplay.adb
-
-import java.io.ByteArrayInputStream
-import java.math.BigInteger
-import java.net.ServerSocket
-import java.nio.ByteBuffer
-import java.nio.ByteOrder
-import java.security.KeyPairGenerator
-import java.security.Signature
-import java.security.interfaces.RSAPublicKey
-import java.util.Base64
-import java.util.concurrent.CopyOnWriteArrayList
-import kotlin.concurrent.thread
-import org.junit.Assert.assertArrayEquals
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertTrue
-import org.junit.Test
-
-class LocalAdbTest {
- private val key = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair()
-
- @Test
- fun packetsRoundTripWithChecksumAndMagic() {
- val bytes = AdbPacket(AdbPacket.OPEN, 1, 0, "shell:id\u0000".toByteArray()).encode()
- val header = ByteBuffer.wrap(bytes, 0, 24).order(ByteOrder.LITTLE_ENDIAN)
-
- assertEquals(AdbPacket.OPEN, header.int)
- header.int; header.int
- assertEquals(9, header.int)
- assertEquals("shell:id\u0000".toByteArray().sumOf { it.toInt() }, header.int)
- assertEquals(AdbPacket.OPEN.inv(), header.int)
- val read = AdbPacket.read(ByteArrayInputStream(bytes))
- assertArrayEquals("shell:id\u0000".toByteArray(), read.payload)
- }
-
- @Test
- fun publicKeyUsesTheAdbdLayout() {
- val message = String(AdbKeys.publicKeyMessage(key.public), Charsets.UTF_8)
- assertTrue(message.endsWith(" diplay@headunit\u0000"))
- val blob = ByteBuffer.wrap(Base64.getDecoder().decode(message.substringBefore(' '))).order(ByteOrder.LITTLE_ENDIAN)
- val n = (key.public as RSAPublicKey).modulus
-
- assertEquals(524, blob.capacity())
- assertEquals(64, blob.int)
- // n0inv * n == -1 (mod 2^32)
- val r32 = BigInteger.ONE.shiftLeft(32)
- assertEquals(r32 - BigInteger.ONE, BigInteger.valueOf(blob.int.toLong() and 0xffffffffL).multiply(n).mod(r32))
- assertEquals(n, littleEndian(blob, 256))
- assertEquals(BigInteger.ONE.shiftLeft(4096).mod(n), littleEndian(blob, 256))
- assertEquals(65537, blob.int)
- }
-
- @Test
- fun knownKeyRunsShellCommands() {
- val adbd = FakeAdbd(knowsKey = true, output = "Result: Parcel(00000000 00000002 '........')")
- LocalAdb(key, port = adbd.port).use { adb ->
- assertEquals(LocalAdb.Access.READY, adb.connect(mayAsk = false))
- assertEquals("Result: Parcel(00000000 00000002 '........')", adb.shell("service call autoservice 5"))
- }
- assertEquals(listOf("shell:service call autoservice 5"), adbd.opened)
- }
-
- @Test
- fun unknownKeyIsOfferedOnlyWhenAsking() {
- val quiet = FakeAdbd(knowsKey = false, approves = true)
- LocalAdb(key, port = quiet.port).use { assertEquals(LocalAdb.Access.NOT_APPROVED, it.connect(mayAsk = false)) }
- assertFalse(quiet.offeredKey)
-
- val asking = FakeAdbd(knowsKey = false, approves = true)
- LocalAdb(key, port = asking.port).use { assertEquals(LocalAdb.Access.READY, it.connect(mayAsk = true)) }
- assertTrue(asking.offeredKey)
- }
-
- @Test
- fun closedPortIsReportedAsUnreachable() {
- val port = ServerSocket(0).use { it.localPort }
- LocalAdb(key, port = port).use { assertEquals(LocalAdb.Access.UNREACHABLE, it.connect(mayAsk = true)) }
- }
-
- private fun littleEndian(buffer: ByteBuffer, size: Int): BigInteger {
- val bytes = ByteArray(size).also { buffer.get(it) }
- return BigInteger(1, bytes.reversedArray())
- }
-
- /** One-connection adbd: token auth with [key], then answers each OPEN with [output]. */
- private inner class FakeAdbd(knowsKey: Boolean, approves: Boolean = false, output: String = "") {
- private val server = ServerSocket(0)
- val port = server.localPort
- val opened = CopyOnWriteArrayList()
- @Volatile var offeredKey = false
-
- init {
- thread(isDaemon = true) {
- server.accept().use { socket ->
- val input = socket.getInputStream()
- val out = socket.getOutputStream()
- fun send(packet: AdbPacket) = out.write(packet.encode())
- AdbPacket.read(input) // CNXN
- val token = ByteArray(20) { it.toByte() }
- send(AdbPacket(AdbPacket.AUTH, AdbPacket.AUTH_TOKEN, 0, token))
- val signature = AdbPacket.read(input)
- val valid = Signature.getInstance("NONEwithRSA").run {
- initVerify(key.public)
- update(byteArrayOf(0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14) + token)
- verify(signature.payload)
- }
- if (!(valid && knowsKey)) {
- send(AdbPacket(AdbPacket.AUTH, AdbPacket.AUTH_TOKEN, 0, token))
- val offer = runCatching { AdbPacket.read(input) }.getOrNull() ?: return@use
- offeredKey = offer.arg0 == AdbPacket.AUTH_PUBLIC_KEY
- if (!approves) return@use
- }
- send(AdbPacket(AdbPacket.CNXN, AdbPacket.VERSION, AdbPacket.MAX_PAYLOAD, "device::\u0000".toByteArray()))
- while (true) {
- val open = runCatching { AdbPacket.read(input) }.getOrNull() ?: break
- if (open.command != AdbPacket.OPEN) continue
- opened += String(open.payload, Charsets.UTF_8).trimEnd('\u0000')
- send(AdbPacket(AdbPacket.OKAY, 77, open.arg0, ByteArray(0)))
- send(AdbPacket(AdbPacket.WRTE, 77, open.arg0, output.toByteArray()))
- AdbPacket.read(input) // OKAY
- send(AdbPacket(AdbPacket.CLSE, 77, open.arg0, ByteArray(0)))
- AdbPacket.read(input) // CLSE
- }
- }
- server.close()
- }
- }
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/airplay/CarPlayClusterDisplayTest.kt b/shared/src/test/java/com/shilapi/xcertplay/airplay/CarPlayClusterDisplayTest.kt
deleted file mode 100644
index 1f6a12374b..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/airplay/CarPlayClusterDisplayTest.kt
+++ /dev/null
@@ -1,108 +0,0 @@
-package com.shilapi.xcertplay.airplay
-
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertTrue
-import org.junit.Test
-
-class CarPlayClusterDisplayTest {
- @Test
- fun defaultClusterIsAdvertisedAsAnInputlessMapScreen() {
- val info = AirPlayInfoPlist.build(
- AirPlayConfig(
- deviceName = "test",
- deviceId = "02:00:00:00:00:02",
- btMac = "02:00:00:00:00:02",
- sourceVersion = "366.0",
- main = AirPlayDisplayConfig(widthPixels = 1280, heightPixels = 720),
- cluster = CarPlayClusterDisplay.config(1920, 720),
- ),
- )
-
- val displays = info["displays"] as List<*>
- assertEquals(2, displays.size)
- val alt = displays[1] as Map<*, *>
- assertEquals(111, alt["type"])
- // 83 % of the 1920x720 panel, same 8:3 aspect.
- assertEquals(1600, alt["widthPixels"])
- assertEquals(600, alt["heightPixels"])
- assertEquals(0, alt["features"])
- assertEquals(0, alt["primaryInputDevice"])
- assertEquals("maps:/car/instrumentcluster/map", alt["initialURL"])
- assertEquals(292, alt["widthPhysical"])
- assertEquals(110, alt["heightPhysical"])
-
- val view = (alt["viewAreas"] as List<*>).single() as Map<*, *>
- assertEquals(1600, view["widthPixels"])
- assertEquals(600, view["heightPixels"])
- val safe = view["safeArea"] as Map<*, *>
- // The centre area clear in both cluster navi modes: left 35 %, right 36 %, top 16 %, bottom 25 %.
- assertEquals(560, safe["originXPixels"])
- assertEquals(96, safe["originYPixels"])
- assertEquals(464, safe["widthPixels"])
- assertEquals(354, safe["heightPixels"])
- assertEquals(true, safe["drawUIOutsideSafeArea"])
-
- // The main screen keeps its touch and knob features.
- assertEquals(0x0A, (displays[0] as Map<*, *>)["features"])
- }
-
- @Test
- fun theDashboardCanAskForTheTurnCardInstead() {
- val card = CarPlayClusterDisplay.config(1920, 720, content = CarPlayClusterDisplay.Content.TURN_CARD)
-
- assertEquals("maps:/car/instrumentcluster/instructioncard", card.initialUrl)
- // The three contents the iPhone lists in altScreenURLs.
- assertEquals(
- listOf("maps:/car/instrumentcluster/map", "maps:/car/instrumentcluster/instructioncard", "maps:/car/instrumentcluster"),
- CarPlayClusterDisplay.Content.entries.map { it.url },
- )
- }
-
- @Test
- fun scaledStreamsKeepThePanelAspect() {
- val sizes = (CarPlayClusterDisplay.scalePresets + 50).map {
- CarPlayClusterDisplay.config(1920, 720, scalePercent = it).let { c -> c.widthPixels to c.heightPixels }
- }
-
- assertEquals(listOf(1920 to 720, 1600 to 600, 1280 to 480, 960 to 360), sizes)
- assertTrue(CarPlayClusterDisplay.STREAM_SCALE_PERCENT in CarPlayClusterDisplay.scalePresets)
- }
-
- @Test
- fun markerStepsMoveTheWholeSafeArea() {
- val centre = CarPlayClusterDisplay.config(1920, 720, scalePercent = 100).safeArea!!
- val farLeftHigher = CarPlayClusterDisplay.config(1920, 720, scalePercent = 100, horizontalStep = -2, verticalStep = -1).safeArea!!
-
- // Two 10 % steps left (384 px) and one 10 % step up (72 px), same size as the centred area.
- assertEquals(centre.left - 384, farLeftHigher.left)
- assertEquals(centre.right + 384, farLeftHigher.right)
- assertEquals(centre.top - 72, farLeftHigher.top)
- assertEquals(centre.bottom + 72, farLeftHigher.bottom)
- }
-
- @Test
- fun markerStepsAreBounded() {
- val beyond = CarPlayClusterDisplay.config(1920, 720, scalePercent = 100, horizontalStep = 9, verticalStep = -9).safeArea
- val limit = CarPlayClusterDisplay.config(1920, 720, scalePercent = 100, horizontalStep = 4, verticalStep = -3).safeArea
-
- assertEquals(limit, beyond)
- }
-
- @Test
- fun nearAnEdgeTheSafeAreaShrinksAroundTheMarker() {
- val top = CarPlayClusterDisplay.config(1000, 1000, scalePercent = 100, verticalStep = -3).safeArea!!
-
- // Marker at 15.5 % from the top: the area reaches the top edge and stays centred on it.
- assertEquals(0, top.top)
- assertEquals(310, 1000 - top.top - top.bottom)
- assertEquals(15.5, CarPlayClusterDisplay.markerPercent(0, -3).second, 0.001)
- }
-
- @Test
- fun theCarSitsNearThePanelCentre() {
- val safe = CarPlayClusterDisplay.SAFE_AREA_PERCENT
- val centreX = (safe.left + 100 - safe.right) / 2.0
-
- assertTrue("centre x $centreX", centreX in 48.0..52.0)
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/airplay/CarPlayMediaButtonTest.kt b/shared/src/test/java/com/shilapi/xcertplay/airplay/CarPlayMediaButtonTest.kt
index 36504011b3..1d2d55c87f 100644
--- a/shared/src/test/java/com/shilapi/xcertplay/airplay/CarPlayMediaButtonTest.kt
+++ b/shared/src/test/java/com/shilapi/xcertplay/airplay/CarPlayMediaButtonTest.kt
@@ -12,22 +12,18 @@ class CarPlayMediaButtonTest {
fun steeringWheelKeysMapToCarPlayMediaPresses() {
assertEquals(CarPlayMediaButton.NEXT, CarPlayMediaButton.forKeyCode(KeyEvent.KEYCODE_MEDIA_NEXT))
assertEquals(CarPlayMediaButton.PREVIOUS, CarPlayMediaButton.forKeyCode(KeyEvent.KEYCODE_MEDIA_PREVIOUS))
- // BYD rewrites its play/pause key into PLAY or PAUSE from the session state; both toggle.
+ // A head unit may rewrite its play/pause key into PLAY or PAUSE; both toggle.
assertEquals(CarPlayMediaButton.PLAY_PAUSE, CarPlayMediaButton.forKeyCode(KeyEvent.KEYCODE_MEDIA_PLAY))
assertEquals(CarPlayMediaButton.PLAY_PAUSE, CarPlayMediaButton.forKeyCode(KeyEvent.KEYCODE_MEDIA_PAUSE))
assertEquals(CarPlayMediaButton.PLAY_PAUSE, CarPlayMediaButton.forKeyCode(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE))
assertEquals(CarPlayMediaButton.PLAY_PAUSE, CarPlayMediaButton.forKeyCode(KeyEvent.KEYCODE_HEADSETHOOK))
- assertEquals(CarPlayMediaButton.PLAY_PAUSE, CarPlayMediaButton.forKeyCode(353))
}
@Test
fun theVoiceKeyOpensSiri() {
- // Recorded on DiLink 5.0: short press 304 (scan 290), long press 312 (scan 312).
- assertTrue(CarPlayMediaButton.opensSiri(304))
- assertTrue(CarPlayMediaButton.opensSiri(312))
assertTrue(CarPlayMediaButton.opensSiri(KeyEvent.KEYCODE_VOICE_ASSIST))
assertFalse(CarPlayMediaButton.opensSiri(KeyEvent.KEYCODE_MEDIA_NEXT))
- assertNull(CarPlayMediaButton.forKeyCode(304))
+ assertNull(CarPlayMediaButton.forKeyCode(KeyEvent.KEYCODE_VOICE_ASSIST))
}
@Test
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydBatteryReadinessTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydBatteryReadinessTest.kt
deleted file mode 100644
index 423b1eb785..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydBatteryReadinessTest.kt
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import com.shilapi.xcertplay.transport.Iap2IdentificationConfig
-import com.shilapi.xcertplay.transport.withVehicleStatusFrom
-import org.junit.Assert.*
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.robolectric.RobolectricTestRunner
-import org.robolectric.RuntimeEnvironment
-import org.robolectric.annotation.Config
-import org.robolectric.shadows.ShadowSystemClock
-import java.time.Duration
-
-@RunWith(RobolectricTestRunner::class)
-@Config(sdk = [29], manifest = Config.NONE)
-class BydBatteryReadinessTest {
- private val context get() = RuntimeEnvironment.getApplication()
- private val reading = BydBatteryReading(25.0, 150, 25.1, false)
- private val identification = Iap2IdentificationConfig(
- name = "test", modelIdentifier = "test", manufacturer = "test", serialNumber = "test",
- firmwareVersion = "1", hardwareVersion = "1", carPlayUsbInterfaceNumber = 3,
- vehicleStatusEnabled = true,
- )
-
- @Test
- fun delayedAdbApprovalPrimesTheNextConnectionFromTheSettingsCheck() {
- val unavailable = BydAdbAccess.readStatus(context) { null }
- assertNull(unavailable.batteryPercent)
- assertFalse(identification.withVehicleStatusFrom(BydBatteryStatus).vehicleStatusEnabled)
-
- // A successful settings check after approval must prime the provider, not just its label.
- val ready = BydAdbAccess.readStatus(context) { command ->
- val bits = when (command.substringAfterLast(' ')) {
- "1246777400" -> "41c80000"
- "1246765118" -> "00000096"
- "882901008" -> "41c8cccd"
- "876609560" -> "0000000f"
- else -> "00000003"
- }
- "Result: Parcel(00000000 $bits '........')"
- }
- assertEquals(25.0, ready.batteryPercent!!, 0.001)
- assertTrue(identification.withVehicleStatusFrom(BydBatteryStatus).vehicleStatusEnabled)
- assertEquals(150, BydBatteryStatus.snapshot()!!.rangeKm)
- reconnectAfterIdleRefreshesWithoutWaitingForThePeriodicTick()
- }
-
- private fun reconnectAfterIdleRefreshesWithoutWaitingForThePeriodicTick() {
- BydBatteryStatus.readBattery = { reading }
- ShadowSystemClock.advanceBy(Duration.ofMinutes(4))
- BydBatteryStatus.start(context)
- awaitReading()
- ShadowSystemClock.advanceBy(Duration.ofMinutes(4))
- assertNull(BydBatteryStatus.snapshot())
- assertFalse(identification.withVehicleStatusFrom(BydBatteryStatus).vehicleStatusEnabled)
-
- BydBatteryStatus.start(context)
- awaitReading()
- assertTrue(identification.withVehicleStatusFrom(BydBatteryStatus).vehicleStatusEnabled)
- }
-
- @Test
- fun staleReadingBecomesUsableAgainOnlyAfterFreshDataIsPublished() {
- var clock = 0L
- val cache = BydBatteryCache { clock }
- cache.accept(reading)
- clock += 181_000
- assertNull(cache.snapshot(20))
- cache.accept(BydBatteryReading(10.0, 60, 10.0, false))
- val fresh = cache.snapshot(20)!!
- assertEquals(10.0, fresh.batteryPercent, 0.001)
- assertEquals(100_400L, fresh.maxChargeWh)
- }
-
- private fun awaitReading() {
- val deadline = System.nanoTime() + 2_000_000_000L
- while (BydBatteryStatus.snapshot() == null && System.nanoTime() < deadline) Thread.sleep(5)
- assertNotNull("refresh should complete before the 30-second periodic tick", BydBatteryStatus.snapshot())
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydBatteryTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydBatteryTest.kt
deleted file mode 100644
index f6fed38fef..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydBatteryTest.kt
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertNull
-import org.junit.Assert.assertTrue
-import org.junit.Test
-
-class BydBatteryTest {
- // Replies from the car on 2026-09-28: 25 %, 150 km, 25.1 kWh left, not charging (BMS state 15).
- private val car = mapOf(
- "1246777400" to "Result: Parcel(00000000 41c80000 '.......A')",
- "1246765118" to "Result: Parcel(00000000 00000096 '........')",
- "882901008" to "Result: Parcel(00000000 41c8cccd '.......A')",
- "876609560" to "Result: Parcel(00000000 0000000f '........')",
- )
-
- private fun shell(replies: Map): (String) -> String? = { command ->
- replies.entries.firstOrNull { command.endsWith(" ${it.key}") }?.value
- }
-
- @Test
- fun readsTheCarsReplies() {
- val reading = BydBattery.read(shell(car))!!
-
- assertEquals(25.0, reading.percent, 0.001)
- assertEquals(150, reading.rangeKm)
- assertEquals(25.1, reading.remainingKwh, 0.001)
- assertFalse(reading.charging)
- }
-
- @Test
- fun noAdbAccessGivesNoReading() {
- // BydAdbShell answers null while adbd is off, refuses DiPlay's key or waits for approval.
- assertNull(BydBattery.read { null })
- }
-
- @Test
- fun aMissingOrRejectedValueGivesNoReading() {
- assertNull(BydBattery.read(shell(car - "1246765118")))
- assertNull(BydBattery.read(shell(car + ("1246777400" to "Result: Parcel(ffffd8e5 '....')"))))
- }
-
- @Test
- fun theIphoneGetsWattHoursAndAWarningAtTheThreshold() {
- val reading = BydBatteryReading(percent = 25.0, rangeKm = 150, remainingKwh = 25.1, charging = false)
-
- val above = BydBattery.snapshot(reading, lowPercent = 20, fullKwh = null)
- assertFalse(above.rangeWarning)
- assertEquals(25_100L, above.currentChargeWh)
- assertEquals(100_400L, above.maxChargeWh)
- assertEquals(600, above.maxRangeKm)
-
- assertTrue(BydBattery.snapshot(reading, lowPercent = 25, fullKwh = null).rangeWarning)
- }
-
- @Test
- fun aLowChargeKeepsTheEarlierFullChargeEstimate() {
- val high = BydBatteryReading(percent = 80.0, rangeKm = 480, remainingKwh = 80.0, charging = false)
- val low = BydBatteryReading(percent = 5.0, rangeKm = 30, remainingKwh = 5.6, charging = false)
-
- assertNull(BydBattery.fullKwh(low))
- assertEquals(100_000L, BydBattery.snapshot(low, lowPercent = 20, fullKwh = BydBattery.fullKwh(high)).maxChargeWh)
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterFrameTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterFrameTest.kt
deleted file mode 100644
index feeca4b896..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterFrameTest.kt
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.assertEquals
-import org.junit.Test
-
-class BydClusterFrameTest {
- @Test
- fun `maps basic turns to amap icons`() {
- assertEquals(BydClusterFrame(2, 0, 53), frame(type = 1, distance = 53))
- assertEquals(BydClusterFrame(3, 0, 53), frame(type = 2, distance = 53))
- assertEquals(BydClusterFrame(9, 0, 53), frame(type = 3, distance = 53))
- assertEquals(BydClusterFrame(4, 0, 53), frame(type = 49, distance = 53))
- assertEquals(BydClusterFrame(5, 0, 53), frame(type = 14, distance = 53))
- }
-
- @Test
- fun `numbered roundabout exit carries exit number`() {
- assertEquals(BydClusterFrame(11, 2, 120), frame(type = 29, distance = 120))
- assertEquals(BydClusterFrame(17, 2, 120), frame(type = 29, distance = 120, drivingSide = 1))
- }
-
- @Test
- fun `u-turn follows driving side and arrival is destination`() {
- assertEquals(8, frame(type = 4).icon)
- assertEquals(19, frame(type = 4, drivingSide = 1).icon)
- assertEquals(15, frame(type = 12).icon)
- }
-
- @Test
- fun `negative distance is clamped`() {
- assertEquals(0, frame(type = 1, distance = -5).distanceMeters)
- }
-
- @Test fun `unknown maneuver is not advertised as straight`() {
- for (type in listOf(0, 15, 16, 17, 54, 255)) assertEquals(0, frame(type).icon)
- for (type in listOf(3, 5, 8, 9, 11, 51)) assertEquals(9, frame(type).icon)
- }
-
- private fun frame(type: Int, distance: Int = 0, drivingSide: Int = 0) =
- BydClusterFrame.from(BydAppleManeuver(distance, type, drivingSide))
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterMapPauseTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterMapPauseTest.kt
deleted file mode 100644
index 5e8f298c75..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterMapPauseTest.kt
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.After
-import org.junit.Assert.assertTrue
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.robolectric.RobolectricTestRunner
-import org.robolectric.RuntimeEnvironment
-import org.robolectric.annotation.Config
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.TimeUnit
-import kotlin.concurrent.thread
-
-@RunWith(RobolectricTestRunner::class)
-@Config(sdk = [29], manifest = Config.NONE)
-class BydClusterMapPauseTest {
- private val context get() = RuntimeEnvironment.getApplication()
- private val release = CountDownLatch(1)
-
- @After
- fun tearDown() {
- release.countDown()
- BydClusterMapPause.streamControl = null
- BydClusterMapPause.clusterMapShown = false
- }
-
- @Test
- fun initializationDoesNotWaitForAPendingAdbRead() {
- val reading = CountDownLatch(1)
- // An adbd that accepted the read and has not answered yet.
- BydClusterMapPause.readMode = {
- reading.countDown()
- release.await()
- null
- }
- BydOutputSettings.setClusterStreamPause(context, true)
- BydClusterMapPause.clusterMapShown = true
- BydClusterMapPause.streamControl = {}
- BydClusterMapPause.initialize(context)
- assertTrue("the ticker should start reading", reading.await(5, TimeUnit.SECONDS))
-
- val initialized = CountDownLatch(1)
- thread { BydClusterMapPause.initialize(context); initialized.countDown() }
-
- assertTrue("initialize() waited for the adb read", initialized.await(1, TimeUnit.SECONDS))
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterNaviModeTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterNaviModeTest.kt
deleted file mode 100644
index 48bdbe602e..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydClusterNaviModeTest.kt
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertNull
-import org.junit.Test
-
-class BydClusterNaviModeTest {
- @Test
- fun readsTheModeFromServiceCallOutput() {
- assertEquals(BydClusterNaviMode.TURN_ON_BY_NAVI, BydClusterNaviMode.parseRead("Result: Parcel(00000000 00000002 '........')"))
- assertEquals(BydClusterNaviMode.FULL, BydClusterNaviMode.parseRead("Result: Parcel(00000000 00000004 '........')"))
- // An exception code in the first word, an unknown value, or no parcel at all.
- assertNull(BydClusterNaviMode.parseRead("Result: Parcel(ffffffff 00000002 '........')"))
- assertNull(BydClusterNaviMode.parseRead("Result: Parcel(00000000 00000009 '........')"))
- assertNull(BydClusterNaviMode.parseRead(null))
- }
-
- @Test
- fun onlySmallAndFullShowTheMap() {
- assertEquals(
- listOf(BydClusterNaviMode.SMALL, BydClusterNaviMode.FULL),
- BydClusterNaviMode.entries.filter { it.showsMap },
- )
- }
-
- @Test
- fun readsTheVerifiedId() {
- assertEquals("service call autoservice 5 i32 1007 i32 1086337074", BydClusterNaviMode.READ_COMMAND)
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydFactoryTurnCodeTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydFactoryTurnCodeTest.kt
deleted file mode 100644
index 49e3f0f9e8..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydFactoryTurnCodeTest.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.*
-import org.junit.Test
-
-class BydFactoryTurnCodeTest {
- @Test fun factoryUsesDifferentCodesFromBroadcasts() {
- assertEquals(1, BydFactoryTurnCode.map(2, 0))
- assertEquals(2, BydFactoryTurnCode.map(3, 0))
- assertEquals(5, BydFactoryTurnCode.map(5, 0))
- assertEquals(11, BydFactoryTurnCode.map(9, 0))
- assertEquals(48, BydFactoryTurnCode.map(15, 0))
- }
- @Test fun roundaboutDirectionAndBounds() {
- assertEquals(25, BydFactoryTurnCode.map(11, 1))
- assertEquals(34, BydFactoryTurnCode.map(12, 10))
- assertEquals(35, BydFactoryTurnCode.map(17, 1))
- assertEquals(44, BydFactoryTurnCode.map(18, 10))
- assertEquals(13, BydFactoryTurnCode.map(11, 11))
- assertEquals(14, BydFactoryTurnCode.map(17, 0))
- }
- @Test fun invalidInstructionsAreNotMadeIntoStraightArrows() {
- assertNull(BydFactoryTurnCode.map(-1, 0))
- assertNull(BydFactoryTurnCode.map(0, 0))
- assertNull(BydFactoryTurnCode.map(29, 0))
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudPayloadTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudPayloadTest.kt
deleted file mode 100644
index 33763a7350..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudPayloadTest.kt
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.assertArrayEquals
-import org.junit.Test
-
-class BydHudPayloadTest {
- @Test
- fun guidanceMatchesFixedFieldTwoWireFixture() {
- assertArrayEquals(
- byteArrayOf(
- 0x0a, 0x15, 0x10, 0x02, 0x30, 0x01, 0x3a, 0x00, 0x42, 0x00,
- 0x48, 0x35, 0x52, 0x00, 0x80.toByte(), 0x01, 0x02,
- 0xd2.toByte(), 0x01, 0x00, 0xe0.toByte(), 0x01, 0x01,
- ),
- BydHudPayload.guidance(distanceMeters = 53, maneuver = 1),
- )
- }
-
- @Test
- fun shortDistanceIsLiftedAndTextIsCarried() {
- val payload = BydHudPayload.guidance(distanceMeters = 4, maneuver = 11, road = "A", eta = "14:36")
- val hex = payload.joinToString("") { "%02x".format(it) }
- assert(hex.contains("480b")) { hex } // field 9 = 11 m
- assert(hex.contains("520141")) { hex } // field 10 = "A"
- assert(hex.contains("d20105" + "31343a3336")) { hex } // field 26 = "14:36"
- }
-
- @Test
- fun clearMatchesBydDirectClear() {
- assertArrayEquals(
- byteArrayOf(0x0a, 0x08, 0x10, 0x02, 0x30, 0xff.toByte(), 0x01, 0x80.toByte(), 0x01, 0x01),
- BydHudPayload.clear(),
- )
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudProtocolTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudProtocolTest.kt
deleted file mode 100644
index 9ba6bf7dfc..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudProtocolTest.kt
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.*
-import org.junit.Test
-
-class BydHudProtocolTest {
- @Test fun onlyStartAcceptsAlreadyStarted() {
- assertTrue(BydHudProtocol.serviceStarted(0))
- assertTrue(BydHudProtocol.serviceStarted(13))
- assertTrue(BydHudProtocol.eventAccepted(0))
- assertFalse(BydHudProtocol.eventAccepted(13))
- }
- @Test fun positiveGatewayErrorsAreNotSuccess() {
- for (code in listOf(-1, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 15)) {
- assertFalse("start=$code", BydHudProtocol.serviceStarted(code))
- assertFalse("event=$code", BydHudProtocol.eventAccepted(code))
- }
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudRouteStateTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudRouteStateTest.kt
deleted file mode 100644
index bc0e49803d..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydHudRouteStateTest.kt
+++ /dev/null
@@ -1,173 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import java.io.ByteArrayOutputStream
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertNull
-import org.junit.Test
-
-class BydHudRouteStateTest {
- @Test
- fun `combines maneuver and route updates`() {
- val state = BydHudRouteState()
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE,
- tlvs(tlv(0x01, 0, 7), tlv(0x03, 1), tlv(0x08, 0)),
- )
-
- val change = state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_UPDATE,
- tlvs(tlv(0x01, 1), tlv(0x0a, 0, 0, 0, 150), tlv(0x0d, 0, 7)),
- )
-
- assertEquals(BydHudRouteChange.GUIDANCE, change)
- assertEquals(BydHudGuidance(distanceMeters = 150, maneuver = 1, gaode = 1), state.current())
- }
-
- @Test
- fun `maps right-hand u-turn`() {
- val state = BydHudRouteState()
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE,
- tlvs(tlv(0x01, 0, 3), tlv(0x03, 4), tlv(0x08, 1)),
- )
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_UPDATE,
- tlvs(tlv(0x01, 1), tlv(0x0a, 0, 0, 0, 50), tlv(0x0d, 0, 3)),
- )
-
- assertEquals(BydHudGuidance(distanceMeters = 50, maneuver = 8, gaode = 10), state.current())
- }
-
- @Test
- fun `route end clears guidance`() {
- val state = populatedState()
-
- val change = state.accept(BydHudRouteState.ROUTE_GUIDANCE_UPDATE, tlvs(tlv(0x01, 2)))
-
- assertEquals(BydHudRouteChange.CLEAR, change)
- assertNull(state.current())
- }
-
- @Test
- fun `malformed frame does not alter active guidance`() {
- val state = populatedState()
- val before = state.current()
-
- val change = state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_UPDATE,
- byteArrayOf(0, 8, 0, 1, 1),
- )
-
- assertEquals(BydHudRouteChange.NONE, change)
- assertEquals(before, state.current())
- }
-
-
- @Test
- fun `carries after-maneuver road and arrival time`() {
- val state = BydHudRouteState()
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE,
- tlvs(tlv(0x01, 0, 2), tlv(0x03, 2), tlv(0x04, *utf8z("Am Wehr")), tlv(0x08, 0)),
- )
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_UPDATE,
- tlvs(
- tlv(0x01, 1), tlv(0x03, *utf8z("Hauptstraße")), tlv(0x05, 0, 0, 0, 0, 0x68, 0xd5, 0x2a, 0x40),
- tlv(0x0a, 0, 0, 1, 44), tlv(0x0d, 0, 2),
- ),
- )
-
- val guidance = state.current()!!
- assertEquals("Am Wehr", guidance.road)
- assertEquals(0x68d52a40L, guidance.arrivalEpochSeconds)
- assertEquals(300, guidance.distanceMeters)
- }
-
- @Test
- fun `brief empty maneuver list keeps guidance and a lasting one hides it without losing maneuvers`() {
- var now = 0L
- val state = populatedState { now }
-
- assertEquals(BydHudRouteChange.NONE, state.accept(BydHudRouteState.ROUTE_GUIDANCE_UPDATE, tlvs(tlv(0x01, 5), tlv(0x0d))))
- now = 2_000_000_000L
- assertEquals(2, state.current()!!.maneuver) // a blip does not blank the outputs
- now = 3_100_000_000L
- assertNull(state.current())
-
- // The iPhone lists the same maneuver again without resending its 0x5202 details.
- val resumed = state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_UPDATE,
- tlvs(tlv(0x01, 1), tlv(0x0a, 0, 0, 0, 20), tlv(0x0d, 0, 1)),
- )
- assertEquals(BydHudRouteChange.GUIDANCE, resumed)
- assertEquals(2, state.current()!!.maneuver)
- }
-
- @Test
- fun `falls back to current road`() {
- val state = BydHudRouteState()
- state.accept(BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE, tlvs(tlv(0x01, 0, 0), tlv(0x03, 1)))
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_UPDATE,
- tlvs(tlv(0x01, 1), tlv(0x03, *utf8z("Hauptstraße")), tlv(0x0d, 0, 0)),
- )
- assertEquals("Hauptstraße", state.current()!!.road)
- }
-
- @Test
- fun `roundabout exit has blank arrow and exit icon`() {
- val state = BydHudRouteState()
- state.accept(BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE, tlvs(tlv(0x01, 0, 0), tlv(0x03, 29)))
- state.accept(BydHudRouteState.ROUTE_GUIDANCE_UPDATE, tlvs(tlv(0x01, 1), tlv(0x0d, 0, 0)))
- val guidance = state.current()!!
- assertEquals(99, guidance.maneuver)
- assertEquals(26, guidance.gaode)
- }
-
- @Test
- fun `silent route expires and fresh update restores cached maneuver`() {
- var now = 0L
- val state = populatedState { now }
- now = 30_000_000_000L
- assertNull(state.current())
- state.accept(BydHudRouteState.ROUTE_GUIDANCE_UPDATE, tlvs(tlv(0x0a, 0, 0, 0, 20)))
- assertEquals(20, state.current()!!.distanceMeters)
- }
-
- @Test
- fun `clear prevents a keepalive from restoring guidance`() {
- val state = populatedState()
- state.clear()
- assertNull(state.current())
- assertNull(state.currentApple())
- }
-
- private fun utf8z(value: String): IntArray =
- (value.toByteArray(Charsets.UTF_8).map { it.toInt() and 0xff } + 0).toIntArray()
-
- private fun populatedState(nanoTime: () -> Long = System::nanoTime): BydHudRouteState =
- BydHudRouteState(nanoTime).also { state ->
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_MANEUVER_UPDATE,
- tlvs(tlv(0x01, 0, 1), tlv(0x03, 2), tlv(0x08, 0)),
- )
- state.accept(
- BydHudRouteState.ROUTE_GUIDANCE_UPDATE,
- tlvs(tlv(0x01, 1), tlv(0x0a, 0, 0, 0, 25), tlv(0x0d, 0, 1)),
- )
- }
-
- private fun tlv(type: Int, vararg value: Int): ByteArray = ByteArrayOutputStream().apply {
- val length = value.size + 4
- write(length ushr 8)
- write(length)
- write(type ushr 8)
- write(type)
- value.forEach(::write)
- }.toByteArray()
-
- private fun tlvs(vararg values: ByteArray): ByteArray = ByteArrayOutputStream().apply {
- values.forEach(::write)
- }.toByteArray()
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydParkedStateTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydParkedStateTest.kt
deleted file mode 100644
index 9fc5dc239f..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydParkedStateTest.kt
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertNull
-import org.junit.Test
-
-class BydParkedStateTest {
- @Test
- fun readsTheGearboxReply() {
- assertEquals(true, BydParkedState.parked("Result: Parcel(00000000 00000001 '........')"))
- assertEquals(false, BydParkedState.parked("Result: Parcel(00000000 00000004 '........')"))
- assertEquals(false, BydParkedState.parked("Result: Parcel(00000000 00000002 '........')"))
- }
-
- @Test
- fun unknownGearIsNotParked() {
- assertNull(BydParkedState.parked(null))
- assertNull(BydParkedState.parked("Result: Parcel(00000000 00000000 '........')"))
- assertNull(BydParkedState.parked("Result: Parcel(ffffffff 00000001 '........')"))
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydStandaloneSessionTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydStandaloneSessionTest.kt
deleted file mode 100644
index d82e991824..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydStandaloneSessionTest.kt
+++ /dev/null
@@ -1,119 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.*
-import org.junit.Test
-
-class BydStandaloneSessionTest {
- private class Rig(recovery: Boolean = false) {
- var now = 0L
- var failPacket: String? = null
- var journalFails = false
- val events = mutableListOf()
- val session = BydStandaloneSession(
- send = { packet ->
- events += packet
- if (packet == failPacket) throw IllegalStateException("dispatch failed")
- },
- rememberPendingClear = { dirty ->
- if (journalFails) throw IllegalStateException("disk failed")
- events += "pending=$dirty"
- },
- needsRecovery = recovery,
- nanoTime = { now },
- )
- }
-
- @Test fun startsOnceUpdatesTurnAndClearsOnRouteEnd() {
- val r = Rig()
- r.session.update(2, 0, 500)
- r.session.update(3, 0, 800)
- r.session.clear()
- assertEquals(listOf("pending=true", BydStandalonePackets.start(),
- BydStandalonePackets.guidance(2, 0, 500), BydStandalonePackets.guidance(3, 0, 800),
- BydStandalonePackets.clear(), "pending=false"), r.events)
- r.session.clear()
- assertEquals(6, r.events.size)
- }
-
- @Test fun unchangedGuidanceIsRateLimitedButKeptAlive() {
- val r = Rig()
- r.session.update(9, 0, 0)
- repeat(9) { r.now += 100_000_000L; r.session.update(9, 0, 0) }
- assertEquals(3, r.events.size)
- r.now = 1_000_000_000L
- r.session.update(9, 0, 0)
- assertEquals(4, r.events.size)
- }
-
- @Test fun unknownManeuverEndsGuidanceInsteadOfInventingStraight() {
- val r = Rig()
- r.session.update(2, 0, 500)
- r.session.update(0, 0, 500)
- assertEquals(listOf(BydStandalonePackets.clear(), "pending=false"), r.events.takeLast(2))
- val count = r.events.size
- r.session.update(999, 0, 500)
- assertEquals(count, r.events.size)
- }
-
- @Test fun invalidDistanceEndsGuidance() {
- val r = Rig()
- r.session.update(2, 0, 500)
- r.session.update(2, 0, 16777215)
- assertEquals(BydStandalonePackets.clear(), r.events[r.events.lastIndex - 1])
- assertNull(BydStandalonePackets.guidance(2, 0, -1))
- assertNotNull(BydStandalonePackets.guidance(2, 0, 16777214))
- }
-
- @Test fun failedGuidanceAfterStartSendsEndAndNextUpdateStartsAgain() {
- val r = Rig()
- r.failPacket = BydStandalonePackets.guidance(2, 0, 500)
- assertThrows(IllegalStateException::class.java) { r.session.update(2, 0, 500) }
- assertEquals(listOf(BydStandalonePackets.clear(), "pending=false"), r.events.takeLast(2))
- r.failPacket = null
- r.events.clear()
- r.session.update(3, 0, 800)
- assertEquals(listOf("pending=true", BydStandalonePackets.start()), r.events.take(2))
- }
-
- @Test fun failedEndIsRetriedBeforeAnyNewGuidance() {
- val r = Rig()
- r.session.update(2, 0, 500)
- r.failPacket = BydStandalonePackets.clear()
- assertThrows(IllegalStateException::class.java) { r.session.clear() }
- r.events.clear()
- assertThrows(IllegalStateException::class.java) { r.session.update(3, 0, 800) }
- assertEquals(listOf(BydStandalonePackets.clear()), r.events)
- r.failPacket = null
- r.events.clear()
- r.session.update(3, 0, 800)
- assertEquals(listOf(BydStandalonePackets.clear(), "pending=false", "pending=true",
- BydStandalonePackets.start(), BydStandalonePackets.guidance(3, 0, 800)), r.events)
- }
-
- @Test fun interruptedSessionClearsBeforeItStartsAnotherRoute() {
- val r = Rig(recovery = true)
- r.session.update(2, 0, 500)
- assertEquals(listOf(BydStandalonePackets.clear(), "pending=false", "pending=true",
- BydStandalonePackets.start()), r.events.take(4))
- }
-
- @Test fun cannotStartIfRecoveryJournalCannotBeSaved() {
- val r = Rig()
- r.journalFails = true
- assertThrows(IllegalStateException::class.java) { r.session.update(2, 0, 500) }
- assertTrue(r.events.isEmpty())
- }
-
- @Test fun fixedWireVectorsAndRoundaboutMapping() {
- assertEquals("43,E0,00,3A,01,02", BydStandalonePackets.start())
- assertEquals("43,E0,00,3A,01,01", BydStandalonePackets.clear())
- assertEquals("43,F0,10,18,04,00,00,01,F4,43,F0,10,10,04,00,00,00,01,43,F0,10,30,04,00,00,00,01",
- BydStandalonePackets.guidance(2, 0, 500))
- assertEquals("43,F0,10,18,04,00,00,03,20,43,F0,10,10,04,00,00,00,02,43,F0,10,30,04,00,00,00,02",
- BydStandalonePackets.guidance(3, 0, 800))
- val bytes = BydStandalonePackets.guidance(11, 10, 0)!!.split(',')
- assertEquals(27, bytes.size)
- assertEquals("22", bytes[17]) // Factory right-roundabout exit 10 = 34.
- assertEquals("22", bytes[26])
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydStandaloneStreetTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydStandaloneStreetTest.kt
deleted file mode 100644
index 6b9a45861f..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydStandaloneStreetTest.kt
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import org.junit.Assert.*
-import org.junit.Test
-
-class BydStandaloneStreetTest {
- private fun content(road: String): ByteArray {
- val bytes = BydStandalonePackets.streetName(road).split(',').map { it.toInt(16).toByte() }
- assertTrue(bytes.size <= 182)
- return bytes.chunked(13).flatMapIndexed { index, record ->
- assertEquals(13, record.size)
- assertEquals(0x43, record[0].toInt() and 255)
- assertEquals(0xFA, record[1].toInt() and 255)
- assertEquals((index + 1) shl 4, record[2].toInt() and 255)
- assertEquals(8, record[3].toInt() and 255)
- assertEquals(8, record[4].toInt() and 255)
- assertEquals(0xA1 + index, record[5].toInt() and 255)
- record.drop(6)
- }.toByteArray()
- }
- private fun decoded(road: String): String {
- val data = content(road)
- val size = data[0].toInt() and 255
- val text = data.copyOfRange(1, size + 1)
- assertEquals(text.sumOf { it.toInt() and 255 } and 255, data[size + 1].toInt() and 255)
- assertTrue(data.drop(size + 2).all { it == 0xFF.toByte() })
- return text.toString(Charsets.UTF_16LE)
- }
- @Test fun matchesActualArm64EncoderEnglishAndArabicVectors() {
- assertEquals("43,FA,10,08,08,A1,16,4D,00,75,00,73,00,43,FA,20,08,08,A2,63,00,61,00,74,00,20,43,FA,30,08,08,A3,00,52,00,6F,00,61,00,43,FA,40,08,08,A4,64,00,13,FF,FF,FF,FF", BydStandalonePackets.streetName("Muscat Road"))
- assertEquals("43,FA,10,08,08,A1,12,34,06,27,06,31,06,43,FA,20,08,08,A2,39,06,20,00,45,06,33,43,FA,30,08,08,A3,06,42,06,37,06,06,FF", BydStandalonePackets.streetName("شارع مسقط"))
- }
- @Test fun textIsBoundedWithoutBreakingUnicodePairs() {
- assertEquals("A".repeat(48), decoded("A".repeat(500)))
- assertEquals("A".repeat(47), decoded("A".repeat(47) + "🚗End"))
- assertEquals("A".repeat(46) + "🚗", decoded("A".repeat(46) + "🚗End"))
- assertEquals("AB", decoded("A\uD800B\uDC00"))
- }
- @Test fun blankAndControlsReplacePriorTextWithSafeWhitespace() {
- assertEquals(" ", decoded(""))
- assertEquals(" ", decoded("\n\u0000\t"))
- assertEquals("A B C", decoded("A\u0000B\nC"))
- }
- @Test fun everyBoundaryHasCorrectLengthChecksumPaddingAndReceiverBound() {
- for (length in 1..48) {
- val road = "R".repeat(length)
- assertEquals(road, decoded(road))
- assertTrue(BydStandalonePackets.guidance(2, 0, 500, road)!!.split(',').size <= 252)
- }
- }
- @Test fun changedStreetIsPublishedAndMissingStreetReplacesIt() {
- val sent = mutableListOf()
- val session = BydStandaloneSession(sent::add, {}, nanoTime = { 0L })
- session.update(2, 0, 500, "First Road")
- session.update(2, 0, 500, "Second Road")
- assertEquals(BydStandalonePackets.guidance(2, 0, 500, "Second Road"), sent.last())
- val count = sent.size
- session.update(2, 0, 500, "Second Road")
- assertEquals(count, sent.size)
- session.update(2, 0, 500, "")
- assertEquals(BydStandalonePackets.guidance(2, 0, 500, ""), sent.last())
- session.clear()
- assertEquals(BydStandalonePackets.clear(), sent.last())
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/BydWheelSpeedTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/BydWheelSpeedTest.kt
deleted file mode 100644
index 2bb6ff8e6c..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/BydWheelSpeedTest.kt
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import com.shilapi.xcertplay.transport.VehicleGear
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertNull
-import org.junit.Test
-
-class BydWheelSpeedTest {
- @Test
- fun readsSpeedInMetersPerSecond() {
- // The car's reply while parked on 2026-09-29, then 36.0 km/h.
- assertEquals(0.0, BydWheelSpeed.metersPerSecond("Result: Parcel(00000000 00000000 '........')")!!, 1e-9)
- assertEquals(10.0, BydWheelSpeed.metersPerSecond("Result: Parcel(00000000 42100000 '.......B')")!!, 1e-6)
- }
-
- @Test
- fun rejectsMissingOrImpossibleSpeed() {
- assertNull(BydWheelSpeed.metersPerSecond(null))
- assertNull(BydWheelSpeed.metersPerSecond("Result: Parcel(ffffffff 00000000 '........')"))
- assertNull(BydWheelSpeed.metersPerSecond("Result: Parcel(00000000 bf800000 '........')")) // -1.0
- assertNull(BydWheelSpeed.metersPerSecond("Result: Parcel(00000000 7fc00000 '........')")) // NaN
- }
-
- @Test
- fun mapsGears() {
- assertEquals(VehicleGear.PARK, BydWheelSpeed.gear("Result: Parcel(00000000 00000001 '........')"))
- assertEquals(VehicleGear.REVERSE, BydWheelSpeed.gear("Result: Parcel(00000000 00000002 '........')"))
- assertEquals(VehicleGear.NEUTRAL, BydWheelSpeed.gear("Result: Parcel(00000000 00000003 '........')"))
- assertEquals(VehicleGear.DRIVE, BydWheelSpeed.gear("Result: Parcel(00000000 00000004 '........')"))
- assertNull(BydWheelSpeed.gear("Result: Parcel(00000000 00000000 '........')"))
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/hud/NavigationOutputWorkerTest.kt b/shared/src/test/java/com/shilapi/xcertplay/hud/NavigationOutputWorkerTest.kt
deleted file mode 100644
index d7382d1758..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/hud/NavigationOutputWorkerTest.kt
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.shilapi.xcertplay.hud
-
-import java.util.concurrent.CountDownLatch
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.atomic.AtomicInteger
-import org.junit.Assert.*
-import org.junit.Test
-
-class NavigationOutputWorkerTest {
- private fun await(latch: CountDownLatch) = assertTrue(latch.await(3, TimeUnit.SECONDS))
-
- @Test fun `blocked HUD does not block caller or independent cluster`() {
- val entered = CountDownLatch(1)
- val release = CountDownLatch(1)
- val clusterRan = CountDownLatch(1)
- val hud = NavigationOutputWorker("test-hud") {}
- val cluster = NavigationOutputWorker("test-cluster") {}
- hud.start {}
- cluster.start {}
- try {
- hud.submit { entered.countDown(); release.await(3, TimeUnit.SECONDS) }
- await(entered)
- cluster.submit { clusterRan.countDown() }
- await(clusterRan)
- } finally { release.countDown(); hud.clear(); cluster.clear() }
- }
-
- @Test fun `clear discards pending guidance and rejects late frames until restart`() {
- val entered = CountDownLatch(1)
- val release = CountDownLatch(1)
- val cleared = CountDownLatch(1)
- val starts = AtomicInteger()
- val frames = AtomicInteger()
- val worker = NavigationOutputWorker("test-cleanup") { if (starts.get() > 0) cleared.countDown() }
- worker.start { starts.incrementAndGet() }
- try {
- worker.submit { entered.countDown(); release.await(3, TimeUnit.SECONDS) }
- await(entered)
- worker.submit { frames.incrementAndGet() }
- worker.clear()
- worker.submit { frames.incrementAndGet() }
- release.countDown()
- await(cleared)
- assertEquals(0, frames.get())
- val resumed = CountDownLatch(1)
- worker.start {}
- worker.submit { resumed.countDown() }
- await(resumed)
- } finally { release.countDown(); worker.clear() }
- }
-
- @Test fun `overflow clears incremental stream instead of replaying partial route`() {
- val entered = CountDownLatch(1)
- val release = CountDownLatch(1)
- val cleared = CountDownLatch(1)
- val initialized = CountDownLatch(1)
- val frames = AtomicInteger()
- val worker = NavigationOutputWorker("test-overflow") { if (initialized.count == 0L) cleared.countDown() }
- worker.start { initialized.countDown() }
- await(initialized)
- try {
- worker.submit { entered.countDown(); release.await(3, TimeUnit.SECONDS) }
- await(entered)
- repeat(140) { worker.submit { frames.incrementAndGet() } }
- release.countDown()
- await(cleared)
- assertEquals(0, frames.get())
- } finally { release.countDown(); worker.clear() }
- }
-}
diff --git a/shared/src/test/java/com/shilapi/xcertplay/orchestration/VideoInCarGateTest.kt b/shared/src/test/java/com/shilapi/xcertplay/orchestration/VideoInCarGateTest.kt
deleted file mode 100644
index 18395f7953..0000000000
--- a/shared/src/test/java/com/shilapi/xcertplay/orchestration/VideoInCarGateTest.kt
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.shilapi.xcertplay.orchestration
-
-import com.shilapi.xcertplay.airplay.VideoInCar
-import org.junit.After
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Test
-
-class VideoInCarGateTest {
- @After
- fun reset() {
- VideoInCar.allowed = false
- }
-
- @Test
- fun videoIsAllowedOnlyWhileTheGearReadsPark() {
- val changes = mutableListOf()
- val gate = VideoInCarGate({ null }) { changes += it }
-
- gate.update(null) // no ADB: stays off
- gate.update(false)
- gate.update(true)
- gate.update(true)
- gate.update(null) // unreadable while parked: off again
- gate.update(false)
-
- assertEquals(listOf(true, false), changes)
- assertFalse(VideoInCar.allowed)
- }
-
- @Test
- fun closingTheGateTurnsVideoOff() {
- val gate = VideoInCarGate({ true }) {}
- gate.update(true)
- gate.close()
- gate.update(true)
-
- assertFalse(VideoInCar.allowed)
- }
-}