如何使用Python / PyWinUSB向设备发送HID数据?

3
我将使用pywinusb向pic18f4550发送输出报告。该设备可以接收数据,并且我已经用C#应用程序进行了测试,工作良好。此外,我可以很好地使用pywinusb从设备中读取数据,但是当我尝试发送数据时遇到了问题。
以下是我正在运行的代码:
from pywinusb import hid

filter = hid.HidDeviceFilter(vendor_id = 0x0777, product_id = 0x0077)
devices = filter.get_devices()

if devices:
    device = devices[0]
    print "success"

device.open()
out_report = device.find_output_reports()[0]

buffer= [0x00]*65
buffer[0]=0x0
buffer[1]=0x01
buffer[2]=0x00
buffer[3]=0x01

out_report.set_raw_data(buffer)
out_report.send()
dev.close()

它会产生以下错误:
success
Traceback (most recent call last):
  File "C:\Users\7User\Desktop\USB PIC18\out.py", line 24, in <module>
    out_report.send()
  File "build\bdist.win32\egg\pywinusb\hid\core.py", line 1451, in send
    self.__prepare_raw_data()
  File "build\bdist.win32\egg\pywinusb\hid\core.py", line 1406, in __prepare_raw_data
    byref(self.__raw_data), self.__raw_report_size) )
  File "build\bdist.win32\egg\pywinusb\hid\winapi.py", line 382, in __init__
    raise helpers.HIDError("hidP error: %s" % self.error_message_dict[error_code])
HIDError: hidP error: data index not found
2个回答

7

这是我的代码,它可以与运行TI的datapipe USB stack的MSP430F芯片配合使用。基本上,它是作为自定义数据管道的hid输入和输出端点,允许我以任何格式发送64字节的数据,除了第一个字节是由TI定义的ID号(十进制63),第二个字节是数据包中相关或有用字节数(最大64字节的数据包),并且前两个字节如上所述。由于缺乏文档,我花了很长时间才弄清楚这一点。pywinusb提供的少量示例最多只能算是难以学习。总之,这是我的代码。它可以在我的微控制器上正常工作,希望能对你有所帮助。

        filter = hid.HidDeviceFilter(vendor_id = 0x2048, product_id = 0x0302)
    hid_device = filter.get_devices()
    device = hid_device[0]
    device.open()
    print(hid_device)


    target_usage = hid.get_full_usage_id(0x00, 0x3f)
    device.set_raw_data_handler(sample_handler)
    print(target_usage)


    report = device.find_output_reports()

    print(report)
    print(report[0])

    buffer = [0xFF]*64
    buffer[0] = 63

    print(buffer)

    report[0].set_raw_data(buffer)
    report[0].send()

可能会让你出错的一个地方在这里:
out_report = device.find_output_reports()[0]

尝试使用“out_report = device.find_output_reports()”而不是末尾的“[0]”。 然后使用


out_report[0].set_raw_data(buffer)

最后。
out_report[0].send()

希望这能帮助你。

如果device.find_output_reports()从未找到任何输出报告,我该如何发送输出报告?对于我来说,它总是返回[] - Gabriel Staples
我的缓冲区必须有65个字节的长度...第一个字节等于报告ID,在我的情况下为0.... - karelv
有什么办法可以从输入报告中读取数据吗? 我想要一个阻塞式命令,而不是使用set_raw_data_handler方法。 - karelv

0
HID非常强大,但是没有人使用适当的HID枚举,HID提供了一种非常灵活(尽管不易)的模式来描述其报告的格式。
对于简单的设备,我建议使用简单的字节数组用法开始,这将为主机应用程序提供数据项的上下文。
无论如何,现在我们来看看原始报告...
对于任何给定的输出报告,请使用starting_data = output_report.get_raw_data()[:],然后直接更改任何“原始”元素。
当然,理想情况下,您会有正确定义的用途,并且您将能够独立地更改报告项,而不必猜测位宽和位置 :-)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接