From 6ead4af37ee02d8f1d56f5af84af49bb9bd387f7 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:58:14 -0500 Subject: [PATCH] feat: Trinkets tab with a Bluetooth controller mode --- app/src/main/AndroidManifest.xml | 12 + .../launcher/BtControllerActivity.kt | 506 +++++++++++++++ .../droiddeck/launcher/input/bt/BtGamepad.kt | 582 ++++++++++++++++++ .../launcher/input/bt/BtPadReports.kt | 551 +++++++++++++++++ .../droiddeck/launcher/ui/FrontEndContent.kt | 4 + .../com/droiddeck/launcher/ui/FrontEndRail.kt | 4 +- .../com/droiddeck/launcher/ui/TrinketsPage.kt | 61 ++ app/src/main/res/values/strings.xml | 22 + 8 files changed, 1741 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/BtControllerActivity.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/input/bt/BtGamepad.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/input/bt/BtPadReports.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/TrinketsPage.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b53770561..6175b4269 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -41,6 +41,10 @@ + + + + @@ -105,6 +109,14 @@ + + = 31) NEARBY + LOCATION else LOCATION + val missing = wanted.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } + if (missing.isEmpty()) startPad() else requestPermissions(missing.toTypedArray(), REQUEST_NEARBY) + setContent { DroidDeckTheme { Screen() } } + } + + private fun startPad() { + BtGamepad.start(this, profile) + BtGamepad.openPairingWindow() + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == REQUEST_NEARBY) startPad() + } + + override fun onDestroy() { + main.removeCallbacks(exitHold) + if (isFinishing) BtGamepad.stop() + super.onDestroy() + } + + private fun pickProfile(p: BtPadProfile) { + if (p == profile) return + profile = p + prefs(this).edit().putString(KEY_PROFILE, p.id).apply() + BtGamepad.switchProfile(p) + } + + private fun push() { + physical.buttons = keyButtons or hatButtons + merged.merge(physical, touch) + BtGamepad.update(merged) + val combo = BtPadState.SELECT or BtPadState.START + val held = physical.buttons and combo == combo + if (held && !exitArmed) main.postDelayed(exitHold, EXIT_HOLD_MS) + else if (!held && exitArmed) main.removeCallbacks(exitHold) + exitArmed = held + } + + private fun isPad(event: KeyEvent): Boolean { + val s = event.source + return s and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD || + s and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK || + KeyEvent.isGamepadButton(event.keyCode) + } + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + val bit = KEYS[event.keyCode] + if (bit == null || event.keyCode in DPAD_KEYS && !isPad(event) && event.source and InputDevice.SOURCE_DPAD != InputDevice.SOURCE_DPAD) { + return super.dispatchKeyEvent(event) + } + when (event.action) { + KeyEvent.ACTION_DOWN -> keyButtons = keyButtons or bit + KeyEvent.ACTION_UP -> keyButtons = keyButtons and bit.inv() + } + push() + return true + } + + override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) { + return super.dispatchGenericMotionEvent(event) + } + val device = event.device + fun axis(code: Int): Float { + val range = device?.getMotionRange(code, event.source) ?: return 0f + val v = event.getAxisValue(code) + return if (Math.abs(v) > maxOf(range.flat, 0.04f)) v else 0f + } + val hasZ = device?.getMotionRange(MotionEvent.AXIS_Z, event.source) != null + physical.lx = axis(MotionEvent.AXIS_X); physical.ly = axis(MotionEvent.AXIS_Y) + physical.rx = axis(if (hasZ) MotionEvent.AXIS_Z else MotionEvent.AXIS_RX) + physical.ry = axis(if (hasZ) MotionEvent.AXIS_RZ else MotionEvent.AXIS_RY) + physical.lt = maxOf(axis(MotionEvent.AXIS_LTRIGGER), axis(MotionEvent.AXIS_BRAKE)) + physical.rt = maxOf(axis(MotionEvent.AXIS_RTRIGGER), axis(MotionEvent.AXIS_GAS)) + val hx = event.getAxisValue(MotionEvent.AXIS_HAT_X) + val hy = event.getAxisValue(MotionEvent.AXIS_HAT_Y) + hatButtons = (if (hy < -0.5f) BtPadState.UP else 0) or (if (hy > 0.5f) BtPadState.DOWN else 0) or + (if (hx < -0.5f) BtPadState.LEFT else 0) or (if (hx > 0.5f) BtPadState.RIGHT else 0) + push() + return true + } + + private fun touchButton(bit: Int, down: Boolean) { + touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv() + if (bit == BtPadState.LT) touch.lt = if (down) 1f else 0f + if (bit == BtPadState.RT) touch.rt = if (down) 1f else 0f + push() + } + + private fun touchStick(left: Boolean, x: Float, y: Float) { + if (left) { touch.lx = x; touch.ly = y } else { touch.rx = x; touch.ry = y } + push() + } + + @Composable + private fun Screen() { + val status by BtGamepad.status.collectAsState() + val colors = MaterialTheme.colorScheme + Column(Modifier.fillMaxSize().background(colors.background).padding(horizontal = 16.dp, vertical = 10.dp)) { + Panel(status) + if (showTouch) { + Spacer(Modifier.height(8.dp)) + TouchPad(Modifier.weight(1f).fillMaxWidth(), status.lightbar) + } else { + Spacer(Modifier.weight(1f)) + } + Text(stringResource(R.string.btpad_exit_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, + modifier = Modifier.align(Alignment.CenterHorizontally).padding(top = 6.dp)) + } + } + + @Composable + private fun Panel(status: BtGamepad.Status) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val connected = status.phase == BtGamepad.Phase.CONNECTED + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Box(Modifier.size(12.dp).clip(CircleShape).background(status.lightbar?.let { Color(it) } ?: if (connected) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.4f))) + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.btpad_title), fontSize = 20.sp, fontWeight = FontWeight.Black, color = colors.onBackground) + Text(statusText(status), fontSize = 13.sp, color = colors.onSurfaceVariant) + } + if (connected) SecondaryButton(stringResource(R.string.btpad_disconnect), compact = true) { BtGamepad.disconnect() } + else PrimaryButton(stringResource(R.string.btpad_pair), compact = true, enabled = status.phase == BtGamepad.Phase.READY) { BtGamepad.openPairingWindow() } + SecondaryButton(stringResource(R.string.btpad_close), compact = true) { finish() } + } + Row(Modifier.horizontalScroll(rememberScrollState()).padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + BtPadProfile.entries.forEach { p -> Chip(profileLabel(p), p == profile) { pickProfile(p) } } + Spacer(Modifier.width(8.dp)) + Chip(stringResource(R.string.btpad_touch), showTouch) { + showTouch = !showTouch + prefs(this@BtControllerActivity).edit().putBoolean(KEY_TOUCH, showTouch).apply() + } + } + if (!connected) Text(stringResource(R.string.btpad_switch_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 6.dp)) + } + + @Composable + private fun statusText(status: BtGamepad.Status): String = when (status.phase) { + BtGamepad.Phase.OFF, BtGamepad.Phase.STARTING -> stringResource(R.string.btpad_status_starting) + BtGamepad.Phase.BLUETOOTH_OFF -> stringResource(R.string.btpad_status_bt_off) + BtGamepad.Phase.UNSUPPORTED -> stringResource(R.string.btpad_status_unsupported) + BtGamepad.Phase.READY -> stringResource(R.string.btpad_status_ready, status.name ?: "") + BtGamepad.Phase.CONNECTING -> stringResource(R.string.btpad_status_connecting, status.host ?: "") + BtGamepad.Phase.CONNECTED -> stringResource(R.string.btpad_status_connected, status.host ?: "") + } + + @Composable + private fun profileLabel(p: BtPadProfile) = stringResource(when (p) { + BtPadProfile.GENERIC -> R.string.btpad_profile_generic + BtPadProfile.XBOX -> R.string.btpad_profile_xbox + BtPadProfile.DUALSHOCK4 -> R.string.btpad_profile_ds4 + BtPadProfile.DUALSENSE -> R.string.btpad_profile_dualsense + BtPadProfile.STEAM -> R.string.btpad_profile_steam + }) + + @Composable + private fun Chip(label: String, on: Boolean, enabled: Boolean = true, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, + color = if (on) colors.background else if (enabled) colors.onBackground else colors.onSurfaceVariant, + modifier = Modifier.clip(CircleShape).background(if (on) pal.signal else colors.surface) + .border(1.dp, if (on) pal.signal else pal.line2, CircleShape) + .clickable(enabled = enabled, onClick = onClick).padding(horizontal = 14.dp, vertical = 8.dp)) + } + + @Composable + private fun TouchPad(modifier: Modifier, lightbar: Int?) { + val sony = profile == BtPadProfile.DUALSHOCK4 || profile == BtPadProfile.DUALSENSE + val steam = profile == BtPadProfile.STEAM + BoxWithConstraints(modifier) { + val unit = minOf(maxWidth / 10f, maxHeight / 6.6f) + val gap = unit * 0.2f + val stick = unit * 2f + val btn = unit * 0.95f + val shoulderW = unit * 1.4f + val shoulderH = unit * 0.7f + Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.Bottom) { + Column(verticalArrangement = Arrangement.spacedBy(gap)) { + Row(horizontalArrangement = Arrangement.spacedBy(gap)) { + PadButton(if (sony) "L2" else "LT", BtPadState.LT, shoulderW, shoulderH) + PadButton(if (sony) "L1" else "LB", BtPadState.LB, shoulderW, shoulderH) + } + Stick(stick, left = true) + Cross(btn) + } + Column(Modifier.fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(gap * 2, Alignment.CenterVertically), horizontalAlignment = Alignment.CenterHorizontally) { + if (steam) Row(horizontalArrangement = Arrangement.spacedBy(gap)) { + PadButton("L5", BtPadState.L5, unit * 0.8f, unit * 0.6f) + PadButton("L4", BtPadState.L4, unit * 0.8f, unit * 0.6f) + Spacer(Modifier.width(gap * 2)) + PadButton("R4", BtPadState.R4, unit * 0.8f, unit * 0.6f) + PadButton("R5", BtPadState.R5, unit * 0.8f, unit * 0.6f) + } + Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically) { + PadButton(if (sony) "Share" else "View", BtPadState.SELECT, unit * 1.2f, unit * 0.6f) + PadButton(if (sony) "PS" else if (steam) "Steam" else "Home", BtPadState.GUIDE, unit * 1.2f, unit * 0.6f, tint = lightbar?.let { Color(it) }) + PadButton(if (sony) "Options" else "Menu", BtPadState.START, unit * 1.2f, unit * 0.6f) + } + Row(horizontalArrangement = Arrangement.spacedBy(gap)) { + PadButton("L3", BtPadState.L3, unit * 0.9f, unit * 0.6f) + if (sony) PadButton("Pad", BtPadState.TOUCHPAD, unit * 1.2f, unit * 0.6f) + if (steam) PadButton("···", BtPadState.SHARE, unit * 1.2f, unit * 0.6f) + PadButton("R3", BtPadState.R3, unit * 0.9f, unit * 0.6f) + } + if (steam) Row(horizontalArrangement = Arrangement.spacedBy(gap * 2)) { + Trackpad(unit * 1.9f, left = true) + Trackpad(unit * 1.9f, left = false) + } + } + Column(verticalArrangement = Arrangement.spacedBy(gap), horizontalAlignment = Alignment.End) { + Row(horizontalArrangement = Arrangement.spacedBy(gap)) { + PadButton(if (sony) "R1" else "RB", BtPadState.RB, shoulderW, shoulderH) + PadButton(if (sony) "R2" else "RT", BtPadState.RT, shoulderW, shoulderH) + } + Diamond(btn, sony) + Stick(stick, left = false) + } + } + } + } + + @Composable + private fun Trackpad(size: Dp, left: Boolean) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var dot by remember { mutableStateOf(null) } + val px = with(LocalDensity.current) { size.toPx() } + Box( + Modifier.size(size).clip(RoundedCornerShape(18.dp)).background(colors.surface).border(1.dp, pal.line2, RoundedCornerShape(18.dp)) + .pointerInput(left) { + awaitEachGesture { + val first = awaitFirstDown(requireUnconsumed = false) + val started = first.uptimeMillis + fun norm(p: Offset) = Offset((p.x / this.size.width * 2f - 1f).coerceIn(-1f, 1f), (p.y / this.size.height * 2f - 1f).coerceIn(-1f, 1f)) + var moved = 0f + var last = norm(first.position) + dot = last + touchPad(left, last, true) + var upTime = started + while (true) { + val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break + if (!change.pressed) { upTime = change.uptimeMillis; break } + change.consume() + val p = norm(change.position) + moved += (p - last).getDistance() + last = p + dot = p + touchPad(left, p, true) + } + dot = null + if (upTime - started < TAP_MS && moved < 0.15f) clickPad(left, last) + else touchPad(left, last, false) + } + }, + ) { + dot?.let { d -> + val r = px * 0.08f + Box(Modifier.offset { IntOffset(((d.x + 1f) / 2f * px - r).roundToInt(), ((d.y + 1f) / 2f * px - r).roundToInt()) } + .size(size * 0.16f).clip(CircleShape).background(pal.signal)) + } + } + } + + private fun touchPad(left: Boolean, p: Offset, down: Boolean) { + val bit = if (left) BtPadState.LPAD_TOUCH else BtPadState.RPAD_TOUCH + touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv() + if (left) { touch.lpx = p.x; touch.lpy = p.y } else { touch.rpx = p.x; touch.rpy = p.y } + push() + } + + private fun clickPad(left: Boolean, p: Offset) { + val click = if (left) BtPadState.LPAD_CLICK else BtPadState.RPAD_CLICK + touch.buttons = touch.buttons or click + touchPad(left, p, true) + main.postDelayed({ + touch.buttons = touch.buttons and click.inv() + touchPad(left, p, false) + }, CLICK_MS) + } + + @Composable + private fun Cross(size: Dp) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + PadButton("▲", BtPadState.UP, size, size) + Row { + PadButton("◀", BtPadState.LEFT, size, size) + Spacer(Modifier.size(size)) + PadButton("▶", BtPadState.RIGHT, size, size) + } + PadButton("▼", BtPadState.DOWN, size, size) + } + } + + @Composable + private fun Diamond(size: Dp, sony: Boolean) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + PadButton(if (sony) "△" else "Y", BtPadState.Y, size, size, round = true) + Row { + PadButton(if (sony) "□" else "X", BtPadState.X, size, size, round = true) + Spacer(Modifier.size(size)) + PadButton(if (sony) "○" else "B", BtPadState.B, size, size, round = true) + } + PadButton(if (sony) "✕" else "A", BtPadState.A, size, size, round = true) + } + } + + @Composable + private fun PadButton(label: String, bit: Int, width: Dp, height: Dp, round: Boolean = false, tint: Color? = null) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var down by remember { mutableStateOf(false) } + val shape = if (round) CircleShape else RoundedCornerShape(10.dp) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.size(width, height).clip(shape) + .background(if (down) pal.signal else tint?.copy(alpha = 0.35f) ?: colors.surface) + .border(1.dp, pal.line2, shape) + .pointerInput(bit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false) + down = true; touchButton(bit, true) + waitForUpOrCancellation() + down = false; touchButton(bit, false) + } + }, + ) { + Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = if (down) colors.background else colors.onBackground) + } + } + + @Composable + private fun Stick(size: Dp, left: Boolean) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var knob by remember { mutableStateOf(Offset.Zero) } + val px = with(LocalDensity.current) { size.toPx() } + val knobSize = size * 0.42f + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.size(size).clip(CircleShape).background(colors.surface).border(1.dp, pal.line2, CircleShape) + .pointerInput(left) { + awaitEachGesture { + val first = awaitFirstDown(requireUnconsumed = false) + val radius = this.size.width / 2f + val center = Offset(radius, this.size.height / 2f) + fun move(p: Offset) { + var d = (p - center) / (radius * 0.8f) + val len = hypot(d.x, d.y) + if (len > 1f) d /= len + knob = d + touchStick(left, d.x, d.y) + } + move(first.position) + while (true) { + val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break + if (!change.pressed) break + change.consume() + move(change.position) + } + knob = Offset.Zero + touchStick(left, 0f, 0f) + } + }, + ) { + val travel = px * 0.29f + Box(Modifier.offset { IntOffset((knob.x * travel).roundToInt(), (knob.y * travel).roundToInt()) } + .size(knobSize).clip(CircleShape).background(if (knob != Offset.Zero) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.5f))) + } + } + + companion object { + private const val EXIT_HOLD_MS = 1_500L + private const val TAP_MS = 200L + private const val CLICK_MS = 90L + private const val REQUEST_NEARBY = 41 + private val NEARBY = listOf("android.permission.BLUETOOTH_ADVERTISE", "android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH_SCAN") + private val LOCATION = listOf("android.permission.ACCESS_FINE_LOCATION") + private const val KEY_PROFILE = "btpad_profile" + private const val KEY_TOUCH = "btpad_touch" + + private fun prefs(c: Context) = c.getSharedPreferences("trinkets", Context.MODE_PRIVATE) + + private val DPAD_KEYS = setOf(KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT) + + private val KEYS = mapOf( + KeyEvent.KEYCODE_BUTTON_A to BtPadState.A, + KeyEvent.KEYCODE_BUTTON_B to BtPadState.B, + KeyEvent.KEYCODE_BUTTON_X to BtPadState.X, + KeyEvent.KEYCODE_BUTTON_Y to BtPadState.Y, + KeyEvent.KEYCODE_BUTTON_L1 to BtPadState.LB, + KeyEvent.KEYCODE_BUTTON_R1 to BtPadState.RB, + KeyEvent.KEYCODE_BUTTON_L2 to BtPadState.LT, + KeyEvent.KEYCODE_BUTTON_R2 to BtPadState.RT, + KeyEvent.KEYCODE_BUTTON_SELECT to BtPadState.SELECT, + KeyEvent.KEYCODE_BUTTON_START to BtPadState.START, + KeyEvent.KEYCODE_BUTTON_MODE to BtPadState.GUIDE, + KeyEvent.KEYCODE_BUTTON_THUMBL to BtPadState.L3, + KeyEvent.KEYCODE_BUTTON_THUMBR to BtPadState.R3, + KeyEvent.KEYCODE_BUTTON_C to BtPadState.L4, + KeyEvent.KEYCODE_BUTTON_Z to BtPadState.R4, + KeyEvent.KEYCODE_BUTTON_1 to BtPadState.L4, + KeyEvent.KEYCODE_BUTTON_2 to BtPadState.R4, + KeyEvent.KEYCODE_BUTTON_3 to BtPadState.L5, + KeyEvent.KEYCODE_BUTTON_4 to BtPadState.R5, + KeyEvent.KEYCODE_DPAD_UP to BtPadState.UP, + KeyEvent.KEYCODE_DPAD_DOWN to BtPadState.DOWN, + KeyEvent.KEYCODE_DPAD_LEFT to BtPadState.LEFT, + KeyEvent.KEYCODE_DPAD_RIGHT to BtPadState.RIGHT, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/bt/BtGamepad.kt b/app/src/main/java/com/droiddeck/launcher/input/bt/BtGamepad.kt new file mode 100644 index 000000000..71d83162e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/bt/BtGamepad.kt @@ -0,0 +1,582 @@ +package com.droiddeck.launcher.input.bt + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCallback +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothGattServer +import android.bluetooth.BluetoothGattServerCallback +import android.bluetooth.BluetoothGattService +import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile +import android.bluetooth.le.AdvertiseData +import android.bluetooth.le.AdvertisingSet +import android.bluetooth.le.AdvertisingSetCallback +import android.bluetooth.le.AdvertisingSetParameters +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.Build +import android.os.Handler +import android.os.HandlerThread +import android.os.ParcelUuid +import android.os.VibrationEffect +import android.os.Vibrator +import android.util.Log +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import java.util.ArrayDeque +import java.util.UUID + +@SuppressLint("MissingPermission") +object BtGamepad { + enum class Phase { OFF, STARTING, BLUETOOTH_OFF, UNSUPPORTED, READY, CONNECTING, CONNECTED } + + data class Status(val phase: Phase, val host: String? = null, val lightbar: Int? = null, val name: String? = null) + + private const val TAG = "BtGamepad" + + private val _status = MutableStateFlow(Status(Phase.OFF)) + val status: StateFlow = _status + + private var handler: Handler? = null + private var app: Context? = null + private var server: BluetoothGattServer? = null + private var advertising = false + private var profile = BtPadProfile.GENERIC + private var encoder: BtPadEncoder = profile.encoder() + private val pendingServices = ArrayDeque() + private val reportRefs = HashMap>() + private val inputChars = HashMap() + private val longReads = HashMap() + private val preparedWrites = HashMap() + private var host: BluetoothDevice? = null + private var priorityLink: BluetoothGatt? = null + private var notifyPending = false + private var dirty = false + private var mtu = 23 + private val latest = BtPadState() + private val sent = BtPadState() + private var sentOnce = false + private var vibrator: Vibrator? = null + @Volatile private var running = false + private var pairingUntil = 0L + private var fastLinkPending = false + private const val PAIRING_WINDOW_MS = 120_000L + private const val MAX_MTU = 517 + private const val FAST_LINK_DELAY_MS = 1_500L + + fun start(context: Context, p: BtPadProfile) { + val h = handler ?: init(context) + h.post { + running = true + if (server != null && p == profile) { + publish(Phase.READY) + startAdvertising() + } else { + close() + profile = p + publish(Phase.STARTING) + open() + } + } + } + + private fun init(context: Context): Handler { + val ctx = context.applicationContext + app = ctx + vibrator = ctx.getSystemService(Vibrator::class.java) + val t = HandlerThread("bt-gamepad").apply { start() } + val h = Handler(t.looper) + handler = h + val receiver = object : BroadcastReceiver() { + override fun onReceive(c: Context, intent: Intent) { + when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)) { + BluetoothAdapter.STATE_ON -> h.post { if (running) open() } + BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> h.post { + close() + publish(Phase.BLUETOOTH_OFF) + } + } + } + } + ctx.registerReceiver(receiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED), null, h) + return h + } + + fun stop() { + val h = handler ?: return + h.post { + running = false + rumble(0, 0) + pairingUntil = 0 + keepScanning() + stopAdvertising() + h.removeCallbacks(periodic) + dropFastLink() + host?.let { d -> runCatching { server?.cancelConnection(d) } } + host = null + _status.value = Status(Phase.OFF) + } + } + + fun switchProfile(p: BtPadProfile) { + val h = handler ?: return + h.post { + if (p == profile && server != null) return@post + profile = p + close() + publish(Phase.STARTING) + h.postDelayed(::open, 300) + } + } + + fun update(s: BtPadState) { + val h = handler ?: return + synchronized(latest) { latest.set(s) } + h.post(::sendIfChanged) + } + + fun openPairingWindow() { + val h = handler ?: return + h.post { + pairingUntil = System.currentTimeMillis() + PAIRING_WINDOW_MS + keepScanning() + if (host == null) { + stopAdvertising() + startAdvertising() + } + } + } + + private fun keepScanning() { + val adapter = adapter() ?: return + val h = handler ?: return + h.removeCallbacks(scanTick) + if (host != null || System.currentTimeMillis() > pairingUntil) { + runCatching { if (adapter.isDiscovering) adapter.cancelDiscovery() } + return + } + runCatching { if (!adapter.isDiscovering) adapter.startDiscovery() } + h.postDelayed(scanTick, 2_000) + } + + private val scanTick = Runnable { keepScanning() } + + fun disconnect() { + handler?.post { host?.let { d -> server?.cancelConnection(d) } } + } + + private fun manager() = app?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager + + private fun adapter(): BluetoothAdapter? = manager()?.adapter + + private fun open() { + val ctx = app ?: return + if (server != null || !running) return + val manager = manager() + val adapter = manager?.adapter + if (adapter == null || !ctx.packageManager.hasSystemFeature("android.hardware.bluetooth_le")) { + publish(Phase.UNSUPPORTED) + return + } + if (!adapter.isEnabled) { + publish(Phase.BLUETOOTH_OFF) + return + } + if (adapter.bluetoothLeAdvertiser == null) { + publish(Phase.UNSUPPORTED) + return + } + encoder = profile.encoder() + sentOnce = false + val s = runCatching { manager.openGattServer(ctx, serverCallback) } + .onFailure { Log.w(TAG, "no GATT server", it) }.getOrNull() + if (s == null) { + publish(Phase.UNSUPPORTED) + return + } + server = s + pendingServices.clear() + pendingServices.add(deviceInfoService()) + pendingServices.add(hidService()) + addNextService() + } + + private fun close() { + stopAdvertising() + pairingUntil = 0 + keepScanning() + dropFastLink() + server?.let { s -> + runCatching { manager()?.getConnectedDevices(BluetoothProfile.GATT_SERVER)?.forEach { s.cancelConnection(it) } } + runCatching { s.clearServices(); s.close() } + } + server = null + host = null + notifyPending = false + dirty = false + reportRefs.clear() + inputChars.clear() + longReads.clear() + preparedWrites.clear() + } + + private fun addNextService() { + val s = server ?: return + val next = pendingServices.pollFirst() + if (next == null) { + Log.i(TAG, "${profile.id}: services ready") + startAdvertising() + return + } + if (!s.addService(next)) { + Log.w(TAG, "addService ${next.uuid} refused") + publish(Phase.UNSUPPORTED) + } + } + + private fun deviceInfoService(): BluetoothGattService { + val service = BluetoothGattService(uuid16(0x180A), BluetoothGattService.SERVICE_TYPE_PRIMARY) + val pnp = BtPadEncoder.bytes(0x02, profile.vendorId and 0xFF, profile.vendorId shr 8, + profile.productId and 0xFF, profile.productId shr 8, profile.version and 0xFF, profile.version shr 8) + service.addCharacteristic(readOnly(0x2A50, pnp)) + service.addCharacteristic(readOnly(0x2A29, "DroidDeck".toByteArray())) + return service + } + + private fun hidService(): BluetoothGattService { + val service = BluetoothGattService(uuid16(0x1812), BluetoothGattService.SERVICE_TYPE_PRIMARY) + service.addCharacteristic(readOnly(0x2A4A, BtPadEncoder.bytes(0x11, 0x01, 0x00, 0x02))) + service.addCharacteristic(readOnly(0x2A4B, encoder.descriptor)) + service.addCharacteristic(BluetoothGattCharacteristic(uuid16(0x2A4C), + BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, BluetoothGattCharacteristic.PERMISSION_WRITE)) + for ((id, type) in encoder.reports) { + val props = when (type) { + BtPadEncoder.INPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_NOTIFY + BtPadEncoder.OUTPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE or + BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE + else -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE + } + val chr = BluetoothGattCharacteristic(uuid16(0x2A4D), props, + BluetoothGattCharacteristic.PERMISSION_READ or BluetoothGattCharacteristic.PERMISSION_WRITE) + if (type == BtPadEncoder.INPUT) { + chr.addDescriptor(cccd()) + inputChars[id] = chr + } + val ref = BluetoothGattDescriptor(uuid16(0x2908), BluetoothGattDescriptor.PERMISSION_READ) + @Suppress("DEPRECATION") + ref.value = BtPadEncoder.bytes(id, type) + chr.addDescriptor(ref) + reportRefs[chr] = id to type + service.addCharacteristic(chr) + } + return service + } + + private fun readOnly(uuid: Int, value: ByteArray): BluetoothGattCharacteristic { + val chr = BluetoothGattCharacteristic(uuid16(uuid), BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ) + @Suppress("DEPRECATION") + chr.value = value + return chr + } + + private fun cccd() = BluetoothGattDescriptor(uuid16(0x2902), + BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE) + + private fun uuid16(v: Int): UUID = UUID.fromString("%08x-0000-1000-8000-00805f9b34fb".format(v)) + + private fun startAdvertising() { + val advertiser = adapter()?.bluetoothLeAdvertiser ?: return + if (advertising || server == null || host != null || !running) return + val params = AdvertisingSetParameters.Builder() + .setLegacyMode(true) + .setConnectable(true) + .setScannable(true) + .setInterval(AdvertisingSetParameters.INTERVAL_LOW) + .setTxPowerLevel(AdvertisingSetParameters.TX_POWER_HIGH) + .build() + val data = AdvertiseData.Builder() + .addServiceUuid(ParcelUuid(uuid16(0x1812))) + .setIncludeDeviceName(true) + .build() + advertising = runCatching { advertiser.startAdvertisingSet(params, data, null, null, null, advertiseCallback); true } + .onFailure { Log.w(TAG, "advertising refused", it) }.getOrDefault(false) + if (!advertising) publish(Phase.UNSUPPORTED) + } + + private fun stopAdvertising() { + if (!advertising) return + advertising = false + runCatching { adapter()?.bluetoothLeAdvertiser?.stopAdvertisingSet(advertiseCallback) } + } + + private val advertiseCallback = object : AdvertisingSetCallback() { + override fun onAdvertisingSetStarted(set: AdvertisingSet?, txPower: Int, status: Int) { + Log.i(TAG, "advertising status $status") + handler?.post { + if (status == ADVERTISE_SUCCESS) { + if (host == null) publish(Phase.READY) + } else { + advertising = false + publish(Phase.UNSUPPORTED) + } + } + } + } + + private val serverCallback = object : BluetoothGattServerCallback() { + override fun onServiceAdded(status: Int, service: BluetoothGattService) { + handler?.post { + if (status != BluetoothGatt.GATT_SUCCESS) { + Log.w(TAG, "service ${service.uuid} failed: $status") + publish(Phase.UNSUPPORTED) + } else addNextService() + } + } + + override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) { + handler?.post { + Log.i(TAG, "${device.address}: state $newState status $status bond ${device.bondState}") + if (newState == BluetoothProfile.STATE_CONNECTED) { + stopAdvertising() + if (!running) { + server?.cancelConnection(device) + return@post + } + mtu = 23 + if (device.bondState == BluetoothDevice.BOND_BONDED) attach(device) + else if (host == null) publish(Phase.CONNECTING, device) + } else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == device) { + host = null + rumble(0, 0) + dropFastLink() + publish(Phase.READY) + startAdvertising() + } else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == null) { + publish(Phase.READY) + startAdvertising() + } + } + } + + override fun onMtuChanged(device: BluetoothDevice, newMtu: Int) { + handler?.post { + mtu = newMtu + Log.i(TAG, "mtu $newMtu") + } + } + + override fun onCharacteristicReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, chr: BluetoothGattCharacteristic) { + handler?.post { + val value = if (offset > 0) longReads[chr] ?: valueOf(chr) else valueOf(chr).also { longReads[chr] = it } + val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size) + server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply) + if (chr.uuid == uuid16(0x2A4B)) attach(device) + } + } + + override fun onDescriptorReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, descriptor: BluetoothGattDescriptor) { + handler?.post { + @Suppress("DEPRECATION") + val value = descriptor.value ?: if (descriptor.uuid == uuid16(0x2902)) BtPadEncoder.bytes(1, 0) else ByteArray(0) + val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size) + server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply) + } + } + + override fun onDescriptorWriteRequest(device: BluetoothDevice, requestId: Int, descriptor: BluetoothGattDescriptor, + preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) { + handler?.post { + if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value) + if (descriptor.uuid == uuid16(0x2902) && descriptor.characteristic in reportRefs && value.isNotEmpty() && + value[0].toInt() and 1 != 0) { + attach(device) + handler?.postDelayed({ startFastLink(device) }, FAST_LINK_DELAY_MS) + } + } + } + + override fun onCharacteristicWriteRequest(device: BluetoothDevice, requestId: Int, chr: BluetoothGattCharacteristic, + preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) { + handler?.post { + if (preparedWrite) { + val old = preparedWrites[chr] ?: ByteArray(0) + val merged = old.copyOf(maxOf(old.size, offset + value.size)) + value.copyInto(merged, offset) + preparedWrites[chr] = merged + } else written(chr, value) + if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value) + } + } + + override fun onExecuteWrite(device: BluetoothDevice, requestId: Int, execute: Boolean) { + handler?.post { + if (execute) preparedWrites.forEach { (chr, v) -> written(chr, v) } + preparedWrites.clear() + server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null) + } + } + + override fun onNotificationSent(device: BluetoothDevice, status: Int) { + handler?.post { + notifyPending = false + if (dirty) sendNow() + } + } + } + + private fun valueOf(chr: BluetoothGattCharacteristic): ByteArray { + val ref = reportRefs[chr] + if (ref == null) { + @Suppress("DEPRECATION") + return chr.value ?: ByteArray(0) + } + val (id, type) = ref + return when (type) { + BtPadEncoder.INPUT -> if (id == encoder.inputId()) encoder.input(current()) else ByteArray(0) + BtPadEncoder.FEATURE -> { + host?.let { d -> handler?.postDelayed({ startFastLink(d) }, FAST_LINK_DELAY_MS) } + encoder.feature(id).also { Log.i(TAG, "feature 0x%02x read -> %d".format(id, it?.size ?: -1)) } ?: ByteArray(0) + } + else -> ByteArray(0) + } + } + + private fun written(chr: BluetoothGattCharacteristic, value: ByteArray) { + val (id, type) = reportRefs[chr] ?: return + when (type) { + BtPadEncoder.FEATURE -> { + Log.i(TAG, "feature 0x%02x write %d bytes".format(id, value.size)) + encoder.setFeature(id, value) + } + BtPadEncoder.OUTPUT -> feedback(encoder.output(id, value)) + } + } + + private fun attach(device: BluetoothDevice) { + if (host == device) return + host = device + stopAdvertising() + pairingUntil = 0 + keepScanning() + sentOnce = false + notifyPending = false + Log.i(TAG, "host ${device.address} attached") + publish(Phase.CONNECTED, device) + fastLinkPending = true + handler?.removeCallbacks(periodic) + handler?.post(periodic) + } + + private fun startFastLink(device: BluetoothDevice) { + if (host != device || !fastLinkPending) return + fastLinkPending = false + requestFastLink(device) + } + + private fun requestFastLink(device: BluetoothDevice) { + val ctx = app ?: return + dropFastLink() + priorityLink = runCatching { + device.connectGatt(ctx, false, object : BluetoothGattCallback() { + override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { + if (newState == BluetoothProfile.STATE_CONNECTED && !gatt.requestMtu(MAX_MTU)) { + gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH) + } + } + + override fun onMtuChanged(gatt: BluetoothGatt, newMtu: Int, status: Int) { + handler?.post { + if (newMtu > mtu) mtu = newMtu + Log.i(TAG, "link mtu $newMtu") + } + gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH) + } + }, BluetoothDevice.TRANSPORT_LE) + }.getOrNull() + } + + private fun dropFastLink() { + priorityLink?.let { runCatching { it.disconnect(); it.close() } } + priorityLink = null + } + + private fun current(): BtPadState = BtPadState().also { s -> synchronized(latest) { s.set(latest) } } + + private fun sendIfChanged() { + if (encoder.periodMs > 0) return + if (sentOnce && current().sameAs(sent)) return + sendNow() + } + + private fun sendNow() { + val s = server ?: return + val device = host ?: return + if (notifyPending) { + dirty = true + return + } + val chr = inputChars[encoder.inputId()] ?: return + val state = current() + val value = encoder.input(state) + if (value.size > mtu - 3) { + dirty = false + return + } + val ok = runCatching { + if (Build.VERSION.SDK_INT >= 33) { + s.notifyCharacteristicChanged(device, chr, false, value) == BluetoothGatt.GATT_SUCCESS + } else { + @Suppress("DEPRECATION") + chr.value = value + @Suppress("DEPRECATION") + s.notifyCharacteristicChanged(device, chr, false) + } + }.getOrDefault(false) + dirty = !ok + notifyPending = ok + if (ok) { + sent.set(state) + sentOnce = true + } + } + + private val periodic: Runnable = object : Runnable { + override fun run() { + val h = handler ?: return + if (host == null) return + if (encoder.periodMs > 0 || dirty) sendNow() + h.postDelayed(this, if (encoder.periodMs > 0) encoder.periodMs else 50) + } + } + + private fun feedback(f: BtFeedback?) { + f ?: return + if (f.strong >= 0) rumble(f.strong, f.weak) + if (f.lightbar != null) _status.value = _status.value.copy(lightbar = f.lightbar) + } + + private fun rumble(strong: Int, weak: Int) { + val v = vibrator ?: return + val amplitude = maxOf(strong, weak * 2 / 3).coerceIn(0, 255) + runCatching { + if (amplitude == 0) v.cancel() + else v.vibrate(VibrationEffect.createOneShot(1_000, amplitude)) + } + } + + private fun publish(phase: Phase, device: BluetoothDevice? = null) { + if (!running) { + _status.value = Status(Phase.OFF) + return + } + val name = device?.let { runCatching { it.name }.getOrNull() ?: it.address } + val own = runCatching { adapter()?.name }.getOrNull() + _status.value = Status(phase, name, _status.value.lightbar.takeIf { phase == Phase.CONNECTED }, own) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/bt/BtPadReports.kt b/app/src/main/java/com/droiddeck/launcher/input/bt/BtPadReports.kt new file mode 100644 index 000000000..0f1339df4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/bt/BtPadReports.kt @@ -0,0 +1,551 @@ +package com.droiddeck.launcher.input.bt + +import java.util.zip.CRC32 +import kotlin.math.roundToInt + +class BtPadState { + @JvmField var buttons = 0 + @JvmField var lx = 0f + @JvmField var ly = 0f + @JvmField var rx = 0f + @JvmField var ry = 0f + @JvmField var lt = 0f + @JvmField var rt = 0f + @JvmField var lpx = 0f + @JvmField var lpy = 0f + @JvmField var rpx = 0f + @JvmField var rpy = 0f + + fun isDown(bit: Int) = buttons and bit != 0 + + fun set(other: BtPadState) { + buttons = other.buttons; lx = other.lx; ly = other.ly; rx = other.rx; ry = other.ry; lt = other.lt; rt = other.rt + lpx = other.lpx; lpy = other.lpy; rpx = other.rpx; rpy = other.rpy + } + + fun merge(a: BtPadState, b: BtPadState) { + buttons = a.buttons or b.buttons + lx = stronger(a.lx, b.lx); ly = stronger(a.ly, b.ly) + rx = stronger(a.rx, b.rx); ry = stronger(a.ry, b.ry) + lt = maxOf(a.lt, b.lt, if (isDown(LT)) 1f else 0f) + rt = maxOf(a.rt, b.rt, if (isDown(RT)) 1f else 0f) + val left = if (b.isDown(LPAD_TOUCH)) b else a + lpx = left.lpx; lpy = left.lpy + val right = if (b.isDown(RPAD_TOUCH)) b else a + rpx = right.rpx; rpy = right.rpy + } + + fun sameAs(o: BtPadState) = buttons == o.buttons && lx == o.lx && ly == o.ly && rx == o.rx && ry == o.ry && lt == o.lt && rt == o.rt && + lpx == o.lpx && lpy == o.lpy && rpx == o.rpx && rpy == o.rpy + + fun hat(): Int { + val x = (if (isDown(RIGHT)) 1 else 0) - (if (isDown(LEFT)) 1 else 0) + val y = (if (isDown(DOWN)) 1 else 0) - (if (isDown(UP)) 1 else 0) + return when { + x == 0 && y == -1 -> 0 + x == 1 && y == -1 -> 1 + x == 1 && y == 0 -> 2 + x == 1 && y == 1 -> 3 + x == 0 && y == 1 -> 4 + x == -1 && y == 1 -> 5 + x == -1 && y == 0 -> 6 + x == -1 && y == -1 -> 7 + else -> -1 + } + } + + companion object { + const val A = 1 shl 0 + const val B = 1 shl 1 + const val X = 1 shl 2 + const val Y = 1 shl 3 + const val LB = 1 shl 4 + const val RB = 1 shl 5 + const val LT = 1 shl 6 + const val RT = 1 shl 7 + const val SELECT = 1 shl 8 + const val START = 1 shl 9 + const val GUIDE = 1 shl 10 + const val L3 = 1 shl 11 + const val R3 = 1 shl 12 + const val UP = 1 shl 13 + const val DOWN = 1 shl 14 + const val LEFT = 1 shl 15 + const val RIGHT = 1 shl 16 + const val L4 = 1 shl 17 + const val R4 = 1 shl 18 + const val L5 = 1 shl 19 + const val R5 = 1 shl 20 + const val TOUCHPAD = 1 shl 21 + const val SHARE = 1 shl 22 + const val LPAD_TOUCH = 1 shl 23 + const val RPAD_TOUCH = 1 shl 24 + const val LPAD_CLICK = 1 shl 25 + const val RPAD_CLICK = 1 shl 26 + + private fun stronger(a: Float, b: Float) = if (Math.abs(b) > Math.abs(a)) b else a + } +} + +class BtFeedback(val strong: Int, val weak: Int, val lightbar: Int? = null) + +enum class BtPadProfile(val id: String, val vendorId: Int, val productId: Int, val version: Int) { + GENERIC("generic", 0x1209, 0x0001, 0x0100), + XBOX("xbox", 0x045E, 0x0B13, 0x0509), + DUALSHOCK4("dualshock4", 0x054C, 0x09CC, 0x0100), + DUALSENSE("dualsense", 0x054C, 0x0CE6, 0x0100), + STEAM("steam", 0x28DE, 0x1303, 0x0100); + + fun encoder(): BtPadEncoder = when (this) { + GENERIC -> GenericEncoder() + XBOX -> XboxEncoder() + DUALSHOCK4 -> DualShock4Encoder() + DUALSENSE -> DualSenseEncoder() + STEAM -> SteamControllerEncoder() + } + + companion object { + fun byId(id: String?) = entries.firstOrNull { it.id == id } ?: GENERIC + } +} + +abstract class BtPadEncoder { + abstract val descriptor: ByteArray + abstract val reports: List> + abstract fun inputId(): Int + abstract fun input(s: BtPadState): ByteArray + open val periodMs = 0L + open fun feature(id: Int): ByteArray? = null + open fun setFeature(id: Int, data: ByteArray) {} + open fun output(id: Int, data: ByteArray): BtFeedback? = null + + protected fun axis8(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 127.5f).roundToInt().coerceIn(0, 255) + protected fun trigger8(v: Float) = (v.coerceIn(0f, 1f) * 255f).roundToInt() + + protected fun ByteArray.le16(at: Int, v: Int) { this[at] = v.toByte(); this[at + 1] = (v shr 8).toByte() } + protected fun ByteArray.le32(at: Int, v: Long) { for (i in 0 until 4) this[at + i] = (v shr (8 * i)).toByte() } + + protected fun ByteArray.sealCrc(seed: Int, id: Int): ByteArray { + val crc = CRC32() + crc.update(seed) + crc.update(id) + crc.update(this, 0, size - 4) + le32(size - 4, crc.value) + return this + } + + protected fun ByteArray.payload(id: Int): ByteArray = + if (isNotEmpty() && this[0].toInt() and 0xFF == id) copyOfRange(1, size) else this + + companion object { + const val INPUT = 1 + const val OUTPUT = 2 + const val FEATURE = 3 + + fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() } + } +} + +private class GenericEncoder : BtPadEncoder() { + override val reports = listOf(1 to INPUT) + + override val descriptor = bytes( + 0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01, + 0x05, 0x09, 0x19, 0x01, 0x29, 0x18, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x18, 0x81, 0x02, + 0x05, 0x01, 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, + 0x65, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x03, + 0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02, + 0x05, 0x02, 0x09, 0xC5, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02, + 0xC0, + ) + + override fun inputId() = 1 + + override fun input(s: BtPadState): ByteArray { + var b = 0 + GENERIC_ORDER.forEachIndexed { i, bit -> if (s.isDown(bit)) b = b or (1 shl i) } + val hat = s.hat().let { if (it < 0) 8 else it } + return bytes( + b and 0xFF, (b shr 8) and 0xFF, (b shr 16) and 0xFF, hat, + axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), trigger8(s.lt), trigger8(s.rt), + ) + } + + companion object { + private val GENERIC_ORDER = intArrayOf( + BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB, + BtPadState.LT, BtPadState.RT, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3, 0, + BtPadState.L4, BtPadState.R4, BtPadState.L5, BtPadState.R5, BtPadState.TOUCHPAD, BtPadState.SHARE, 0, 0, + ) + } +} + +private class XboxEncoder : BtPadEncoder() { + override val reports = listOf(1 to INPUT, 3 to OUTPUT) + + override val descriptor = bytes( + 0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01, + 0x09, 0x01, 0xA1, 0x00, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0, + 0x09, 0x01, 0xA1, 0x00, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0, + 0x05, 0x02, 0x09, 0xC5, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03, + 0x05, 0x02, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03, + 0x05, 0x01, 0x09, 0x39, 0x15, 0x01, 0x25, 0x08, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x66, 0x14, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, + 0x75, 0x04, 0x95, 0x01, 0x15, 0x00, 0x25, 0x00, 0x35, 0x00, 0x45, 0x00, 0x65, 0x00, 0x81, 0x03, + 0x05, 0x09, 0x19, 0x01, 0x29, 0x0F, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0F, 0x81, 0x02, + 0x15, 0x00, 0x25, 0x00, 0x75, 0x01, 0x95, 0x01, 0x81, 0x03, + 0x05, 0x0C, 0x0A, 0xB2, 0x00, 0x15, 0x00, 0x25, 0x01, 0x95, 0x01, 0x75, 0x01, 0x81, 0x02, + 0x15, 0x00, 0x25, 0x00, 0x75, 0x07, 0x95, 0x01, 0x81, 0x03, + 0x05, 0x0F, 0x09, 0x21, 0x85, 0x03, 0xA1, 0x02, + 0x09, 0x97, 0x15, 0x00, 0x25, 0x01, 0x75, 0x04, 0x95, 0x01, 0x91, 0x02, + 0x15, 0x00, 0x25, 0x00, 0x75, 0x04, 0x95, 0x01, 0x91, 0x03, + 0x09, 0x70, 0x15, 0x00, 0x25, 0x64, 0x75, 0x08, 0x95, 0x04, 0x91, 0x02, + 0x09, 0x50, 0x66, 0x01, 0x10, 0x55, 0x0E, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02, + 0x09, 0xA7, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02, + 0x65, 0x00, 0x55, 0x00, 0x09, 0x7C, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02, + 0xC0, 0xC0, + ) + + override fun inputId() = 1 + + override fun input(s: BtPadState): ByteArray { + val r = ByteArray(16) + r.le16(0, axis16(s.lx)); r.le16(2, axis16(s.ly)); r.le16(4, axis16(s.rx)); r.le16(6, axis16(s.ry)) + r.le16(8, (s.lt.coerceIn(0f, 1f) * 1023f).roundToInt()) + r.le16(10, (s.rt.coerceIn(0f, 1f) * 1023f).roundToInt()) + r[12] = (s.hat() + 1).toByte() + var b = 0 + XBOX_ORDER.forEachIndexed { i, bit -> if (bit != 0 && s.isDown(bit)) b = b or (1 shl i) } + r.le16(13, b) + r[15] = if (s.isDown(BtPadState.SHARE)) 1 else 0 + return r + } + + override fun output(id: Int, data: ByteArray): BtFeedback? { + if (id != 3) return null + val d = data.payload(id) + if (d.size < 5) return null + val enable = d[0].toInt() + val strong = if (enable and 0x02 != 0) d[3].toInt() and 0xFF else 0 + val weak = if (enable and 0x01 != 0) d[4].toInt() and 0xFF else 0 + return BtFeedback(strong * 255 / 100, weak * 255 / 100) + } + + private fun axis16(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 32767.5f).roundToInt().coerceIn(0, 65535) + + companion object { + private val XBOX_ORDER = intArrayOf( + BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB, + 0, 0, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3, + ) + } +} + +private abstract class SonyEncoder : BtPadEncoder() { + @Volatile protected var enhanced = false + protected var counter = 0 + protected var timestamp = 0L + + override val periodMs = 8L + + protected fun buttons(s: BtPadState): IntArray { + val hat = s.hat().let { if (it < 0) 8 else it } + var b0 = hat + if (s.isDown(BtPadState.X)) b0 = b0 or 0x10 + if (s.isDown(BtPadState.A)) b0 = b0 or 0x20 + if (s.isDown(BtPadState.B)) b0 = b0 or 0x40 + if (s.isDown(BtPadState.Y)) b0 = b0 or 0x80 + var b1 = 0 + if (s.isDown(BtPadState.LB)) b1 = b1 or 0x01 + if (s.isDown(BtPadState.RB)) b1 = b1 or 0x02 + if (s.lt > 0.05f) b1 = b1 or 0x04 + if (s.rt > 0.05f) b1 = b1 or 0x08 + if (s.isDown(BtPadState.SELECT) || s.isDown(BtPadState.SHARE)) b1 = b1 or 0x10 + if (s.isDown(BtPadState.START)) b1 = b1 or 0x20 + if (s.isDown(BtPadState.L3)) b1 = b1 or 0x40 + if (s.isDown(BtPadState.R3)) b1 = b1 or 0x80 + var b2 = 0 + if (s.isDown(BtPadState.GUIDE)) b2 = b2 or 0x01 + if (s.isDown(BtPadState.TOUCHPAD)) b2 = b2 or 0x02 + return intArrayOf(b0, b1, b2) + } + + protected fun simple(s: BtPadState): ByteArray { + val b = buttons(s) + counter = (counter + 1) and 0x3F + return bytes(axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), b[0], b[1], b[2] or (counter shl 2), trigger8(s.lt), trigger8(s.rt)) + } + + protected fun calibration(): ByteArray { + val r = ByteArray(40) + val v = intArrayOf(0, 0, 0, GYRO, -GYRO, GYRO, -GYRO, GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL) + v.forEachIndexed { i, x -> r.le16(i * 2, x) } + return r.sealCrc(FEATURE_SEED, 0x05) + } + + override fun feature(id: Int): ByteArray? { + val reply = reply(id) ?: return null + enhanced = true + return reply + } + + protected abstract fun reply(id: Int): ByteArray? + + companion object { + const val INPUT_SEED = 0xA1 + const val OUTPUT_SEED = 0xA2 + const val FEATURE_SEED = 0xA3 + const val GYRO = 8800 + const val GYRO_SPEED = 540 + const val ACCEL = 8192 + } +} + +private class DualShock4Encoder : SonyEncoder() { + override val reports = listOf(0x01 to INPUT, 0x11 to INPUT, 0x11 to OUTPUT, 0x02 to FEATURE, 0xA3 to FEATURE, 0x05 to FEATURE, 0x12 to FEATURE) + + override val descriptor = bytes( + 0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01, + 0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02, + 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00, + 0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02, + 0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02, + 0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02, + 0x06, 0x04, 0xFF, + 0x85, 0x02, 0x09, 0x24, 0x95, 0x24, 0xB1, 0x02, + 0x85, 0xA3, 0x09, 0x25, 0x95, 0x30, 0xB1, 0x02, + 0x85, 0x05, 0x09, 0x26, 0x95, 0x28, 0xB1, 0x02, + 0x85, 0x12, 0x09, 0x27, 0x95, 0x0F, 0xB1, 0x02, + 0x85, 0x11, 0x09, 0x22, 0x95, 0x4D, 0x81, 0x02, + 0x09, 0x23, 0x95, 0x4D, 0x91, 0x02, + 0xC0, + ) + + override fun inputId() = if (enhanced) 0x11 else 0x01 + + override fun input(s: BtPadState): ByteArray { + if (!enhanced) return simple(s) + val r = ByteArray(77) + r[0] = 0xC0.toByte() + val b = buttons(s) + counter = (counter + 1) and 0x3F + timestamp += 1500 + val c = 2 + r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte() + r[c + 4] = b[0].toByte(); r[c + 5] = b[1].toByte(); r[c + 6] = (b[2] or (counter shl 2)).toByte() + r[c + 7] = trigger8(s.lt).toByte(); r[c + 8] = trigger8(s.rt).toByte() + r.le16(c + 9, timestamp.toInt()) + r.le16(c + 20, ACCEL) + r[c + 29] = 0x09 + r[c + 32] = 1 + r[c + 34] = 0x80.toByte() + r[c + 38] = 0x80.toByte() + return r.sealCrc(INPUT_SEED, 0x11) + } + + override fun reply(id: Int): ByteArray? = when (id) { + 0x02 -> ByteArray(36).also { r -> + val v = intArrayOf(0, 0, 0, GYRO, GYRO, GYRO, -GYRO, -GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL) + v.forEachIndexed { i, x -> r.le16(i * 2, x) } + } + 0x05 -> calibration() + 0xA3 -> ByteArray(48).also { r -> + "Sep 21 2018".toByteArray().copyInto(r, 0) + "04:50:51".toByteArray().copyInto(r, 16) + r.le16(34, 0x0100) + r.le16(40, 0xA00A) + } + 0x12 -> ByteArray(15).also { r -> FAKE_MAC.copyInto(r, 0); r[6] = 0x08; r[7] = 0x25 } + else -> null + } + + override fun output(id: Int, data: ByteArray): BtFeedback? { + if (id != 0x11) return null + enhanced = true + val d = data.payload(id) + if (d.size < 10) return null + val flags = d[2].toInt() + val light = if (flags and 0x02 != 0) rgb(d[7], d[8], d[9]) else null + return BtFeedback(d[6].toInt() and 0xFF, d[5].toInt() and 0xFF, light) + } +} + +private class DualSenseEncoder : SonyEncoder() { + override val reports = listOf(0x01 to INPUT, 0x31 to INPUT, 0x31 to OUTPUT, 0x05 to FEATURE, 0x09 to FEATURE, 0x20 to FEATURE) + + override val descriptor = bytes( + 0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01, + 0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02, + 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00, + 0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02, + 0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02, + 0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02, + 0x06, 0x00, 0xFF, + 0x85, 0x31, 0x09, 0x31, 0x95, 0x4D, 0x81, 0x02, + 0x09, 0x32, 0x95, 0x4D, 0x91, 0x02, + 0x85, 0x05, 0x09, 0x33, 0x95, 0x28, 0xB1, 0x02, + 0x85, 0x09, 0x09, 0x34, 0x95, 0x13, 0xB1, 0x02, + 0x85, 0x20, 0x09, 0x35, 0x95, 0x3F, 0xB1, 0x02, + 0xC0, + ) + + private var sequence = 0 + + override fun inputId() = if (enhanced) 0x31 else 0x01 + + override fun input(s: BtPadState): ByteArray { + if (!enhanced) return simple(s) + val r = ByteArray(77) + sequence = (sequence + 1) and 0xFF + timestamp += 24000 + r[0] = 0x10 + val c = 1 + r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte() + r[c + 4] = trigger8(s.lt).toByte(); r[c + 5] = trigger8(s.rt).toByte() + r[c + 6] = sequence.toByte() + val b = buttons(s) + r[c + 7] = b[0].toByte(); r[c + 8] = b[1].toByte(); r[c + 9] = b[2].toByte() + r.le16(c + 23, ACCEL) + r.le32(c + 27, timestamp) + r[c + 32] = 0x80.toByte() + r[c + 36] = 0x80.toByte() + r[c + 52] = 0x09 + return r.sealCrc(INPUT_SEED, 0x31) + } + + override fun reply(id: Int): ByteArray? = when (id) { + 0x05 -> calibration() + 0x09 -> ByteArray(19).also { r -> FAKE_MAC.copyInto(r, 0) }.sealCrc(FEATURE_SEED, 0x09) + 0x20 -> ByteArray(63).also { r -> + "Jun 19 2023".toByteArray().copyInto(r, 0) + "14:47:34".toByteArray().copyInto(r, 11) + r.le16(19, 0x0003) + r.le32(23, 0x00000615L) + r.le32(27, 0x0110002AL) + r.le16(43, 0x0630) + }.sealCrc(FEATURE_SEED, 0x20) + else -> null + } + + override fun output(id: Int, data: ByteArray): BtFeedback? { + if (id != 0x31) return null + enhanced = true + val d = data.payload(id) + if (d.size < 49) return null + val flags0 = d[2].toInt() + val flags1 = d[3].toInt() + val light = if (flags1 and 0x04 != 0) rgb(d[46], d[47], d[48]) else null + return if (flags0 and 0x03 != 0) BtFeedback(d[5].toInt() and 0xFF, d[4].toInt() and 0xFF, light) + else if (light != null) BtFeedback(-1, -1, light) else null + } +} + +private class SteamControllerEncoder : BtPadEncoder() { + override val descriptor = bytes( + 0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, + 0x85, 0x45, 0x09, 0x02, 0x95, 0x2D, 0x81, 0x02, 0x85, 0x47, 0x09, 0x03, 0x95, 0x2D, 0x81, 0x02, + 0x85, 0x80, 0x09, 0x04, 0x95, 0x09, 0x91, 0x02, 0x85, 0x81, 0x09, 0x05, 0x95, 0x07, 0x91, 0x02, + 0x85, 0x82, 0x09, 0x06, 0x95, 0x03, 0x91, 0x02, 0x85, 0x83, 0x09, 0x07, 0x95, 0x09, 0x91, 0x02, + 0x85, 0x84, 0x09, 0x08, 0x95, 0x08, 0x91, 0x02, 0x85, 0x85, 0x09, 0x09, 0x95, 0x03, 0x91, 0x02, + 0x85, 0x01, 0x09, 0x0A, 0x95, 0x3F, 0xB1, 0x02, 0xC0, + ) + override val reports = listOf(0x45 to INPUT, 0x47 to INPUT, 0x80 to OUTPUT, 0x81 to OUTPUT, 0x82 to OUTPUT, + 0x83 to OUTPUT, 0x84 to OUTPUT, 0x85 to OUTPUT, 0x01 to FEATURE) + override val periodMs = 8L + + @Volatile private var pending = 0 + private var packet = 0 + private val start = System.nanoTime() + + override fun inputId() = 0x45 + + override fun input(s: BtPadState): ByteArray { + val r = ByteArray(45) + packet++ + r[0] = packet.toByte() + var b = LGRIP_TOUCH or RGRIP_TOUCH + BUTTONS.forEach { (mine, theirs) -> if (s.isDown(mine)) b = b or theirs } + if (s.lt >= 0.98f) b = b or LTRIGGER_CLICK + if (s.rt >= 0.98f) b = b or RTRIGGER_CLICK + if (Math.abs(s.lx) > 0.06f || Math.abs(s.ly) > 0.06f) b = b or LSTICK_TOUCH + if (Math.abs(s.rx) > 0.06f || Math.abs(s.ry) > 0.06f) b = b or RSTICK_TOUCH + r.le32(1, b.toLong()) + r.le16(5, (s.lt.coerceIn(0f, 1f) * 32767f).roundToInt()) + r.le16(7, (s.rt.coerceIn(0f, 1f) * 32767f).roundToInt()) + r.le16(9, stick(s.lx)); r.le16(11, stick(-s.ly)); r.le16(13, stick(s.rx)); r.le16(15, stick(-s.ry)) + if (s.isDown(BtPadState.LPAD_TOUCH)) { + r.le16(17, stick(s.lpx)); r.le16(19, stick(-s.lpy)) + r.le16(21, if (s.isDown(BtPadState.LPAD_CLICK)) 32767 else 4000) + } + if (s.isDown(BtPadState.RPAD_TOUCH)) { + r.le16(23, stick(s.rpx)); r.le16(25, stick(-s.rpy)) + r.le16(27, if (s.isDown(BtPadState.RPAD_CLICK)) 32767 else 4000) + } + r.le32(29, (System.nanoTime() - start) / 1000) + r.le16(37, 16384) + return r + } + + override fun setFeature(id: Int, data: ByteArray) { + val d = data.payload(id) + if (id == 1 && d.isNotEmpty()) pending = d[0].toInt() and 0xFF + } + + override fun feature(id: Int): ByteArray? { + if (id != 1) return null + val r = ByteArray(63) + r[0] = pending.toByte() + when (pending) { + 0x83 -> { + val ids = intArrayOf(0x01, 0x02, 0x04, 0x09, 0x0A, 0x0B) + val values = longArrayOf(0x1303, 0, FW_TIMESTAMP, 72, 0, 4000) + r[1] = (ids.size * 5).toByte() + ids.forEachIndexed { i, a -> r[2 + i * 5] = a.toByte(); r.le32(3 + i * 5, values[i]) } + } + 0xAE -> { r[1] = 0x14; r[2] = 0x01; SERIAL.toByteArray().copyInto(r, 3) } + 0xBA -> { r[1] = 0x11; "DROIDDECKCHIP02".toByteArray().copyInto(r, 3) } + } + return r + } + + override fun output(id: Int, data: ByteArray): BtFeedback? { + val d = data.payload(id) + return when (id) { + 0x80 -> if (d.size >= 8) { + val left = (d[3].toInt() and 0xFF) or ((d[4].toInt() and 0xFF) shl 8) + val right = (d[6].toInt() and 0xFF) or ((d[7].toInt() and 0xFF) shl 8) + BtFeedback(left shr 8, right shr 8) + } else null + in 0x81..0x85 -> BtFeedback(0, 120) + else -> null + } + } + + private fun stick(v: Float) = (v.coerceIn(-1f, 1f) * 32767f).roundToInt() + + companion object { + private const val LGRIP_TOUCH = 0x20000000 + private const val RGRIP_TOUCH = 0x10000000 + private const val LTRIGGER_CLICK = 0x08000000 + private const val RTRIGGER_CLICK = 0x00800000 + private const val LSTICK_TOUCH = 0x01000000 + private const val RSTICK_TOUCH = 0x00100000 + private const val FW_TIMESTAMP = 0x6AC686B3L + private const val SERIAL = "DROIDDECKSC01" + private val BUTTONS = listOf( + BtPadState.A to 0x00000001, BtPadState.B to 0x00000002, BtPadState.X to 0x00000004, BtPadState.Y to 0x00000008, + BtPadState.SHARE to 0x00000010, BtPadState.R3 to 0x00000020, BtPadState.SELECT to 0x00000040, + BtPadState.R4 to 0x00000080, BtPadState.R5 to 0x00000100, BtPadState.RB to 0x00000200, + BtPadState.DOWN to 0x00000400, BtPadState.RIGHT to 0x00000800, BtPadState.LEFT to 0x00001000, + BtPadState.UP to 0x00002000, BtPadState.START to 0x00004000, BtPadState.L3 to 0x00008000, + BtPadState.GUIDE to 0x00010000, BtPadState.L4 to 0x00020000, BtPadState.L5 to 0x00040000, + BtPadState.LB to 0x00080000, + BtPadState.RPAD_TOUCH to 0x00200000, BtPadState.RPAD_CLICK to 0x00400000, + BtPadState.LPAD_TOUCH to 0x02000000, BtPadState.LPAD_CLICK to 0x04000000, + ) + } +} + +private val FAKE_MAC = BtPadEncoder.bytes(0x5D, 0x44, 0x33, 0x22, 0x11, 0xD0) + +private fun rgb(r: Byte, g: Byte, b: Byte) = + (0xFF shl 24) or ((r.toInt() and 0xFF) shl 16) or ((g.toInt() and 0xFF) shl 8) or (b.toInt() and 0xFF) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 1c4536fc0..434d1939f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -250,6 +250,10 @@ private fun Content( UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) return } + if (selected == "trinkets") { + TrinketsPage(modifier.padding(horizontal = padH).padding(top = padV)) + return + } if (selected == "steam") { SteamHome(s, a, modifier) return diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index ecc597c93..ec9c51265 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -54,6 +54,7 @@ import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material.icons.outlined.Storefront import androidx.compose.material.icons.outlined.SystemUpdate import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material.icons.outlined.Toys import androidx.compose.material.icons.outlined.VideoLibrary import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.material3.Icon @@ -125,7 +126,7 @@ internal fun navigationKeys(s: FrontEndState) = buildList { if (s.gameStoresEnabled) add("stores") add("desktop"); add("components") if (s.isHomeApp) add("android-apps") - add("setup"); add("updates") + add("setup"); add("updates"); add("trinkets") } internal object RailLabels { @@ -199,6 +200,7 @@ internal fun railLabelIcon(key: String): Pair = when (key) { "components" -> R.string.rail_components to Icons.Outlined.Layers "android-apps" -> R.string.rail_apps to Icons.Outlined.Apps "setup" -> R.string.rail_setup to Icons.Outlined.Tune + "trinkets" -> R.string.rail_trinkets to Icons.Outlined.Toys else -> R.string.rail_updates to Icons.Outlined.SystemUpdate } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TrinketsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/TrinketsPage.kt new file mode 100644 index 000000000..8945e3e55 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/TrinketsPage.kt @@ -0,0 +1,61 @@ +package com.droiddeck.launcher.ui + +import android.content.Intent +import androidx.compose.foundation.background +import androidx.compose.foundation.border +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.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.BluetoothConnected +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.BtControllerActivity +import com.droiddeck.launcher.R + +@Composable +internal fun TrinketsPage(modifier: Modifier) { + val context = LocalContext.current + Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(stringResource(R.string.trinkets_intro), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + Trinket(Icons.Outlined.BluetoothConnected, stringResource(R.string.btpad_title), stringResource(R.string.btpad_summary)) { + context.startActivity(Intent(context, BtControllerActivity::class.java)) + } + } +} + +@Composable +private fun Trinket(icon: ImageVector, title: String, summary: String, onOpen: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp), + modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line2, Shape14).padding(14.dp), + ) { + Box(Modifier.size(44.dp).clip(Shape12).background(pal.signal.copy(alpha = 0.14f)), contentAlignment = Alignment.Center) { + Icon(icon, null, tint = pal.signal) + } + Column(Modifier.weight(1f)) { + Text(title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) + Text(summary, fontSize = 13.sp, color = colors.onSurfaceVariant) + } + PrimaryButton(stringResource(R.string.trinkets_open), compact = true, onClick = onOpen) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 32911e9d6..cfb6becc4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1374,6 +1374,7 @@ Apps Setup Updates + Trinkets %1$d%% Resume %1$s Shows up as /root/ROMs in each session. Internal storage is at /root/Storage. @@ -3724,4 +3725,25 @@ Status Partners Followed games + Odds and ends that don\'t fit anywhere else. + Open + Bluetooth controller + Use this device as a wireless gamepad for a PC, phone, or another handheld. + Hold Select + Start to stop + Disconnect + Pair new + Stop + Touch controls + After changing the type, remove this device from the other side\'s Bluetooth list and pair again. + Starting Bluetooth controller… + Turn on Bluetooth to continue + This device\'s Bluetooth can\'t act as a controller + On the other device, add a Bluetooth device and pick %1$s. If it takes over 2 minutes, tap Pair new. + Pairing with %1$s. Accept the request on this device. + Connected to %1$s + Generic + Xbox + DualShock 4 + DualSense + Steam Controller