Simple reading/writing from/to a USB HID device in Python?

Will picture Will · Oct 9, 2012 · Viewed 25k times · Source

I've got a fairly simple USB HID device that I've been trying to figure out how to read from and write to using Python. I've been able to read from it using PyWinUSB, but the problem comes in when I try to write to it. Trying to write to it makes things explode.

For example:

device = hid.HidDeviceFilter(vendor_id = 0x0003, product_id = 0x1001).get_devices()[0]

This works fine. Then for reading raw data, which is all that I care about right now (I'll work with that once I can figure out how to write to the cursed thing):

def readData(data):
    print(data)
    return None

This works fine (in fact, it was quite exciting when I got to see it work). So I would assign the data handler like so:

device.set_raw_data_handler(readData)

And every time I hit a button, it's fine. The data comes through as you would expect. Which is great!

The problem comes when I want to write to the device. Following the sample simple_send file as a template (which was probably not the best choice), I would do the following:

report = device.find_output_reports()[0]

Which would return a report object with a dictionary holding 4 entries. Is that correct? Do you write to a device using the output_reports object? Trying to do so by setting the report value to ANYTHING:

report[<key>] = "pneumonoultramicroscopicvolcanoconiosis"
report.send()

This would keep returning some obnoxious error that I can't interpret:

    Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    report.send()
  File "C:\Python27\lib\site-packages\pywinusb-0.3.1-py2.7.egg\pywinusb\hid\core.py", line 1446, in send
    self.__prepare_raw_data()
  File "C:\Python27\lib\site-packages\pywinusb-0.3.1-py2.7.egg\pywinusb\hid\core.py", line 1401, in __prepare_raw_data
    byref(self.__raw_data), self.__raw_report_size) )
  File "C:\Python27\lib\site-packages\pywinusb-0.3.1-py2.7.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

I'm using Windows 7. I've managed to find (finally) a reference for the HID DLL exported functions, and I don't HAVE to (or, for that matter even really WANT to) use the PyWinUSB library. I just want to make this work, and it didn't seem like it would be that tough, but it has been.

Can someone tell me what it is I've been doing wrong here?

Thanks.

Also, I tried tracing the error call, and made it so far before the program just closed which was kind of disheartening.

Answer

Totoxa picture Totoxa · Jan 21, 2013

i made it work with this

    buffer= [0xFF]*33 # 33 = report size + 1 byte (report id)
    buffer[0]=0x0 # report id
    buffer[1]=0xFE
    buffer[2]=0x00
    buffer[3]=0xFF
    out_report.set_raw_data(buffer)
    out_report.send()
    dev.close()