Redo HID device handling. No more shit abstraction on top of HidApi

This commit is contained in:
loucass003 committed 2026-09-02 16:49:57 +02:00
1 parent c09bddf148
commit e97c9a16bd
8 files changed
+629 -278

No files matched your search

@@ -27,6 +27,7 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -7,56 +7,154 @@ import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import androidx.core.content.ContextCompat
import dev.slimevr.AppContextProvider
import dev.slimevr.VRServerActions
import dev.slimevr.hid.HIDReceiver
import dev.slimevr.hid.HIDReceiverActions
import dev.slimevr.hid.HidConnection
import dev.slimevr.hid.HidDeviceDescriptor
import dev.slimevr.hid.HidTransport
import dev.slimevr.hid.isCompatibleHidReceiver
import dev.slimevr.hid.isCompatibleHidTracker
import dev.slimevr.hid.parseHIDPackets
import dev.slimevr.hid.runHidManager
import dev.slimevr.logging.AppLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.data_feed.dongle_data.DongleStatus
private const val ACTION_USB_HID_PERMISSION = "dev.slimevr.android.USB_HID_PERMISSION"
private const val HID_POLL_INTERVAL_MS = 3000L
private const val HID_WRITE_TIMEOUT_MS = 1000
private fun findHidInputEndpoint(device: UsbDevice): Pair<UsbInterface, UsbEndpoint>? {
private data class HidEndpoints(val iface: UsbInterface, val input: UsbEndpoint, val output: UsbEndpoint?)
private fun findHidEndpoints(device: UsbDevice): HidEndpoints? {
for (ifaceIdx in 0 until device.interfaceCount) {
val iface = device.getInterface(ifaceIdx)
if (iface.interfaceClass != UsbConstants.USB_CLASS_HID) continue
var input: UsbEndpoint? = null
var output: UsbEndpoint? = null
for (epIdx in 0 until iface.endpointCount) {
val endpoint = iface.getEndpoint(epIdx)
if (endpoint.type == UsbConstants.USB_ENDPOINT_XFER_INT &&
endpoint.direction == UsbConstants.USB_DIR_IN
) {
return iface to endpoint
if (endpoint.type != UsbConstants.USB_ENDPOINT_XFER_INT) continue
when (endpoint.direction) {
UsbConstants.USB_DIR_IN -> if (input == null) input = endpoint
UsbConstants.USB_DIR_OUT -> if (output == null) output = endpoint
}
}
if (input != null) return HidEndpoints(iface, input, output)
}
return null
}
private data class ActiveReceiver(val job: Job, val receiver: HIDReceiver)
private class AndroidHidConnection(
private val connection: UsbDeviceConnection,
private val endpoints: HidEndpoints,
) : HidConnection {
private val writeLock = Mutex()
fun createAndroidHIDManager(context: Context, appContext: AppContextProvider, scope: CoroutineScope) {
@Volatile
private var closed = false
override suspend fun read(buffer: ByteArray, timeoutMs: Int): Int = withContext(Dispatchers.IO) {
if (closed) return@withContext -1
connection.bulkTransfer(endpoints.input, buffer, buffer.size, timeoutMs).coerceAtLeast(0)
}
override suspend fun write(data: ByteArray): Int = writeLock.withLock {
val output = endpoints.output ?: return@withLock -1
if (closed) return@withLock -1
withContext(Dispatchers.IO) {
connection.bulkTransfer(output, data, data.size, HID_WRITE_TIMEOUT_MS)
}
}
override suspend fun close() {
writeLock.withLock {
if (closed) return@withLock
closed = true
withContext(Dispatchers.IO) {
connection.releaseInterface(endpoints.iface)
connection.close()
}
}
}
}
private class AndroidHidTransport(
private val context: Context,
private val usbManager: UsbManager,
private val permissionIntent: PendingIntent,
private val usbReceiver: BroadcastReceiver,
private val wakeChannel: Channel<Unit>,
) : HidTransport {
private val permissionRequested = mutableSetOf<String>()
override val wakeSignal: ReceiveChannel<Unit> = wakeChannel
override suspend fun enumerate(directTrackersEnabled: Boolean): Map<String, HidDeviceDescriptor> = withContext(Dispatchers.IO) {
val compatible = usbManager.deviceList.values.filter { device ->
isCompatibleHidReceiver(device.vendorId, device.productId) ||
(directTrackersEnabled && isCompatibleHidTracker(device.vendorId, device.productId))
}
for (device in compatible) {
if (usbManager.hasPermission(device) || device.deviceName in permissionRequested) continue
AppLogger.hid.info("Requesting USB HID permission for ${device.deviceName}")
usbManager.requestPermission(device, permissionIntent)
permissionRequested.add(device.deviceName)
}
permissionRequested.retainAll(compatible.mapTo(mutableSetOf()) { device -> device.deviceName })
// Only permitted devices are handed up, so the manager never tries to open one it cannot
compatible
.filter { device -> usbManager.hasPermission(device) }
.associate { device ->
device.deviceName to HidDeviceDescriptor(
key = device.deviceName,
vendorId = device.vendorId,
productId = device.productId,
serialNumber = device.serialNumber,
)
}
}
override suspend fun open(descriptor: HidDeviceDescriptor): HidConnection? = withContext(Dispatchers.IO) {
val device = usbManager.deviceList[descriptor.key] ?: return@withContext null
val endpoints = findHidEndpoints(device)
if (endpoints == null) {
AppLogger.hid.warn("No HID input endpoint found for ${descriptor.key}")
return@withContext null
}
val connection = usbManager.openDevice(device) ?: return@withContext null
if (!connection.claimInterface(endpoints.iface, true)) {
connection.close()
AppLogger.hid.warn("Failed to claim HID interface for ${descriptor.key}")
return@withContext null
}
AndroidHidConnection(connection, endpoints)
}
override suspend fun shutdown() {
context.unregisterReceiver(usbReceiver)
wakeChannel.close()
}
}
fun createAndroidHIDManager(context: Context, appContext: AppContextProvider, scope: CoroutineScope): Job {
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
val wakeSignal = Channel<Unit>(Channel.CONFLATED)
val permissionRequested = mutableSetOf<String>()
val active = mutableMapOf<String, ActiveReceiver>()
val wakeChannel = Channel<Unit>(Channel.CONFLATED)
val permissionIntent = PendingIntent.getBroadcast(
context,
@@ -67,7 +165,7 @@ fun createAndroidHIDManager(context: Context, appContext: AppContextProvider, sc
val usbReceiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
wakeSignal.trySend(Unit)
wakeChannel.trySend(Unit)
}
}
@@ -77,114 +175,6 @@ fun createAndroidHIDManager(context: Context, appContext: AppContextProvider, sc
}
ContextCompat.registerReceiver(context, usbReceiver, intentFilter, ContextCompat.RECEIVER_NOT_EXPORTED)
scope.launch {
while (isActive) {
val directTrackersEnabled = appContext.config.settings.context.state.value.data.hidConfig.trackersOverHid
val found = withContext(Dispatchers.IO) {
try {
usbManager.deviceList.values
.filter { device ->
isCompatibleHidReceiver(device.vendorId, device.productId) ||
(directTrackersEnabled && isCompatibleHidTracker(device.vendorId, device.productId))
}
.associate { device -> device.deviceName to device }
} catch (e: Exception) {
AppLogger.hid.error(e, "HID enumeration failed")
emptyMap()
}
}
for ((deviceName, device) in found) {
if (!usbManager.hasPermission(device) && deviceName !in permissionRequested) {
AppLogger.hid.info("Requesting USB HID permission for $deviceName")
usbManager.requestPermission(device, permissionIntent)
permissionRequested.add(deviceName)
}
}
val authorized = found.filter { (_, device) -> usbManager.hasPermission(device) }
val toRemove = (active.keys - authorized.keys) +
active.entries.filter { (_, entry) -> !entry.job.isActive }.map { (key, _) -> key }
for (deviceName in toRemove) {
val entry = active.remove(deviceName) ?: continue
entry.job.cancel()
entry.job.join()
permissionRequested.remove(deviceName)
AppLogger.hid.info("HID device removed: $deviceName")
}
for ((deviceName, device) in authorized) {
if (deviceName in active) continue
permissionRequested.remove(deviceName)
val hidEndpoint = findHidInputEndpoint(device)
if (hidEndpoint == null) {
AppLogger.hid.warn("No HID input endpoint found for $deviceName")
continue
}
val (iface, endpoint) = hidEndpoint
val connection = withContext(Dispatchers.IO) { usbManager.openDevice(device) }
if (connection == null) {
AppLogger.hid.warn("Failed to open HID device $deviceName")
continue
}
connection.claimInterface(iface, true)
val serial = device.serialNumber ?: deviceName
AppLogger.hid.info("HID device detected: $serial")
val deviceJob = Job(scope.coroutineContext[Job])
val deviceScope = CoroutineScope(scope.coroutineContext + deviceJob)
val receiver = appContext.server.context.state.value.dongles.values
.find { it.context.state.value.serialNumber == serial }
?: run {
val id = appContext.server.nextHandle()
val created = HIDReceiver.create(
id = id,
serialNumber = serial,
isDirect = isCompatibleHidTracker(device.vendorId, device.productId),
appContext = appContext,
scope = scope,
)
appContext.server.context.dispatch(VRServerActions.NewDongle(id, created))
created
}
receiver.context.dispatch(HIDReceiverActions.SetStatus(DongleStatus.CONNECTED))
deviceScope.launch(Dispatchers.IO) {
try {
val buffer = ByteArray(64)
while (isActive) {
val read = try {
connection.bulkTransfer(endpoint, buffer, buffer.size, 0)
} catch (_: Exception) {
-1
}
when {
read < 0 -> return@launch
read > 0 -> parseHIDPackets(buffer, read).forEach { packet -> receiver.packetEvents.emit(packet) }
else -> delay(1)
}
}
} finally {
withContext(NonCancellable + Dispatchers.IO) {
connection.releaseInterface(iface)
connection.close()
}
withContext(NonCancellable) { receiver.onDisconnected() }
}
}
deviceJob.complete()
active[deviceName] = ActiveReceiver(deviceJob, receiver)
}
permissionRequested.retainAll(found.keys)
withTimeoutOrNull(HID_POLL_INTERVAL_MS) { wakeSignal.receive() }
}
}
val transport = AndroidHidTransport(context, usbManager, permissionIntent, usbReceiver, wakeChannel)
return runHidManager(appContext, transport, scope)
}
@@ -0,0 +1,160 @@
package dev.slimevr.hid
import dev.slimevr.AppContextProvider
import dev.slimevr.VRServerActions
import dev.slimevr.logging.AppLogger
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.data_feed.dongle_data.DongleStatus
import kotlin.time.Duration.Companion.seconds
val HID_POLL_INTERVAL = 3.seconds
const val HID_READ_BUFFER_SIZE = 64
const val HID_READ_TIMEOUT_MS = 100
const val HID_STALL_READS = 30
private data class ActiveReceiver(val job: Job, val receiver: HIDReceiver)
fun runHidManager(appContext: AppContextProvider, transport: HidTransport, scope: CoroutineScope): Job {
val active = mutableMapOf<String, ActiveReceiver>()
return scope.launch {
try {
while (isActive) {
val directTrackersEnabled = appContext.config.settings.context.state.value.data.hidConfig.trackersOverHid
val found = try {
transport.enumerate(directTrackersEnabled)
} catch (e: Exception) {
AppLogger.hid.error(e, "HID enumeration failed")
emptyMap()
}
val toRemove = (active.keys - found.keys) +
active.entries.filter { !it.value.job.isActive }.map { it.key }
for (key in toRemove) {
val entry = active.remove(key) ?: continue
entry.job.cancel()
entry.job.join()
AppLogger.hid.info("HID device removed: $key")
}
for ((key, descriptor) in found) {
if (key in active) continue
val connection = try {
transport.open(descriptor)
} catch (e: Exception) {
AppLogger.hid.error(e, "Failed to open HID device: $key")
null
}
if (connection == null) {
AppLogger.hid.warn("Failed to open HID device: $key")
continue
}
val serial = descriptor.serialNumber ?: key
val isDirect = isCompatibleHidTracker(descriptor.vendorId, descriptor.productId)
AppLogger.hid.info("HID device detected: $serial")
val deviceJob = SupervisorJob(scope.coroutineContext[Job])
val deviceScope = CoroutineScope(scope.coroutineContext + deviceJob)
val receiver = appContext.server.context.state.value.dongles.values
.find { it.context.state.value.serialNumber == serial }
?: run {
val id = appContext.server.nextHandle()
val created = HIDReceiver.create(
id = id,
serialNumber = serial,
isDirect = isDirect,
appContext = appContext,
scope = scope,
)
appContext.server.context.dispatch(VRServerActions.NewDongle(id, created))
created
}
receiver.context.dispatch(HIDReceiverActions.SetStatus(DongleStatus.CONNECTED))
// Device is already open, so the body must start even if the scope is cancelled
// first: readDevice's finally is what closes it
deviceScope.launch(start = CoroutineStart.UNDISPATCHED) {
// A direct tracker legitimately goes quiet while it sleeps, so it gets no watchdog
readDevice(connection, receiver, if (isDirect) null else HID_STALL_READS)
}
deviceJob.complete()
active[key] = ActiveReceiver(deviceJob, receiver)
}
val wake = transport.wakeSignal
if (wake == null) {
delay(HID_POLL_INTERVAL)
} else {
withTimeoutOrNull(HID_POLL_INTERVAL) { wake.receive() }
}
}
} finally {
// Stop every in-flight native read before the transport tears its backend down, so we
// never call hid_exit() while another thread is still inside hid_read()/hid_close().
withContext(NonCancellable) {
for ((job) in active.values) {
job.cancel()
job.join()
}
transport.shutdown()
}
}
}
}
private suspend fun readDevice(connection: HidConnection, receiver: HIDReceiver, stallReads: Int?) {
try {
val buffer = ByteArray(HID_READ_BUFFER_SIZE)
var emptyReads = 0
while (currentCoroutineContext().isActive) {
val read = try {
connection.read(buffer, HID_READ_TIMEOUT_MS)
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
// A throwing read means the same thing as a negative one: the device is gone
-1
}
when {
// read error, device gone
read < 0 -> return
read > 0 -> {
emptyReads = 0
parseHIDPackets(buffer, read).forEach { receiver.packetEvents.emit(it) }
}
// A timeout with no data: the read already blocked, so just go again, unless the
// device has been silent long enough to count as wedged
else -> {
emptyReads++
if (stallReads != null && emptyReads >= stallReads) {
AppLogger.hid.info("No HID data from ${receiver.context.state.value.serialNumber}, reopening")
return
}
}
}
}
} finally {
withContext(NonCancellable) {
connection.close()
receiver.onDisconnected()
}
}
}
@@ -0,0 +1,33 @@
package dev.slimevr.hid
import kotlinx.coroutines.channels.ReceiveChannel
data class HidDeviceDescriptor(
/** unique per-device id from the platform: a hidraw path, or a UsbDevice name */
val key: String,
val vendorId: Int,
val productId: Int,
val serialNumber: String?,
)
interface HidConnection {
/** Bytes read into [buffer], 0 on a timeout with no data, negative if the device is gone */
suspend fun read(buffer: ByteArray, timeoutMs: Int): Int
/** Payload bytes written, or negative on failure. */
suspend fun write(data: ByteArray): Int
suspend fun close()
}
interface HidTransport {
/** Compatible devices present and ready to open, keyed by [HidDeviceDescriptor.key] */
suspend fun enumerate(directTrackersEnabled: Boolean): Map<String, HidDeviceDescriptor>
suspend fun open(descriptor: HidDeviceDescriptor): HidConnection?
/** Hotplug hint that cuts the poll wait short. Null where the platform reports no such events */
val wakeSignal: ReceiveChannel<Unit>?
suspend fun shutdown()
}
@@ -19,3 +19,8 @@ fun isCompatibleHidTracker(vid: Int, pid: Int) = TRACKER_PRODUCT_RULES.any { rul
}
fun isCompatibleHidDevice(vid: Int, pid: Int) = isCompatibleHidReceiver(vid, pid) || isCompatibleHidTracker(vid, pid)
fun hidVendorIds(directTrackersEnabled: Boolean): Set<Int> {
val rules = if (directTrackersEnabled) RECEIVER_PRODUCT_RULES + TRACKER_PRODUCT_RULES else RECEIVER_PRODUCT_RULES
return rules.mapTo(mutableSetOf()) { rule -> rule.vendorId }
}
@@ -1,10 +1,10 @@
@file:OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)
package dev.slimevr
import dev.slimevr.bvh.BVHManager
import dev.slimevr.config.AppConfig
import dev.slimevr.config.ConfigStorage
import dev.slimevr.config.GlobalConfig
import dev.slimevr.config.GlobalConfigState
import dev.slimevr.config.Settings
import dev.slimevr.config.SettingsConfigState
import dev.slimevr.config.SettingsState
@@ -62,7 +62,6 @@ import dev.slimevr.config.reduce as reduceConfig
import dev.slimevr.heightcalibration.reduce as reduceHeightCalibration
import dev.slimevr.resets.reduce as reduceResets
import dev.slimevr.skeleton.reduce as reduceSkeleton
import dev.slimevr.solarxr.reduce as reduceSolarXR
import dev.slimevr.tracker.reduce as reduceTracker
import dev.slimevr.udp.reduce as reduceUdpServer
@@ -199,7 +198,7 @@ fun buildTestSettings(scope: CoroutineScope): Settings {
fun buildTestHeightCalibration(server: VRServer, userConfig: UserConfig, scope: CoroutineScope): HeightCalibrationManager {
val initialState = HeightCalibrationState(status = UserHeightCalibrationStatus.NONE, currentHeight = 1.6f, canDoUserHeightCalibration = true)
val context = Context.create<HeightCalibrationState, HeightCalibrationActions>(
val context = Context.create(
initialState = initialState,
scope = scope,
reducer = ::reduceHeightCalibration,
@@ -222,10 +221,29 @@ fun buildTestAppContext(server: VRServer): AppContextProvider = object : TestApp
override val server: VRServer = server
}
fun buildTestAppConfig(scope: CoroutineScope): AppConfig {
val globalContext = Context.create(
initialState = GlobalConfigState(),
scope = scope,
reducer = ::reduceConfig,
name = "GlobalConfig[test]",
)
return AppConfig(
globalConfig = GlobalConfig(globalContext).also { it.startObserving() },
userConfig = buildTestUserConfig(scope),
settings = buildTestSettings(scope),
)
}
fun buildTestAppContext(server: VRServer, config: AppConfig): AppContextProvider = object : TestAppContext() {
override val server: VRServer = server
override val config: AppConfig = config
}
private fun buildTestUdpServer(): dev.slimevr.udp.UdpServer {
val context = Context.create(
initialState = dev.slimevr.udp.UdpServerState(emptyMap()),
scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Job()),
scope = CoroutineScope(kotlinx.coroutines.Job()),
reducer = ::reduceUdpServer,
name = "TestUdpServer",
)
@@ -0,0 +1,200 @@
package dev.slimevr.hid
import dev.slimevr.VRServer
import dev.slimevr.buildTestAppConfig
import dev.slimevr.buildTestAppContext
import dev.slimevr.buildTestVrServerStub
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runTest
import solarxr_protocol.data_feed.dongle_data.DongleStatus
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
private const val RECEIVER_VID = 0x1209
private const val RECEIVER_PID = 0x7690
private const val TRACKER_PID = 0x7692
private const val PATH = "/dev/hidraw0"
private fun descriptor(key: String, productId: Int, serial: String?) = HidDeviceDescriptor(
key = key,
vendorId = RECEIVER_VID,
productId = productId,
serialNumber = serial,
)
private fun registerFrame(hidId: Int, address: Long): ByteArray {
val frame = ByteArray(16)
frame[0] = 0xFF.toByte()
frame[1] = hidId.toByte()
for (byte in 0 until 6) frame[2 + byte] = (address shr (byte * 8) and 0xFF).toByte()
return frame
}
private class FakeHidConnection(private val onClose: () -> Unit) : HidConnection {
val frames = ArrayDeque<ByteArray>()
override suspend fun read(buffer: ByteArray, timeoutMs: Int): Int {
val frame = frames.removeFirstOrNull()
if (frame == null) {
delay(timeoutMs.toLong())
return 0
}
frame.copyInto(buffer)
return frame.size
}
override suspend fun write(data: ByteArray): Int = data.size
override suspend fun close() = onClose()
}
private class FakeHidTransport : HidTransport {
val present = mutableMapOf<String, HidDeviceDescriptor>()
val connections = mutableMapOf<String, FakeHidConnection>()
val closed = mutableSetOf<String>()
var openCount = 0
private set
var shutdownCalled = false
private set
override val wakeSignal: ReceiveChannel<Unit>? = null
override suspend fun enumerate(directTrackersEnabled: Boolean): Map<String, HidDeviceDescriptor> = present.toMap()
override suspend fun open(descriptor: HidDeviceDescriptor): HidConnection {
openCount++
return FakeHidConnection { closed += descriptor.key }.also { connections[descriptor.key] = it }
}
override suspend fun shutdown() {
shutdownCalled = true
}
}
private class Harness(val server: VRServer, val job: Job)
private fun startHidManager(transport: FakeHidTransport, scope: CoroutineScope): Harness {
val server = buildTestVrServerStub(scope)
val appContext = buildTestAppContext(server, buildTestAppConfig(scope))
return Harness(server, runHidManager(appContext, transport, scope))
}
private fun dongles(server: VRServer) = server.context.state.value.dongles.values.toList()
@OptIn(ExperimentalCoroutinesApi::class)
class HidManagerTest {
@Test
fun `opens a detected receiver and forwards its packets`() = runTest {
val fake = FakeHidTransport()
fake.present[PATH] = descriptor(PATH, RECEIVER_PID, "DONGLE1")
val harness = startHidManager(fake, backgroundScope)
advanceTimeBy(100)
val dongle = dongles(harness.server).single()
assertEquals("DONGLE1", dongle.context.state.value.serialNumber)
assertEquals(DongleStatus.CONNECTED, dongle.context.state.value.status)
fake.connections.getValue(PATH).frames += registerFrame(3, 0xAABBCCDDEEFFL)
advanceTimeBy(500)
assertEquals("AABBCCDDEEFF", dongle.context.state.value.trackers[3]?.address)
}
@Test
fun `falls back to the device key when it reports no serial`() = runTest {
val fake = FakeHidTransport()
fake.present[PATH] = descriptor(PATH, RECEIVER_PID, null)
val harness = startHidManager(fake, backgroundScope)
advanceTimeBy(100)
assertEquals(PATH, dongles(harness.server).single().context.state.value.serialNumber)
}
@Test
fun `marks the dongle disconnected once it stops being enumerated`() = runTest {
val fake = FakeHidTransport()
fake.present[PATH] = descriptor(PATH, RECEIVER_PID, "DONGLE1")
val harness = startHidManager(fake, backgroundScope)
advanceTimeBy(100)
val dongle = dongles(harness.server).single()
fake.present.remove(PATH)
advanceTimeBy(4_000)
assertEquals(DongleStatus.DISCONNECTED, dongle.context.state.value.status)
assertTrue(PATH in fake.closed)
}
@Test
fun `reuses the existing receiver when the same serial comes back`() = runTest {
val fake = FakeHidTransport()
fake.present[PATH] = descriptor(PATH, RECEIVER_PID, "DONGLE1")
val harness = startHidManager(fake, backgroundScope)
advanceTimeBy(100)
val first = dongles(harness.server).single()
fake.present.remove(PATH)
advanceTimeBy(4_000)
// Same dongle on a different port, so the key changes but the serial does not
fake.present["/dev/hidraw1"] = descriptor("/dev/hidraw1", RECEIVER_PID, "DONGLE1")
advanceTimeBy(4_000)
assertEquals(1, dongles(harness.server).size)
assertEquals(first, dongles(harness.server).single())
assertEquals(DongleStatus.CONNECTED, first.context.state.value.status)
assertEquals(2, fake.openCount)
}
@Test
fun `reopens a receiver that stays enumerated but goes silent`() = runTest {
val fake = FakeHidTransport()
fake.present[PATH] = descriptor(PATH, RECEIVER_PID, "DONGLE1")
startHidManager(fake, backgroundScope)
// 30 empty reads at 100ms is the stall threshold, plus a poll interval to reopen
advanceTimeBy(7_000)
assertTrue(fake.openCount > 1, "expected a reopen, opened ${fake.openCount} time(s)")
}
@Test
fun `never reopens a silent direct tracker`() = runTest {
val fake = FakeHidTransport()
fake.present[PATH] = descriptor(PATH, TRACKER_PID, "TRACKER1")
val harness = startHidManager(fake, backgroundScope)
advanceTimeBy(20_000)
assertEquals(1, fake.openCount)
assertTrue(dongles(harness.server).single().context.state.value.isDirect)
}
@Test
fun `closes every device before shutting the transport down`() = runTest {
val fake = FakeHidTransport()
fake.present[PATH] = descriptor(PATH, RECEIVER_PID, "DONGLE1")
val harness = startHidManager(fake, backgroundScope)
advanceTimeBy(100)
harness.job.cancelAndJoin()
assertTrue(PATH in fake.closed)
assertTrue(fake.shutdownCalled)
}
}
@@ -1,169 +1,113 @@
package dev.slimevr.desktop.hid
import dev.slimevr.AppContextProvider
import dev.slimevr.VRServerActions
import dev.slimevr.hid.HIDReceiver
import dev.slimevr.hid.HIDReceiverActions
import dev.slimevr.hid.HidConnection
import dev.slimevr.hid.HidDeviceDescriptor
import dev.slimevr.hid.HidTransport
import dev.slimevr.hid.hidVendorIds
import dev.slimevr.hid.isCompatibleHidReceiver
import dev.slimevr.hid.isCompatibleHidTracker
import dev.slimevr.hid.parseHIDPackets
import dev.slimevr.logging.AppLogger
import dev.slimevr.hid.runHidManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.hid4java.HidDevice
import org.hid4java.HidManager
import org.hid4java.HidServicesSpecification
import org.hid4java.jna.HidApi
import org.hid4java.jna.HidDeviceInfoStructure
import solarxr_protocol.data_feed.dongle_data.DongleStatus
import org.hid4java.jna.HidDeviceStructure
private const val HID_POLL_INTERVAL_MS = 3000L
private val hidLibLock = Any()
private var hidLibInitialized = false
// A HID report is 64 bytes, which parseHIDPackets splits into four 16-byte packets
private const val HID_READ_BUFFER_SIZE = 64
// Bounds how long cancellation waits on the uninterruptible native read when a device is idle
private const val HID_READ_TIMEOUT_MS = 100
// We manage device open/close/read ourselves; hid4java's own shutdown hook would call
// HidApi.exit() on a separate thread with no coordination, racing our in-flight native reads.
// hidapi's own contract forbids this (hid_exit must not run concurrently with hid_read on
// another thread), and the same call shape has hung indefinitely on Windows before:
// https://github.com/libusb/hidapi/issues/133
private val hidSpec = HidServicesSpecification().apply {
isAutoStart = false
isAutoShutdown = false
private fun ensureHidApi() {
synchronized(hidLibLock) {
if (hidLibInitialized) return
HidApi.init()
hidLibInitialized = true
}
}
// Initialize the native HID library. Must be called before enumerateDevices.
private val hidServices by lazy { HidManager.getHidServices(hidSpec) }
private fun shutdownHidApi() {
synchronized(hidLibLock) {
if (!hidLibInitialized) return
HidApi.exit()
hidLibInitialized = false
}
}
private fun enumerateCompatibleDevices(directTrackersEnabled: Boolean): Map<String, HidDevice> {
hidServices // ensure native lib is loaded
val root = HidApi.enumerateDevices(0, 0) ?: return emptyMap()
val result = mutableMapOf<String, HidDevice>()
var info: HidDeviceInfoStructure? = root
while (info != null) {
val vid = info.vendor_id.toInt()
val pid = info.product_id.toInt()
if (isCompatibleHidReceiver(vid, pid) || (directTrackersEnabled && isCompatibleHidTracker(vid, pid))) {
val device = HidDevice(info, null, hidSpec)
// Use path as key, unique per physical device, available without opening
result[info.path] = device
private fun enumerateHidDevices(directTrackersEnabled: Boolean): Map<String, HidDeviceDescriptor> {
ensureHidApi()
val result = mutableMapOf<String, HidDeviceDescriptor>()
for (vendorId in hidVendorIds(directTrackersEnabled)) {
val root = HidApi.enumerateDevices(vendorId, 0) ?: continue
try {
var info: HidDeviceInfoStructure? = root
while (info != null) {
val vid = info.vendor_id.toInt() and 0xFFFF
val pid = info.product_id.toInt() and 0xFFFF
if (isCompatibleHidReceiver(vid, pid) || (directTrackersEnabled && isCompatibleHidTracker(vid, pid))) {
// Needs to be copied over as freeEnumeration would free the memory. JNA shenanigans
result[info.path] = HidDeviceDescriptor(
key = info.path,
vendorId = vid,
productId = pid,
serialNumber = info.serial_number?.toString(),
)
}
info = info.next()
}
} finally {
HidApi.freeEnumeration(root)
}
info = info.next()
}
HidApi.freeEnumeration(root)
return result
}
private data class ActiveReceiver(val job: Job, val receiver: HIDReceiver)
private class DesktopHidConnection(private val struct: HidDeviceStructure) : HidConnection {
private val writeLock = Mutex()
fun createDesktopHIDManager(appContext: AppContextProvider, scope: CoroutineScope): Job {
val active = mutableMapOf<String, ActiveReceiver>()
@Volatile
private var closed = false
return scope.launch {
try {
while (isActive) {
val directTrackersEnabled = appContext.config.settings.context.state.value.data.hidConfig.trackersOverHid
val found = withContext(Dispatchers.IO) {
try {
enumerateCompatibleDevices(directTrackersEnabled)
} catch (e: Exception) {
AppLogger.hid.error(e, "HID enumeration failed")
emptyMap()
}
}
override suspend fun read(buffer: ByteArray, timeoutMs: Int): Int = withContext(Dispatchers.IO) {
if (closed) return@withContext -1
HidApi.read(struct, buffer, timeoutMs)
}
// Devices no longer present + jobs that exited on their own (read error)
val toRemove = (active.keys - found.keys) +
active.entries.filter { !it.value.job.isActive }.map { it.key }
for (path in toRemove) {
val entry = active.remove(path) ?: continue
entry.job.cancel()
entry.job.join()
AppLogger.hid.info("HID device removed: $path")
}
override suspend fun write(data: ByteArray): Int = writeLock.withLock {
if (closed) return@withLock -1
withContext(Dispatchers.IO) {
val written = HidApi.write(struct, data, data.size, 0)
if (written > 0) written - 1 else written
}
}
// Open newly detected devices
for ((path, hidDevice) in found) {
if (path in active) continue
if (!hidDevice.open()) {
AppLogger.hid.warn("Failed to open HID device: $path")
continue
}
val serial = hidDevice.serialNumber ?: path
AppLogger.hid.info("HID device detected: $serial")
val deviceJob = SupervisorJob(scope.coroutineContext[Job])
val deviceScope = CoroutineScope(scope.coroutineContext + deviceJob)
val receiver = appContext.server.context.state.value.dongles.values
.find { it.context.state.value.serialNumber == serial }
?: run {
val id = appContext.server.nextHandle()
val created = HIDReceiver.create(
id = id,
serialNumber = serial,
isDirect = isCompatibleHidTracker(hidDevice.vendorId, hidDevice.productId),
appContext = appContext,
scope = scope,
)
appContext.server.context.dispatch(VRServerActions.NewDongle(id, created))
created
}
receiver.context.dispatch(HIDReceiverActions.SetStatus(DongleStatus.CONNECTED))
deviceScope.launch(Dispatchers.IO) {
try {
// Reused across reads: parseHIDPackets is told how much of it is live
val buffer = ByteArray(HID_READ_BUFFER_SIZE)
while (isActive) {
val read = try {
hidDevice.read(buffer, HID_READ_TIMEOUT_MS)
} catch (_: Exception) {
-1
}
when {
// read error, device gone
read < 0 -> return@launch
read > 0 -> parseHIDPackets(buffer, read).forEach { receiver.packetEvents.emit(it) }
// 0 is a timeout with no data: the read already blocked, so just go again
}
}
} finally {
withContext(NonCancellable + Dispatchers.IO) { hidDevice.close() }
withContext(NonCancellable) { receiver.onDisconnected() }
}
}
deviceJob.complete()
active[path] = ActiveReceiver(deviceJob, receiver)
}
delay(HID_POLL_INTERVAL_MS)
}
} finally {
// Stop every in-flight native read before HidApi.exit() runs, so we never
// call hid_exit() while another thread is still inside hid_read()/hid_close().
withContext(NonCancellable) {
for (entry in active.values) {
entry.job.cancel()
entry.job.join()
}
withContext(Dispatchers.IO) { HidApi.exit() }
}
override suspend fun close() {
writeLock.withLock {
if (closed) return@withLock
closed = true
withContext(Dispatchers.IO) { HidApi.close(struct) }
}
}
}
private class DesktopHidTransport : HidTransport {
override val wakeSignal: ReceiveChannel<Unit>? = null
override suspend fun enumerate(directTrackersEnabled: Boolean): Map<String, HidDeviceDescriptor> = withContext(Dispatchers.IO) {
enumerateHidDevices(directTrackersEnabled)
}
override suspend fun open(descriptor: HidDeviceDescriptor): HidConnection? = withContext(Dispatchers.IO) {
ensureHidApi()
HidApi.open(descriptor.key)?.let { struct -> DesktopHidConnection(struct) }
}
override suspend fun shutdown() = withContext(Dispatchers.IO) { shutdownHidApi() }
}
fun createDesktopHIDManager(appContext: AppContextProvider, scope: CoroutineScope): Job = runHidManager(appContext, DesktopHidTransport(), scope)