我能够成功连接到蓝牙HID设备,并能够控制配对设备的home键和导航键。但无法将键盘键事件正确地发送到HID设备。当我在主机设备中输入一些东西时,HID设备响应随机动作。
对于与描述符数组
的连接,我有以下代码override fun onServiceConnected(profile: Int, proxy: BluetoothProfile?) {
if (profile == BluetoothProfile.HID_DEVICE) {
mBtHidDevice = proxy as BluetoothHidDevice
val sdp = BluetoothHidDeviceAppSdpSettings(
"HidControl",
"Android HID Joystick",
"Android",
0xC0.toByte(),
descriptor
)
}
}
描述符数组如下,
private val descriptor = byteArrayOf( // HID descriptor
0x09, // bLength
0x21, // bDescriptorType - HID
0x11, 0x01, // bcdHID (little endian - 1.11)
0x00, // bCountryCode
0x01, // bNumDescriptors (min 1)
0x22, // bDescriptorType - Report
0x30, 0x00, // wDescriptorLength (48)
// Report descriptor
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
0x09, 0x06, // USAGE (Key board)
0xa1.toByte(), 0x01, // COLLECTION (Application)
0xa1.toByte(), 0x00, // COLLECTION (Physical)
0x05, 0x09, // USAGE_PAGE (Button)
0x19, 0x01, // USAGE_MINIMUM (Button 1)
0x29, 0x04, // USAGE_MAXIMUM (Button 4)
0x15, 0x00, // LOGICAL_MINIMUM (0)
0x25, 0x01, // LOGICAL_MAXIMUM (1)
0x75, 0x01, // REPORT_SIZE (1)
0x95.toByte(), 0x04, // REPORT_COUNT (4)
0x81.toByte(), 0x02, // INPUT (Data,Var,Abs)
0x75, 0x04, // REPORT_SIZE (4)
0x95.toByte(), 0x01, // REPORT_COUNT (1)
0x81.toByte(), 0x03, // INPUT (Cnst,Var,Abs)
0x05, 0x01, // USAGE_PAGE (Generic Desktop)
0x09, 0x30, // USAGE (X)
0x09, 0x31, // USAGE (Y)
0x15, 0x81.toByte(), // LOGICAL_MINIMUM (-127)
0x25, 0x7f, // LOGICAL_MAXIMUM (127)
0x75, 0x08, // REPORT_SIZE (8)
0x95.toByte(), 0x02, // REPORT_COUNT (2)
0x81.toByte(), 0x02, // INPUT (Data,Var,Abs)
0xc0.toByte(), // END_COLLECTION
0xc0.toByte() // END_COLLECTION
)
发送键盘事件到目标设备的代码在
下面override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
Log.d("Key Codes ", "$keyCode + event: $event")
for (btDev in mBtHidDevice!!.connectedDevices) {
mBtHidDevice!!.sendReport(
btDev, 0, byteArrayOf(event!!.keyCode.toByte())
)
mBtHidDevice!!.sendReport(
btDev, 0, byteArrayOf(
0
)
)
}
return super.onKeyUp(keyCode, event)
}
如果我在这里遗漏了什么,请建议。谢谢你的帮助!
你需要使用键盘使用页面
我看到的逻辑最小值和逻辑最大值只有1到4。你只想要那些用法?
参考HID使用表https://www.usb.org/document-library/hid-usage-tables-122
在附录中有一个键盘用例。你可以参考一下