diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 2fc01d8a3..b1416dbc6 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -3134,7 +3134,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { ) /** Pages for the bottom-screen dashboard; the dashboard is offered only while at least one exists. */ - private fun bottomPages(): List = sessionBottomPages(BottomPageActions(takeScreenshot = ::captureScreenshot)) + private fun bottomPages(): List = sessionBottomPages(BottomPageActions(takeScreenshot = ::captureScreenshot, fps = { if (::hud.isInitialized) hud.liveFps else null })) /** Copies the game frame (no overlay) at the size it is shown and saves it to Pictures/DroidDeck. */ private fun captureScreenshot(onDone: (Boolean) -> Unit) { diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt index 07ed74843..b6b775f4b 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt @@ -43,6 +43,9 @@ class DroidDeckHudHost(context: Context) { var onPresentingWindowChanged: (() -> Unit)? = null + /** The frame rate the HUD shows; null while the HUD is off and not counting frames. */ + val liveFps: Float? get() = if (polling) feed.stats.fps else null + /** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */ var onConfigChanged: (() -> Unit)? = null diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameTelemetry.kt b/app/src/main/java/com/droiddeck/launcher/session/GameTelemetry.kt new file mode 100644 index 000000000..68d014ad3 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/GameTelemetry.kt @@ -0,0 +1,190 @@ +package com.droiddeck.launcher.session + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** One reading from a racing game's telemetry. Fractions are 0..1; null means the game does not send it. */ +data class Telemetry( + val source: String, + val speedKmh: Float? = null, + val rpm: Float? = null, + val maxRpm: Float? = null, + val gear: String? = null, + val throttle: Float? = null, + val brake: Float? = null, + val lap: Int? = null, + val laps: Int? = null, + val position: Int? = null, + val fuel: Float? = null, + val currentLapS: Float? = null, + val lastLapS: Float? = null, +) + +/** + * Racing telemetry games send over UDP to 127.0.0.1. Each format has its own port, the one the game or + * its common tools use by default: + * - [CODEMASTERS_PORT]: DiRT Rally 1/2, DiRT 4, GRID ("extradata 3" float array). + * - [FORZA_PORT]: Forza Motorsport 7/2023 and Forza Horizon 4/5 "Data Out" (Sled and Dash). + * - [OUTGAUGE_PORT]: BeamNG.drive and Live for Speed OutGauge. + */ +object GameTelemetry { + const val CODEMASTERS_PORT = 20777 + const val FORZA_PORT = 5300 + const val OUTGAUGE_PORT = 4444 + val PORTS = listOf(CODEMASTERS_PORT, FORZA_PORT, OUTGAUGE_PORT) + + fun parse(port: Int, data: ByteArray, length: Int): Telemetry? = runCatching { + val buf = ByteBuffer.wrap(data, 0, length).order(ByteOrder.LITTLE_ENDIAN) + when (port) { + CODEMASTERS_PORT -> codemasters(buf, length) + FORZA_PORT -> forza(buf, length) + OUTGAUGE_PORT -> outGauge(buf, length) + else -> null + } + }.getOrNull() + + private const val MPS_TO_KMH = 3.6f + + // Float indexes of the Codemasters "extradata 3" packet; engine rpm values are sent divided by 10. + private const val CM_LAP_TIME = 1 + private const val CM_SPEED = 7 + private const val CM_THROTTLE = 29 + private const val CM_BRAKE = 31 + private const val CM_GEAR = 33 + private const val CM_LAP = 36 + private const val CM_RPM = 37 + private const val CM_POSITION = 39 + private const val CM_FUEL = 45 + private const val CM_FUEL_CAPACITY = 46 + private const val CM_LAPS = 60 + private const val CM_LAST_LAP = 62 + private const val CM_MAX_RPM = 63 + private const val CM_FLOATS = 64 + + internal fun codemasters(buf: ByteBuffer, length: Int): Telemetry? { + if (length < CM_FLOATS * 4) return null + fun f(i: Int) = buf.getFloat(i * 4) + val gear = f(CM_GEAR).toInt() + val capacity = f(CM_FUEL_CAPACITY) + return Telemetry( + source = "Codemasters", + speedKmh = f(CM_SPEED) * MPS_TO_KMH, + rpm = f(CM_RPM) * 10f, + maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f }, + // Neutral is 0; DiRT Rally 2.0 reports reverse as 10, older games as -1. + gear = when { + gear == 0 -> "N" + gear < 0 || gear == 10 -> "R" + else -> gear.toString() + }, + throttle = f(CM_THROTTLE).coerceIn(0f, 1f), + brake = f(CM_BRAKE).coerceIn(0f, 1f), + lap = f(CM_LAP).toInt() + 1, + laps = f(CM_LAPS).toInt().takeIf { it > 0 }, + position = f(CM_POSITION).toInt().takeIf { it > 0 }, + fuel = if (capacity > 0f) (f(CM_FUEL) / capacity).coerceIn(0f, 1f) else null, + currentLapS = f(CM_LAP_TIME).takeIf { it > 0f }, + lastLapS = f(CM_LAST_LAP).takeIf { it > 0f }, + ) + } + + // Forza "Data Out": Sled is 232 bytes; the Dash block follows it (FM7 311, FM 2023 331). Horizon 4/5 send + // 324 bytes with 12 extra bytes before the Dash block. + private const val FORZA_SLED = 232 + private const val FORZA_FM7 = 311 + private const val FORZA_HORIZON = 324 + private const val FORZA_FM2023 = 331 + private const val HORIZON_SHIFT = 12 + + internal fun forza(buf: ByteBuffer, length: Int): Telemetry? { + if (length < FORZA_SLED) return null + val racing = buf.getInt(0) != 0 + val maxRpm = buf.getFloat(8) + val rpm = buf.getFloat(16) + val dash = when (length) { + FORZA_FM7, FORZA_FM2023 -> FORZA_SLED + FORZA_HORIZON -> FORZA_SLED + HORIZON_SHIFT + else -> -1 + } + if (dash < 0) return Telemetry(source = "Forza", rpm = rpm, maxRpm = maxRpm.takeIf { it > 0f }) + if (!racing) return Telemetry(source = "Forza") + val gear = buf.get(dash + 75).toInt() and 0xFF + return Telemetry( + source = "Forza", + speedKmh = buf.getFloat(dash + 12) * MPS_TO_KMH, + rpm = rpm, + maxRpm = maxRpm.takeIf { it > 0f }, + gear = if (gear == 0) "R" else gear.toString(), + throttle = (buf.get(dash + 71).toInt() and 0xFF) / 255f, + brake = (buf.get(dash + 72).toInt() and 0xFF) / 255f, + lap = (buf.getShort(dash + 68).toInt() and 0xFFFF) + 1, + position = (buf.get(dash + 70).toInt() and 0xFF).takeIf { it > 0 }, + fuel = buf.getFloat(dash + 44).coerceIn(0f, 1f), + currentLapS = buf.getFloat(dash + 60).takeIf { it > 0f }, + lastLapS = buf.getFloat(dash + 56).takeIf { it > 0f }, + ) + } + + // OutGauge: 92 bytes, or 96 with the optional id at the end. + private const val OUTGAUGE_SIZE = 92 + + internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? { + if (length < OUTGAUGE_SIZE) return null + val gear = buf.get(10).toInt() and 0xFF + return Telemetry( + source = "OutGauge", + speedKmh = buf.getFloat(12) * MPS_TO_KMH, + rpm = buf.getFloat(16), + gear = when (gear) { + 0 -> "R" + 1 -> "N" + else -> (gear - 1).toString() + }, + throttle = buf.getFloat(48).coerceIn(0f, 1f), + brake = buf.getFloat(52).coerceIn(0f, 1f), + fuel = buf.getFloat(28).coerceIn(0f, 1f), + ) + } +} + +/** Games that publish their state locally without any setup: War Thunder's web page and Elite Dangerous' Status.json. */ +object GameStatusFiles { + const val WAR_THUNDER_STATE = "http://127.0.0.1:8111/state" + private const val ELITE_APP = "359320" + private const val ELITE_STATUS = "pfx/drive_c/users/steamuser/Saved Games/Frontier Developments/Elite Dangerous/Status.json" + private const val WAR_THUNDER_ROWS = 12 + + /** War Thunder's own labels (for example "TAS, km/h") with their values, while a match runs. */ + internal fun warThunder(json: String): List> { + val state = org.json.JSONObject(json) + if (!state.optBoolean("valid", false)) return emptyList() + return state.keys().asSequence().filter { it != "valid" }.mapNotNull { key -> + val value = state.opt(key) as? Number ?: return@mapNotNull null + key to if (value.toDouble() % 1.0 == 0.0) value.toLong().toString() else "%.1f".format(java.util.Locale.US, value.toDouble()) + }.take(WAR_THUNDER_ROWS).toList() + } + + fun eliteStatusFile(runtimeRoot: java.io.File, mounts: Map): java.io.File? { + val libraries = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { it.parentFile } + + SteamDownloadMonitor.STEAM_HOMES.map { java.io.File(runtimeRoot, "$it/steamapps") } + return libraries.distinct().map { java.io.File(it, "compatdata/$ELITE_APP/$ELITE_STATUS") }.firstOrNull { it.isFile } + } + + data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List?, val legal: String?, val balance: Long?) + + /** Null while Elite is at its menus (Status.json then carries only the timestamp and flags). */ + internal fun elite(json: String): Elite? { + val s = org.json.JSONObject(json) + val fuel = s.optJSONObject("Fuel") + val pips = s.optJSONArray("Pips")?.let { a -> (0 until a.length()).map { a.optInt(it) } } + if (fuel == null && pips == null && !s.has("Cargo") && !s.has("Balance")) return null + return Elite( + fuelMain = fuel?.optDouble("FuelMain")?.takeIf { !it.isNaN() }, + fuelReserve = fuel?.optDouble("FuelReservoir")?.takeIf { !it.isNaN() }, + cargo = s.optDouble("Cargo").takeIf { !it.isNaN() }, + pips = pips, + legal = s.optString("LegalState").takeIf { it.isNotEmpty() }, + balance = if (s.has("Balance")) s.optLong("Balance") else null, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt index 510c8172c..183427858 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Download import androidx.compose.material.icons.outlined.Forum +import androidx.compose.material.icons.outlined.Speed import androidx.compose.material.icons.outlined.Notifications import androidx.compose.material.icons.outlined.PhotoLibrary import com.droiddeck.launcher.R @@ -10,10 +11,12 @@ import com.droiddeck.launcher.R /** What the bottom-screen pages can ask the running session to do. */ class BottomPageActions( val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null, + val fps: () -> Float? = { null }, ) /** The pages the bottom-screen dashboard offers during a session, in tab order. */ fun sessionBottomPages(actions: BottomPageActions): List = listOf( + BottomPage("telemetry", R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps) }, BottomPage("downloads", R.string.bottom_page_downloads, Icons.Outlined.Download) { BottomDownloadsPage() }, BottomPage("notifications", R.string.bottom_page_notifications, Icons.Outlined.Notifications) { BottomNotificationsPage() }, BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Outlined.PhotoLibrary) { BottomScreenshotsPage(actions.takeScreenshot) }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt new file mode 100644 index 000000000..f31cdfd7a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt @@ -0,0 +1,281 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.hud.HudMetrics +import com.droiddeck.launcher.hud.MangoReadings +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.GameStatusFiles +import com.droiddeck.launcher.session.GameTelemetry +import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.session.Telemetry +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.HttpURLConnection +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.SocketTimeoutException +import java.net.URL +import java.util.concurrent.atomic.AtomicReference + +private const val DRAW_MS = 66L +private const val STALE_MS = 3_000L +private const val METRICS_MS = 1_000L +private const val THUNDER_MS = 500L +private const val THUNDER_RETRY_MS = 3_000L +private const val ELITE_MS = 1_000L +private const val ELITE_SEARCH_MS = 10_000L + +@Composable +fun BottomTelemetryPage(fps: () -> Float?) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val latest = remember { AtomicReference?>(null) } + var race by remember { mutableStateOf(null) } + var fpsNow by remember { mutableStateOf(null) } + var device by remember { mutableStateOf(null) } + var thunder by remember { mutableStateOf>>(emptyList()) } + var elite by remember { mutableStateOf(null) } + var busyPorts by remember { mutableStateOf>(emptySet()) } + + LaunchedEffect(Unit) { + for (port in GameTelemetry.PORTS) launch(Dispatchers.IO) { + val socket = runCatching { + DatagramSocket(null).apply { + reuseAddress = true + soTimeout = 500 + bind(InetSocketAddress(InetAddress.getLoopbackAddress(), port)) + } + }.getOrNull() + if (socket == null) { + withContext(Dispatchers.Main) { busyPorts = busyPorts + port } + return@launch + } + socket.use { + val data = ByteArray(2048) + val packet = DatagramPacket(data, data.size) + while (isActive) { + try { + packet.length = data.size + it.receive(packet) + GameTelemetry.parse(port, data, packet.length)?.let { t -> latest.set(System.currentTimeMillis() to t) } + } catch (_: SocketTimeoutException) { + } + } + } + } + while (isActive) { + val reading = latest.get() + race = reading?.takeIf { System.currentTimeMillis() - it.first < STALE_MS }?.second + fpsNow = fps() + delay(DRAW_MS) + } + } + LaunchedEffect(Unit) { + val metrics = HudMetrics(context).apply { setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context))) } + while (isActive) { + device = withContext(Dispatchers.IO) { runCatching { metrics.snapshot() }.getOrNull() } + delay(METRICS_MS) + } + } + LaunchedEffect(Unit) { + while (isActive) { + val rows = withContext(Dispatchers.IO) { runCatching { GameStatusFiles.warThunder(httpGet(GameStatusFiles.WAR_THUNDER_STATE)) }.getOrNull() } + thunder = rows.orEmpty() + delay(if (rows == null) THUNDER_RETRY_MS else THUNDER_MS) + } + } + LaunchedEffect(Unit) { + var file: File? = null + var searchedAt = 0L + while (isActive) { + val now = System.currentTimeMillis() + if (file == null && now - searchedAt > ELITE_SEARCH_MS) { + searchedAt = now + file = withContext(Dispatchers.IO) { + runCatching { GameStatusFiles.eliteStatusFile(LinuxRuntime.rootDir(context), SessionState.steamLibraryMounts) }.getOrNull() + } + } + val f = file + // Status.json changes while Elite runs; one older than a minute belongs to an earlier session. + elite = if (f != null && now - f.lastModified() < 60_000L) { + withContext(Dispatchers.IO) { runCatching { GameStatusFiles.elite(f.readText()) }.getOrNull() } + } else null + delay(ELITE_MS) + } + } + + Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + DeviceRow(fpsNow, device) + race?.let { RaceDash(it) } + if (thunder.isNotEmpty()) Card(stringResource(R.string.bottom_telemetry_war_thunder)) { ValueGrid(thunder) } + elite?.let { e -> + Card(stringResource(R.string.bottom_telemetry_elite)) { + ValueGrid(listOfNotNull( + e.fuelMain?.let { stringResource(R.string.bottom_telemetry_fuel) to "%.1f t".format(it) }, + e.cargo?.let { stringResource(R.string.bottom_telemetry_cargo) to "%.0f t".format(it) }, + e.pips?.takeIf { it.size == 3 }?.let { p -> + stringResource(R.string.bottom_telemetry_pips) to p.joinToString(" · ") { "%.1f".format(it / 2f) } + }, + e.legal?.let { stringResource(R.string.bottom_telemetry_legal) to it }, + e.balance?.let { stringResource(R.string.bottom_telemetry_balance) to "%,d CR".format(it) }, + )) + } + } + if (race == null && thunder.isEmpty() && elite == null) { + Text(stringResource(R.string.bottom_telemetry_help, GameTelemetry.CODEMASTERS_PORT, GameTelemetry.FORZA_PORT, GameTelemetry.OUTGAUGE_PORT), + fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp)) + } + if (busyPorts.isNotEmpty()) { + Text(stringResource(R.string.bottom_telemetry_port_busy, busyPorts.sorted().joinToString()), fontSize = 13.sp, + color = colors.error, modifier = Modifier.padding(horizontal = 4.dp)) + } + } +} + +private fun httpGet(url: String): String { + val c = URL(url).openConnection() as HttpURLConnection + c.connectTimeout = 300 + c.readTimeout = 500 + return try { + c.inputStream.bufferedReader().use { it.readText() } + } finally { + c.disconnect() + } +} + +@Composable +private fun DeviceRow(fps: Float?, s: HudMetrics.Snapshot?) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Tile(stringResource(R.string.bottom_telemetry_fps), fps?.takeIf { it > 0f }?.let { "%.0f".format(it) } ?: "–", Modifier.weight(1f)) + Tile(stringResource(R.string.bottom_telemetry_cpu), listOfNotNull(s?.cpuPercent?.let { "$it%" }, s?.cpuTempC?.let { "$it°" }) + .joinToString(" ").ifEmpty { "–" }, Modifier.weight(1f)) + Tile(stringResource(R.string.bottom_telemetry_gpu), listOfNotNull(s?.gpuPercent?.let { "$it%" }, s?.gpuTempC?.let { "$it°" }) + .joinToString(" ").ifEmpty { "–" }, Modifier.weight(1f)) + Tile(stringResource(R.string.bottom_telemetry_battery), listOfNotNull(s?.battery?.percent?.let { "$it%" }, + s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1fW".format(it) }).joinToString(" ").ifEmpty { "–" }, Modifier.weight(1f)) + } +} + +@Composable +private fun Tile(label: String, value: String, modifier: Modifier) { + val colors = MaterialTheme.colorScheme + Column(modifier.clip(RoundedCornerShape(12.dp)).background(LocalPalette.current.surface).padding(horizontal = 10.dp, vertical = 8.dp)) { + Text(label, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1) + Text(value, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +} + +@Composable +private fun Card(title: String, content: @Composable () -> Unit) { + val pal = LocalPalette.current + Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal) + content() + } +} + +@Composable +private fun ValueGrid(rows: List>) { + val colors = MaterialTheme.colorScheme + rows.chunked(2).forEach { pair -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + pair.forEach { (k, v) -> + Row(Modifier.weight(1f)) { + Text(k, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + Text(v, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) + } + } + if (pair.size == 1) Box(Modifier.weight(1f)) + } + } +} + +internal fun lapTime(seconds: Float): String { + val total = kotlin.math.round(seconds * 1000.0).toLong() + return "%d:%02d.%03d".format(total / 60_000, total / 1000 % 60, total % 1000) +} + +@Composable +private fun RaceDash(t: Telemetry) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Card(t.source) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Text(t.gear ?: "–", fontSize = 56.sp, fontWeight = FontWeight.Bold, color = pal.signal) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text(t.speedKmh?.let { "%.0f km/h".format(it) } ?: "–", fontSize = 30.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) + val rpm = t.rpm + if (rpm != null) { + val max = t.maxRpm + Text(if (max != null) "%.0f / %.0f rpm".format(rpm, max) else "%.0f rpm".format(rpm), fontSize = 14.sp, color = colors.onSurfaceVariant) + if (max != null) Bar((rpm / max).coerceIn(0f, 1f), if (rpm / max > 0.92f) colors.error else pal.signal) + } + } + Row(Modifier.height(72.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + t.throttle?.let { Pedal(it, pal.good) } + t.brake?.let { Pedal(it, colors.error) } + } + } + ValueGrid(listOfNotNull( + t.lap?.let { lap -> stringResource(R.string.bottom_telemetry_lap) to (t.laps?.let { "$lap / $it" } ?: "$lap") }, + t.position?.let { stringResource(R.string.bottom_telemetry_position) to "P$it" }, + t.currentLapS?.let { stringResource(R.string.bottom_telemetry_this_lap) to lapTime(it) }, + t.lastLapS?.let { stringResource(R.string.bottom_telemetry_last_lap) to lapTime(it) }, + t.fuel?.let { stringResource(R.string.bottom_telemetry_fuel) to "%.0f%%".format(it * 100) }, + )) + } +} + +@Composable +private fun Bar(fraction: Float, color: Color) { + Box(Modifier.fillMaxWidth().height(10.dp).clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line)) { + Box(Modifier.fillMaxWidth(fraction).fillMaxHeight().background(color)) + } +} + +@Composable +private fun Pedal(fraction: Float, color: Color) { + Box(Modifier.width(14.dp).fillMaxHeight().clip(RoundedCornerShape(4.dp)).background(LocalPalette.current.line), + contentAlignment = Alignment.BottomCenter) { + Box(Modifier.fillMaxWidth().fillMaxHeight(fraction.coerceIn(0f, 1f)).background(color)) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 517b127d4..d7e976138 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1903,6 +1903,24 @@ Mic on Mic off Volume %1$d%% + Telemetry + FPS + CPU + GPU + Battery + Lap + Position + This lap + Last lap + Fuel + Cargo + Pips SYS · ENG · WEP + Legal state + Balance + War Thunder + Elite Dangerous + Racing games show a live dash here when they send telemetry to 127.0.0.1: DiRT Rally, DiRT 4 and GRID on port %1$d (UDP on, extradata 3), Forza "Data Out" on port %2$d, BeamNG.drive and Live for Speed OutGauge on port %3$d. War Thunder and Elite Dangerous show up on their own. FPS needs the HUD on. + Another program already uses port %1$s, so that game cannot show here. Removing Linux runtime diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameTelemetryTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameTelemetryTest.kt new file mode 100644 index 000000000..85839c649 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/GameTelemetryTest.kt @@ -0,0 +1,120 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class GameTelemetryTest { + private fun packet(size: Int, fill: ByteBuffer.() -> Unit): ByteArray = + ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN).apply(fill).array() + + @Test fun codemastersFloatsBecomeADash() { + val data = packet(264) { + putFloat(7 * 4, 25f) // m/s + putFloat(29 * 4, 0.8f) + putFloat(31 * 4, 0.1f) + putFloat(33 * 4, 3f) + putFloat(36 * 4, 1f) + putFloat(37 * 4, 650f) // rpm / 10 + putFloat(63 * 4, 800f) + putFloat(45 * 4, 30f) + putFloat(46 * 4, 60f) + } + val t = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, data, data.size)!! + assertEquals(90f, t.speedKmh!!, 0.01f) + assertEquals("3", t.gear) + assertEquals(6500f, t.rpm!!, 0.01f) + assertEquals(8000f, t.maxRpm!!, 0.01f) + assertEquals(2, t.lap) + assertEquals(0.5f, t.fuel!!, 0.001f) + } + + @Test fun codemastersReverseAndNeutral() { + fun gear(g: Float) = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, packet(264) { putFloat(33 * 4, g) }, 264)!!.gear + assertEquals("N", gear(0f)) + assertEquals("R", gear(-1f)) + assertEquals("R", gear(10f)) + } + + @Test fun forzaHorizonDashSitsTwelveBytesLater() { + val dash = 232 + 12 + val data = packet(324) { + putInt(0, 1) + putFloat(8, 8000f) + putFloat(16, 5000f) + putFloat(dash + 12, 50f) + put(dash + 71, 255.toByte()) + put(dash + 75, 4) + putShort(dash + 68, 2) + put(dash + 70, 5) + } + val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!! + assertEquals(180f, t.speedKmh!!, 0.01f) + assertEquals("4", t.gear) + assertEquals(1f, t.throttle!!, 0.001f) + assertEquals(3, t.lap) + assertEquals(5, t.position) + } + + @Test fun forzaMotorsportDashFollowsTheSled() { + val data = packet(311) { + putInt(0, 1) + putFloat(232 + 12, 10f) + put(232 + 75, 0) + } + val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!! + assertEquals(36f, t.speedKmh!!, 0.01f) + assertEquals("R", t.gear) + } + + @Test fun forzaInMenusHasNoDash() { + val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, packet(324) {}, 324)!! + assertNull(t.speedKmh) + } + + @Test fun outGaugeGearsAreShiftedByOne() { + val data = packet(96) { + put(10, 3) + putFloat(12, 20f) + putFloat(16, 4000f) + } + val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, data, data.size)!! + assertEquals("2", t.gear) + assertEquals(72f, t.speedKmh!!, 0.01f) + assertEquals(4000f, t.rpm!!, 0.01f) + } + + @Test fun shortPacketsAreIgnored() { + assertNull(GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, ByteArray(100), 100)) + assertNull(GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, ByteArray(40), 40)) + assertNull(GameTelemetry.parse(1234, ByteArray(400), 400)) + } +} + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class GameStatusFilesTest { + @Test fun warThunderShowsNumbersOnlyDuringAMatch() { + assertEquals(emptyList>(), GameStatusFiles.warThunder("""{"valid": false}""")) + val rows = GameStatusFiles.warThunder("""{"valid": true, "H, m": 1520, "TAS, km/h": 512.4, "name": "x"}""") + assertEquals(listOf("H, m" to "1520", "TAS, km/h" to "512.4"), rows) + } + + @Test fun eliteAtTheMenusShowsNothing() { + assertNull(GameStatusFiles.elite("""{"timestamp": "2026-10-31T02:00:00Z", "event": "Status", "Flags": 0}""")) + } + + @Test fun eliteInFlight() { + val e = GameStatusFiles.elite("""{"Flags": 16777240, "Pips": [4, 8, 0], "Fuel": {"FuelMain": 16.0, "FuelReservoir": 0.43}, + "Cargo": 2.0, "LegalState": "Clean", "Balance": 1234567}""")!! + assertEquals(16.0, e.fuelMain!!, 0.001) + assertEquals(listOf(4, 8, 0), e.pips) + assertEquals("Clean", e.legal) + assertEquals(1234567L, e.balance) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/BottomDashboardTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/BottomDashboardTest.kt index 1fe4d535f..be65cd85a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/BottomDashboardTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/BottomDashboardTest.kt @@ -36,3 +36,10 @@ class BottomDownloadsRateTest { assertEquals(0L, downloadRate(-1L, 0L, 100L, 2_000L)) } } + +class BottomTelemetryLapTimeTest { + @Test fun lapTimesReadAsMinutesSecondsMillis() { + assertEquals("1:23.456", lapTime(83.456f)) + assertEquals("0:05.000", lapTime(5f)) + } +}