我正在尝试通过 USB 从一组称重秤中获取重量值。这应该很简单,根据他们的文档,我需要发送两个字节,字母“W”和回车字节。然后它以 16 字节的数据作为响应,表示设备上的当前重量。
该设备有 1 个接口,2 个端点,最大数据包大小为 64。我相信我必须使用该bulkTransfer
函数,因为端点类型是 USB_ENDPOINT_XFER_BULK。
我应该如何发送此请求并接收响应?我的尝试如下,响应只是一个标题符号的开始,然后是一个反引号符号“`”和一个零负载。我试图在轮询循环或单个请求上运行代码,但得到相同的结果。
val connection = usbManager.openDevice(scales)
val intf: UsbInterface = scales.getInterface(0)
connection.claimInterface(intf, true)
val endpointReadIn = intf.getEndpoint(0)
val endpointWriteOut = intf.getEndpoint(1)
val bytes = byteArrayOf(0x57.toByte(), 0x0D.toByte())
thread {
val request = connection.bulkTransfer(endpointWriteOut, bytes, bytes.size, 0)
Log.d(TAG, "Was request to write successful? $request")
val buffer = ByteArray(16)
val response = connection.bulkTransfer(endpointReadIn, buffer, buffer.size, 0)
Log.d(TAG, "Was response from read successful? $response")
val responseString = StringBuilder()
for (i in 0..15) {
responseString.append(buffer[i])
}
Log.d(TAG, "Response: $responseString")
val hex = toHexString(buffer)
Log.d(TAG, "Hex: $hex")
connection.close()
}
fun fromHexString(hexString: String): ByteArray {
val len = hexString.length / 2
val bytes = ByteArray(len)
for (i in 0 until len) bytes[i] = hexString.substring(2 * i, 2 * i + 2).toInt(16).toByte()
return bytes
}
输出:
Was request to write successful? 2
Was response from read successful? 2
Response: 19600000000000000
Hex: 01 60 00 00 00 00 00 00 00 00 00 00 00 00 00 00