HIDAPI.read函数无法读取USB设备返回数据的问题求助
HID设备发送数据成功但无法读取返回数据的排查与解决
我正在开发一款向HID设备发送n字节数据并读取返回数据的程序,使用十六进制列表(例如
[0x00,0x01,0x02...0x0n])作为收发数据。目前数据已成功发送,但调用HIDAPI的read函数时无法读取到返回数据,无任何接收数据输出。以下是我的代码:
import hid import time try: print("Opening the device") h = hid.device() h.open(0x1234, 0x5678) # TREZOR VendorID/ProductID print("Manufacturer: %s" % h.get_manufacturer_string()) print("Product: %s" % h.get_product_string()) print("Serial No: %s" % h.get_serial_number_string()) # enable non-blocking mode h.set_nonblocking(1) # write some data to the device print("Write the data") h.write([0x00]*64) print("Data written successfully") # wait time.sleep(0.05) # read back the answer print("Read the data") while True: d = h.read(64) if d: print(d) else: break print("Closing the device") h.close() except IOError as ex: print(ex) print("You probably don't have the hard-coded device.") print("Update the h.open() line in this script with the one") print("from the enumeration list output above and try again.") print("Done")
排查与解决建议
调整非阻塞模式设置
当前设置的非阻塞模式会让read函数立即返回,哪怕设备还没准备好响应。0.05秒的延迟可能不足以让设备返回数据,建议先改为阻塞模式测试:h.set_nonblocking(0) # 切换为阻塞模式,read会等待直到有数据返回确认HID指令格式正确性
你发送的[0x00]*64是空数据帧,很多HID设备需要特定的报告ID或指令才能触发响应。请查阅设备的HID协议文档,替换为符合要求的指令,比如:# 示例:使用报告ID 0x01 + 设备要求的指令 h.write([0x01, 0x05, 0x03] + [0x00]*61) # 补全到64字节的报告长度优化非阻塞模式下的读取逻辑
如果必须使用非阻塞模式,不要只读取一次就退出循环,增加重试时长和次数:print("Read the data") start_time = time.time() # 最多等待1秒读取数据 while time.time() - start_time < 1: d = h.read(64) if d: print(d) break time.sleep(0.01) # 短间隔重试,避免占用过多CPU验证设备是否真的返回数据
使用USB监控工具(如USBlyzer、HID Explorer)抓取USB通信包,确认设备在收到数据后是否发送了响应。如果工具中也看不到返回,问题可能出在设备本身或发送的指令不符合要求。匹配设备输入报告大小
查看设备的HID报告描述符,确认输入报告的字节数,确保read的参数和这个大小一致。比如如果设备输入报告是65字节(包含报告ID),则需要调用h.read(65)。
内容的提问来源于stack exchange,提问作者prathetic
相关产品推荐
相关产品推荐

