.NET MAUI Android与USB RFID设备双向通信配置及调试问题
.NET MAUI Android 连接ELTE GPS RFID阅读器问题解决
关于响应监听的选择
直接用批量传输端点读取即可,BroadcastReceiver主要用于监听系统的USB设备插拔事件,不是读取设备返回数据的常规方式。发送命令后,从对应IN端点等待读取响应是这类USB设备的标准操作逻辑。
BulkTransfer发送失败的排查步骤
确认端点方向与类型
遍历设备的接口和端点,确保发送命令用的是OUT方向的批量传输端点,读取响应用IN方向的批量传输端点。代码示例:UsbInterface usbInterface = device.GetInterface(0); // 替换为厂商指定的接口索引 UsbEndpoint outEndpoint = null; UsbEndpoint inEndpoint = null; for (int i = 0; i < usbInterface.EndpointCount; i++) { var endpoint = usbInterface.GetEndpoint(i); if (endpoint.Type == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (endpoint.Direction == UsbConstants.USB_DIR_OUT) outEndpoint = endpoint; else inEndpoint = endpoint; } }端点方向搞反是这类问题最常见的诱因。
核对命令字节的准确性
必须严格按照厂商要求生成36字节的命令数组,包括起始标识、校验位等关键内容。可以打印字节数组的十六进制值核对:string commandHex = BitConverter.ToString(commandBytes).Replace("-", " "); Console.WriteLine($"Command: {commandHex}");确保和厂商提供的示例命令完全一致。
调整超时时间
默认超时时间可能过短,导致传输未完成就判定失败。调用BulkTransfer时手动设置超时(比如3000毫秒):int sentBytes = deviceConnection.BulkTransfer(outEndpoint, commandBytes, commandBytes.Length, 3000); if (sentBytes != commandBytes.Length) { Console.WriteLine($"发送失败,仅发送{sentBytes}字节"); }返回值为实际发送的字节数,返回-1表示传输失败。
确认接口权限与配置
除了动态申请USB权限,还要在Platforms/Android/AndroidManifest.xml中添加必要的权限和特性:<uses-feature android:name="android.hardware.usb.host" /> <uses-permission android:name="android.permission.USB_PERMISSION" />连接设备后需确保正确打开接口:
if (!deviceConnection.ClaimInterface(usbInterface, true)) { // 处理接口权限获取失败的逻辑 }
读取响应的示例流程
发送命令成功后,直接从IN端点读取36字节的响应:
byte[] responseBuffer = new byte[36]; int readBytes = deviceConnection.BulkTransfer(inEndpoint, responseBuffer, responseBuffer.Length, 3000); if (readBytes == 36) { // 根据厂商协议解析响应中的标签信息 string responseHex = BitConverter.ToString(responseBuffer).Replace("-", " "); Console.WriteLine($"响应数据: {responseHex}"); } else { Console.WriteLine($"读取失败,仅接收{readBytes}字节"); }
内容的提问来源于stack exchange,提问作者Štěpán Obrátil
相关产品推荐
相关产品推荐

