|
| 1 | +package dev.slimevr.android.tracking.trackers.hid |
| 2 | + |
| 3 | +import android.app.PendingIntent |
| 4 | +import android.content.BroadcastReceiver |
| 5 | +import android.content.Context |
| 6 | +import android.content.Intent |
| 7 | +import android.content.IntentFilter |
| 8 | +import android.hardware.usb.UsbDevice |
| 9 | +import android.hardware.usb.UsbManager |
| 10 | +import androidx.core.content.ContextCompat |
| 11 | +import dev.slimevr.tracking.trackers.Device |
| 12 | +import dev.slimevr.tracking.trackers.Tracker |
| 13 | +import dev.slimevr.tracking.trackers.TrackerStatus |
| 14 | +import dev.slimevr.tracking.trackers.hid.HIDCommon |
| 15 | +import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_PID |
| 16 | +import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_VID |
| 17 | +import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.PACKET_SIZE |
| 18 | +import dev.slimevr.tracking.trackers.hid.HIDDevice |
| 19 | +import io.eiren.util.logging.LogManager |
| 20 | +import java.nio.ByteBuffer |
| 21 | +import java.util.function.Consumer |
| 22 | + |
| 23 | +const val ACTION_USB_PERMISSION = "dev.slimevr.USB_PERMISSION" |
| 24 | + |
| 25 | +/** |
| 26 | + * Handles Android USB Host HID dongles and receives tracker data from them. |
| 27 | + */ |
| 28 | +class AndroidHIDManager( |
| 29 | + name: String, |
| 30 | + private val trackersConsumer: Consumer<Tracker>, |
| 31 | + private val context: Context, |
| 32 | +) : Thread(name) { |
| 33 | + private val devices: MutableList<HIDDevice> = mutableListOf() |
| 34 | + private val devicesBySerial: MutableMap<String, MutableList<Int>> = HashMap() |
| 35 | + private val devicesByHID: MutableMap<UsbDevice, MutableList<Int>> = HashMap() |
| 36 | + private val connByHID: MutableMap<UsbDevice, AndroidHIDDevice> = HashMap() |
| 37 | + private val lastDataByHID: MutableMap<UsbDevice, Int> = HashMap() |
| 38 | + private val usbManager: UsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager |
| 39 | + |
| 40 | + val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() { |
| 41 | + override fun onReceive(context: Context, intent: Intent) { |
| 42 | + when (intent.action) { |
| 43 | + UsbManager.ACTION_USB_DEVICE_ATTACHED -> { |
| 44 | + (intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice?)?.let { |
| 45 | + checkConfigureDevice(it, requestPermission = true) |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + UsbManager.ACTION_USB_DEVICE_DETACHED -> { |
| 50 | + (intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice?)?.let { |
| 51 | + removeDevice(it) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + ACTION_USB_PERMISSION -> { |
| 56 | + deviceEnumerate(false) |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + private fun proceedWithDeviceConfiguration(hidDevice: UsbDevice) { |
| 63 | + // This is the original logic from checkConfigureDevice after permission is confirmed |
| 64 | + LogManager.info("[TrackerServer] USB Permission granted for ${hidDevice.deviceName}. Proceeding with configuration.") |
| 65 | + |
| 66 | + // Close any existing connection (do we still have one?) |
| 67 | + this.connByHID[hidDevice]?.close() |
| 68 | + // Open new HID connection with USB device |
| 69 | + this.connByHID[hidDevice] = AndroidHIDDevice(hidDevice, usbManager) |
| 70 | + |
| 71 | + val serial = hidDevice.serialNumber ?: "Unknown USB Device ${hidDevice.deviceId}" |
| 72 | + this.devicesBySerial[serial]?.let { |
| 73 | + this.devicesByHID[hidDevice] = it |
| 74 | + synchronized(this.devices) { |
| 75 | + for (id in it) { |
| 76 | + val device = this.devices[id] |
| 77 | + for (value in device.trackers.values) { |
| 78 | + if (value.status == TrackerStatus.DISCONNECTED) value.status = TrackerStatus.OK |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + LogManager.info("[TrackerServer] Linked HID device reattached: $serial") |
| 83 | + return |
| 84 | + } |
| 85 | + |
| 86 | + val list: MutableList<Int> = mutableListOf() |
| 87 | + this.devicesBySerial[serial] = list |
| 88 | + this.devicesByHID[hidDevice] = list |
| 89 | + this.lastDataByHID[hidDevice] = 0 // initialize last data received |
| 90 | + LogManager.info("[TrackerServer] (Probably) Compatible HID device detected: $serial") |
| 91 | + } |
| 92 | + |
| 93 | + fun checkConfigureDevice(usbDevice: UsbDevice, requestPermission: Boolean = false) { |
| 94 | + if (usbDevice.vendorId == HID_TRACKER_RECEIVER_VID && usbDevice.productId == HID_TRACKER_RECEIVER_PID) { |
| 95 | + if (usbManager.hasPermission(usbDevice)) { |
| 96 | + LogManager.info("[TrackerServer] Already have permission for ${usbDevice.deviceName}") |
| 97 | + proceedWithDeviceConfiguration(usbDevice) |
| 98 | + } else if (requestPermission) { |
| 99 | + LogManager.info("[TrackerServer] Requesting permission for ${usbDevice.deviceName}") |
| 100 | + val permissionIntent = PendingIntent.getBroadcast( |
| 101 | + context, |
| 102 | + 0, |
| 103 | + Intent(ACTION_USB_PERMISSION).apply { setPackage(context.packageName) }, // Explicitly set package |
| 104 | + PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, |
| 105 | + ) |
| 106 | + usbManager.requestPermission(usbDevice, permissionIntent) |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private fun removeDevice(hidDevice: UsbDevice) { |
| 112 | + this.devicesByHID[hidDevice]?.let { |
| 113 | + synchronized(this.devices) { |
| 114 | + for (id in it) { |
| 115 | + val device = this.devices[id] |
| 116 | + for (value in device.trackers.values) { |
| 117 | + if (value.status == TrackerStatus.OK) { |
| 118 | + value.status = |
| 119 | + TrackerStatus.DISCONNECTED |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + this.devicesByHID.remove(hidDevice) |
| 126 | + |
| 127 | + val oldConn = this.connByHID.remove(hidDevice) |
| 128 | + val serial = oldConn?.serialNumber ?: "Unknown" |
| 129 | + oldConn?.close() |
| 130 | + |
| 131 | + LogManager.info("[TrackerServer] Linked HID device removed: $serial") |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private fun dataRead() { |
| 136 | + synchronized(devicesByHID) { |
| 137 | + var devicesPresent = false |
| 138 | + var devicesDataReceived = false |
| 139 | + val q = intArrayOf(0, 0, 0, 0) |
| 140 | + val a = intArrayOf(0, 0, 0) |
| 141 | + val m = intArrayOf(0, 0, 0) |
| 142 | + for ((hidDevice, deviceList) in devicesByHID) { |
| 143 | + val dataReceived = ByteArray(64) |
| 144 | + val conn = connByHID[hidDevice]!! |
| 145 | + val dataRead = conn.deviceConnection.bulkTransfer(conn.endpointIn, dataReceived, dataReceived.size, 0) |
| 146 | + |
| 147 | + // LogManager.info("[TrackerServer] HID data read ($dataRead bytes): ${dataReceived.contentToString()}") |
| 148 | + |
| 149 | + devicesPresent = true // Even if the device has no data |
| 150 | + if (dataRead > 0) { |
| 151 | + // Process data |
| 152 | + // The data is always received as 64 bytes, this check no longer works |
| 153 | + if (dataRead % PACKET_SIZE != 0) { |
| 154 | + LogManager.info("[TrackerServer] Malformed HID packet, ignoring") |
| 155 | + continue // Don't continue with this data |
| 156 | + } |
| 157 | + devicesDataReceived = true // Data is received and is valid (not malformed) |
| 158 | + lastDataByHID[hidDevice] = 0 // reset last data received |
| 159 | + val packetCount = dataRead / PACKET_SIZE |
| 160 | + var i = 0 |
| 161 | + while (i < packetCount * PACKET_SIZE) { |
| 162 | + // Common packet data |
| 163 | + val packetType = dataReceived[i].toUByte().toInt() |
| 164 | + val id = dataReceived[i + 1].toUByte().toInt() |
| 165 | + val deviceId = id |
| 166 | + |
| 167 | + // Register device |
| 168 | + if (packetType == 255) { // device register packet from receiver |
| 169 | + val buffer = ByteBuffer.wrap(dataReceived, i + 2, 8) |
| 170 | + buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN) |
| 171 | + val addr = buffer.getLong() and 0xFFFFFFFFFFFF |
| 172 | + val deviceName = String.format("%012X", addr) |
| 173 | + HIDCommon.deviceIdLookup(devices, hidDevice.serialNumber, deviceId, deviceName, deviceList) // register device |
| 174 | + // server wants tracker to be unique, so use combination of hid serial and full id |
| 175 | + i += PACKET_SIZE |
| 176 | + continue |
| 177 | + } |
| 178 | + |
| 179 | + val device: HIDDevice? = HIDCommon.deviceIdLookup(devices, hidDevice.serialNumber, deviceId, null, deviceList) |
| 180 | + if (device == null) { // not registered yet |
| 181 | + i += PACKET_SIZE |
| 182 | + continue |
| 183 | + } |
| 184 | + |
| 185 | + HIDCommon.processPacket(dataReceived, i, packetType, device, q, a, m, trackersConsumer) |
| 186 | + i += PACKET_SIZE |
| 187 | + } |
| 188 | + // LogManager.info("[TrackerServer] HID received $packetCount tracker packets") |
| 189 | + } else { |
| 190 | + lastDataByHID[hidDevice] = lastDataByHID[hidDevice]!! + 1 // increment last data received |
| 191 | + } |
| 192 | + } |
| 193 | + if (!devicesPresent) { |
| 194 | + sleep(10) // No hid device, "empty loop" so sleep to save the poor cpu |
| 195 | + } else if (!devicesDataReceived) { |
| 196 | + sleep(1) // read has no timeout, no data also causes an "empty loop" |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + private fun deviceEnumerate(requestPermission: Boolean = false) { |
| 202 | + val hidDeviceList: MutableList<UsbDevice> = usbManager.deviceList.values.filter { |
| 203 | + it.vendorId == HID_TRACKER_RECEIVER_VID && it.productId == HID_TRACKER_RECEIVER_PID |
| 204 | + }.toMutableList() |
| 205 | + synchronized(devicesByHID) { |
| 206 | + // Work on devicesByHid and add/remove as necessary |
| 207 | + val removeList: MutableList<UsbDevice> = devicesByHID.keys.toMutableList() |
| 208 | + removeList.removeAll(hidDeviceList) |
| 209 | + for (device in removeList) { |
| 210 | + removeDevice(device) |
| 211 | + } |
| 212 | + |
| 213 | + hidDeviceList.removeAll(devicesByHID.keys) // addList |
| 214 | + for (device in hidDeviceList) { |
| 215 | + // This will handle permission check/request |
| 216 | + checkConfigureDevice(device, requestPermission) |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + override fun run() { |
| 222 | + val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED) |
| 223 | + intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED) |
| 224 | + intentFilter.addAction(ACTION_USB_PERMISSION) |
| 225 | + |
| 226 | + // Listen for USB device attach/detach |
| 227 | + ContextCompat.registerReceiver( |
| 228 | + context, |
| 229 | + usbReceiver, |
| 230 | + intentFilter, |
| 231 | + ContextCompat.RECEIVER_NOT_EXPORTED, |
| 232 | + ) |
| 233 | + |
| 234 | + // Enumerate existing devices |
| 235 | + deviceEnumerate(true) |
| 236 | + |
| 237 | + // Data read loop |
| 238 | + while (true) { |
| 239 | + try { |
| 240 | + sleep(0) // Possible performance impact |
| 241 | + } catch (e: InterruptedException) { |
| 242 | + currentThread().interrupt() |
| 243 | + break |
| 244 | + } |
| 245 | + dataRead() // not in try catch? |
| 246 | + } |
| 247 | + } |
| 248 | + |
| 249 | + fun getDevices(): List<Device> = devices |
| 250 | + |
| 251 | + companion object { |
| 252 | + private const val resetSourceName = "TrackerServer" |
| 253 | + } |
| 254 | +} |
0 commit comments