Giter Club home page Giter Club logo

pywinusb's Introduction

Installing and Using pywinusb.hid

Table of Contents

Introduction

This project aims to be a simple USB/HID user application space (hence no system drivers needed) 100% python package (without C extensions). Initially targeting simple HID devices management.

The vision for this project is to be something similar to PySerial or PyParallel but for USB/HID hardware enthusiasts.

Advantages

  • All python code, using ctypes
  • Top level handling of HID events (usage events calling hook function handlers)

Current limitations

Depending on your application you might find these limitations

  • Windows only (so far...)
  • Maybe speed. I've had feedback by some users that speed is not a problem for high data throughput, but I think you might hit some Python limits if you are require any real time processing.

Installation Instructions

Windows

The most convenient way of installing is using easy_install or pip (see below for pip install commands in Windows). I recommend you do this once you are familiar with the library as you might otherwise loose track of the example source files. However, you can always come back and take a look at the examples or the source browsing the github repository here.

pip install commands:
For Python 2: pip install pywinusb, or py -2 -m pip install pywinusb
For Python 3: py -3 -m pip install pywinusb
(More on pip installation instructions here: https://docs.python.org/3/installing/)

If using a source package (.zip) from PyPi, un-zip your file (or get the source

from the main repository) and run the familiar setup.py install command from the command line, as this is sufficient. Note that setuptools or distribute (for python 3) are required.

Other

So far only Windows OS it's supported.

Using pywinusb.hid

View the ./examples directory for some (ok, few right now) scripts. These show, for instance, how to use pywinusb.hid to handle events from HID class devices usages events.

Latest code and some Wiki information can be found on the main project code page.

Utilities

More on this later...

  • The module pywinusb.hid.tools contains a function to check HID class devices capabilities, for now it provides a basic human readable text report (see the hid.core package, run it as main while HID class devices are connected to your system)

Feedback and Contributing

Feel free to contact me! use the main code project page, just tell what do you think about the project or bring me anything you think might be cool to consider.

Any participation it's appreciated, feel free to contribute more examples or applications or just a reference to your open source project that uses the library.

pywinusb's People

Contributors

c1728p9 avatar electricrcaircraftguy avatar j3hyde avatar rene-aguirre avatar vernie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pywinusb's Issues

hid.core.show_hids() fails under Python 2 if there is a Unicode character in the device name

Under Python 2, this

    if all_hids:
        print("Found HID class devices!, writting details...")
        for dev in all_hids:
            device_name = str(dev)

fails because str() attempts to do an implicit ascii conversion and fails. So even though the calls to output.write() will work correctly if there is non-ascii encoding in the data they report, the code never gets to the point of calling them if there is non-ascii encoding in the device name.

In my case the device name in question is Natural® Ergonomic Keyboard 4000.

This is only an issue under Python 2. The corresponding str() call in Python 3 does the right thing.

no dev found

Hi,

i have WIN10 64bit and this shows the devmanager:

HID\VID_040B&PID_6533&REV_0100
HID\VID_040B&PID_6533
HID\VID_040B&UP:0001_U:0005
HID_DEVICE_SYSTEM_GAME
HID_DEVICE_UP:0001_U:0005
HID_DEVICE

but if i use pywinusb 0.4.1 (python3.3) it found no device.
Is it problem with WIN10?

My code:

import pywinusb.hid as hid

filter = hid.HidDeviceFilter()
all_devices = filter.get_devices()

if all_devices:
print("Found %d matching hid devices" % len(all_devices))

More Info Dev:

=========================== USB Port1 ===========================

Connection Status : 0x01 (Device is connected)
Port Chain : 1-1-1
Properties : 0x01
IsUserConnectable : yes
PortIsDebugCapable : no
PortHasMultiCompanions : no

  ======================== USB Device ========================

    +++++++++++++++++ Device Information ++++++++++++++++++

Device Description : USB-Eingabegerät
Device Path : ?\usb#vid_040b&pid_6533#6&24bfad55&0&1#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
Device ID : USB\VID_040B&PID_6533\6&24BFAD55&0&1
Driver KeyName : {745a17a0-74d3-11d0-b6fe-00a0c90f57da}\0007 (GUID_DEVCLASS_HIDCLASS)
Driver : C:\WINDOWS\System32\drivers\hidusb.sys (Version: 10.0.10586.0 Date: 2015-10-30)
Driver Inf : C:\WINDOWS\inf\input.inf
Legacy BusType : PNPBus
Class : HIDClass
Service : HidUsb
Enumerator : USB
Location Info : Port_#0001.Hub_#0003
Location IDs : PCIROOT(0)#PCI(1A00)#USBROOT(0)#USB(1)#USB(1), ACPI(SB)#ACPI(PCI0)#ACPI(EHC2)#ACPI(URTH)#ACPI(URMH)#ACPI(PRT8)
Container ID : {36d9925a-0a46-11e6-98dd-f0def1de8935}
Manufacturer Info : (Standardsystemgeräte)
Capabilities : 0x84 (Removable, SurpriseRemovalOK)
Problem Code : 0
Power State : D3 (supported: D0, D1, D2, D3, wake from D0, wake from D1, wake from D2)
Child Device 1 : HID-konformer Gamecontroller
Device ID : HID\VID_040B&PID_6533\7&1F774CD4&0&0000
Class : HIDClass

    ---------------- Connection Information ---------------

Connection Index : 0x01 (1)
Connection Status : 0x01 (DeviceConnected)
Current Config Value : 0x01
Device Address : 0x02 (2)
Is Hub : 0x00 (no)
Number Of Open Pipes : 0x01 (1)
Device Bus Speed : 0x00 (Low-Speed)
Pipe0ScheduleOffset : 0x00 (0)

    --------------- Connection Information V2 -------------

Connection Index : 0x01 (1)
Length : 0x10 (16 bytes)
SupportedUsbProtocols : 0x03
Usb110 : 1 (yes)
Usb200 : 1 (yes)
Usb300 : 0 (no)
ReservedMBZ : 0x00
Flags : 0x00
DevIsOpAtSsOrHigher : 0 (Is not operating at SuperSpeed or higher)
DevIsSsCapOrHigher : 0 (Is not SuperSpeed capable or higher)
DevIsOpAtSsPlusOrHigher : 0 (Is not operating at SuperSpeedPlus or higher)
DevIsSsPlusCapOrHigher : 0 (Is not SuperSpeedPlus capable or higher)
ReservedMBZ : 0x00

    ------------------ Device Descriptor ------------------

bLength : 0x12 (18 bytes)
bDescriptorType : 0x01 (Device Descriptor)
bcdUSB : 0x110 (USB Version 1.10)
bDeviceClass : 0x00 (defined by the interface descriptors)
bDeviceSubClass : 0x00
bDeviceProtocol : 0x00
bMaxPacketSize0 : 0x08 (8 bytes)
idVendor : 0x040B (Weltrend Semiconductor)
idProduct : 0x6533
bcdDevice : 0x0100
iManufacturer : 0x01 (String Descriptor 1)
_!_ERROR String descriptor 1 not found
iProduct : 0x02 (String Descriptor 2)
_!_ERROR String descriptor 2 not found
iSerialNumber : 0x00 (No String Descriptor)
bNumConfigurations : 0x01

  ---------------- Configuration Descriptor -----------------

bLength : 0x09 (9 bytes)
bDescriptorType : 0x02 (Configuration Descriptor)
wTotalLength : 0x0022 (34 bytes)
bNumInterfaces : 0x01
bConfigurationValue : 0x01
iConfiguration : 0x00 (No String Descriptor)
bmAttributes : 0xA0
D7: Reserved, set 1 : 0x01
D6: Self Powered : 0x00 (no)
D5: Remote Wakeup : 0x01 (yes)
D4..0: Reserved, set 0 : 0x00
MaxPower : 0x32 (100 mA)

    ---------------- Interface Descriptor -----------------

bLength : 0x09 (9 bytes)
bDescriptorType : 0x04 (Interface Descriptor)
bInterfaceNumber : 0x00
bAlternateSetting : 0x00
bNumEndpoints : 0x01 (1 Endpoint)
bInterfaceClass : 0x03 (HID - Human Interface Device)
bInterfaceSubClass : 0x00 (None)
bInterfaceProtocol : 0x00 (None)
iInterface : 0x00 (No String Descriptor)

    ------------------- HID Descriptor --------------------

bLength : 0x09 (9 bytes)
bDescriptorType : 0x21 (HID Descriptor)
bcdHID : 0x0100 (HID Version 1.00)
bCountryCode : 0x00 (00 = not localized)
bNumDescriptors : 0x01
Descriptor 1:
bDescriptorType : 0x22 (Class=Report)
wDescriptorLength : 0x0033 (51 bytes)
Error reading descriptor : ERROR_GEN_FAILURE

    ----------------- Endpoint Descriptor -----------------

bLength : 0x07 (7 bytes)
bDescriptorType : 0x05 (Endpoint Descriptor)
bEndpointAddress : 0x81 (Direction=IN EndpointID=1)
bmAttributes : 0x03 (TransferType=Interrupt)
wMaxPacketSize : 0x0008
bInterval : 0x0A (10 ms)

Solved issue of pywinusb Input threads not closing or terminating.

I have had issues in the past of threads not closing
properly. When you set up a raw data handler, pywinusb
creates two threads:

InputReportProcessing
InputReportReader

and in theory, if you script everything correctly, and all your functions
get returned, and you do the proper cleanup, that these threads will (should)
close on their own.

However, i have had instances where this did not take place. I have seen
on stackoverflow there are many people who try to terminate/abort threads,
and because of the locks, it just doesn't seem to be effective.

threading._after_fork()

I discovered this function, that... doesn't seem to be documented, but... the nearest
i can tell, it calls an additional function that is designed to "reset all locks" for python.
This function seems to work wonderfully, and is a good way of freeing up our threads.

I'm not sure if it is something that could be incorporated into the project, because...
you would hate to close all threads or locks that should be in place.... but, maybe it
could still be incorporated... or at very least documented as a last resort option.

Here is code also, to list the threads (for troubleshooting).

for t in threading.enumerate():
    print(t.getName())

ImportError: cannot import name LPVOID

This error occurs running python 2.6, Windows Vista Ultimate 64bit

"ImportError: cannot import name LPVOID"

Any ideas? I can't find a solution to this anywhere.

Thanks!

Python exception in usage_pages.py when an unknown usage is encountered.

The wrong variable appears to have been used in the repr() function. The following patch fixes this.

--- pywinusb/pywinusb-0.3.2/pywinusb/hid/usage_pages.py Sun Mar 02 14:32:49 2014
+++ pywinusb/pywinusb-0.3.2_fixed_usages/pywinusb/hid/usage_pages.py    Mon Feb 17 20:40:31 2014
@@ -1075,11 +1075,11 @@
             page = self.Usages[self.page_id]
             if self.usage_id in page:
                 return "%s device, %s usage" % (str(UsagePage(self.page_id)), 
                         page[self.usage_id][0])
             else:
-                return "%s device, Unknown usage" % str(UsagePage(page))
+                return "%s device, Unknown usage" % str(UsagePage(self.page_id))
         return "Unknown Page/usage"

 if __name__ == '__main__':
     #simple testing
     PAGES = [

Once that was fixed this module worked perfectly for me. Thank you!

Chris

Fail to run simple_feature.py example

I had download the latest version (dated 2018/04/30) and tried the simple_feature.py example on Python 3.4.4 under Win7 32 bit. I got a ValueError at line 29
print("The value:", list(report[target_usage]))
This error seems was raise by core.ReportItem.getitem()

Can you confirm that it works at your site?

By the way, what is the comment (line 1059) means in core.ReportItem.init()?
# TODO: This seems not supported by Windows

Can't get it working with a CP2112 from SiLabs

I'm trying to get the CP2112 (I2C and GPIO interface chip) from SiLabs working. The HID interface is documented here: http://www.silabs.com/Support%20Documents/TechnicalDocs/AN495.pdf Here is the output of the show_hids.py example: show_hids.txt My environment is Win7(64-bit) and python 3.4.4 (32-bit).
I already got the LEDs on the board blinking, but I'm running into problems when the HidP_GetUsageValueArray function is called in getting a report:

Traceback (most recent call last):
  File "C:/work/usb_hid_test_cp2112/cp2112_test.py", line 148, in <module>
    print(cp.get_version())
  File "C:/work/usb_hid_test_cp2112/cp2112_test.py", line 114, in get_version
    val = report.get()
  File "C:\Anaconda3\lib\site-packages\pywinusb\hid\core.py", line 1522, in get
    self.set_raw_data(raw_data)
  File "C:\Anaconda3\lib\site-packages\pywinusb\hid\core.py", line 1375, in set_raw_data
    byref(self.__raw_data), len(self.__raw_data)) )
  File "C:\Anaconda3\lib\site-packages\pywinusb\hid\winapi.py", line 395, in __init__
    raise helpers.HIDError("hidP error: %s" % self.error_message_dict[error_code])
pywinusb.hid.helpers.HIDError: hidP error: not value array

The interesting thing is that it is working for report_id 0x03, but not for report_id 0x05. If I comment out the section where HidP_GetUsageValueArray is called, it works.

Here is the code I'm using:

from time import sleep
import struct
import ctypes
from ctypes import c_ubyte
import pywinusb.hid as hid

USB_VID=0x10c4
USB_PID=0xea90
USB_VENDOR="OMICRON"
USB_PRODCT="SWT1LOAD"

class CP2112(object):
        def __init__(self, usb_device):
            """Initialize a cp2112 device class.
            The pywinusb device object must exist and needs to be open
            """
            self.dev = usb_device
            self.__feature_reports = dict()
            for r in self.dev.find_feature_reports():
                self.__feature_reports[r.report_id] = r

        def set_gpio_configuration(self, direction=0x00, push_pull=0x00, special=0x00, clk_divider=0x00):
            device.send_feature_report( (c_ubyte * 5)(0x02, direction, push_pull, special, clk_divider) )

        def get_gpio(self):
            report = self.__feature_reports[0x03]
            return report.get()[1]

        def set_gpio(self, value=0, mask=0xff):
            device.send_feature_report( (c_ubyte * 3)(0x04, value, mask) )

        def get_version(self):
            report = self.__feature_reports[0x05]
            val = report.get()
            return (val[1], val[2])

if __name__ == '__main__':
    devices = hid.HidDeviceFilter(vendor_id = USB_VID, product_id = USB_PID,
                                  vendor_name=USB_VENDOR, product=USB_PRODCT).get_devices()
    device = devices[0]
    device.open()
    cp=CP2112(device)
    cp.set_gpio_configuration(0xff, 0)
    print(cp.get_gpio())
    print(cp.get_version())
    # blink leds
    for k in range(10):
        cp.set_gpio()
        cp.get_gpio()
        sleep(0.1)
        cp.set_gpio(0xff)
        cp.get_gpio()
        sleep(0.1)

Enhancing pywinusb for Windows: WinUSB

Another idea for pywinusb is to support generic USB device with WinUSB.

Common generic USB device either uses HID or custom USB class. WinUSB is the most widely use driver for custom USB device (others include libusb-win32, libusbK, cyusb, etc).

pywinusb with pyinstaller

Hi there,

I'm trying to package up my python app that uses pywinusb with pyinstaller.

I wrote a little Test.py:

import pywinusb.hid as hid

all_devices = hid.find_all_hid_devices()

if not all_devices:
    print("No devices found")

for device in all_devices:
    print(device)

This works fine and I get a print out of a list of devices like:

HID device (vID=0x04f3, pID=0x20d0, v=0x1111); ELAN; Touchscreen, Path: \\?\hid#vid_04f3&pid_20d0&col04#6&11e83ff1&0&0003#{4d1e55b2-f16f-11cf-88cb-001111000030}

When I then try to package it up using pyinstaller, it prints out No devices found.

If I then add a debug print out line to find_all_hid_devices() in core.py

            # add device to results, if not protected
            if hid_device.vendor_id:
                results.append(hid_device)
            else:
                print("Not appended: " + str(hid_device))

I get this from the pyinstaller version:

Not appended: HID device (vID=0x0000, pID=0x0000, v=0x0000); ; , Path: \\?\hid#vid_04f3&pid_20d0&col04#6&11e83ff1&0&0003#{4d1e55b2-f16f-11cf-88cb-001111000030}

So it looks like it's finding the device paths, but somehow the vID and pID are zero. Any ideas on what could be missing from the pyinstaller package?

Using pywinusb with an HID compliant mouse

Hi.

So I have a microcontroller board that is currently enumerating as an HID compliant mouse. However, when I run the raw_data.py script, the device is not found. Should this be the case or am I perhaps doing something wrong?

Thanks

Edit: I've tried it with a number of HID mouse devices. Is the module just not compatible with mouse and keyboard devices?

Can't find any devices

I'm having the same problem.
I try to run the show_hids.py example, and I get "There's not any non system HID class device available"
When I looked in USBDeview.exe, I saw that the service my device uses is not hidUsb, but rather WinUsb, also it doesn't show in the device manager under Human Interface Device, but rather under Universal Serial Bus devices, but the device class is HID, so I don't know how should I procees from here.
Is there any way to move it so that windows will refer to it as a HID device?

Thanks alot!

Can the raw_data read a HID-compitable mouse deivce ?

I run the raw_data code, and it can recognise several devices (they are keyboard or touchpad), when I select anyone, none of them returns raw data. Is it the limitation of the pywinusb ? Or how can I get the raw data from the touchpad or similar device ? Thanks.

Stuck on Installing GRUB...

I tried seeing if any other issues like this came up, couldn't find any, sorry if this is a duplicate.

I installed with pip, ran with sudo, selected my windows iso, went with ntfs as that was hooked by default, selected my usb-stick and went apply. It ran fine until it said "Installing GRUB...", it's been like that for an hour now.

Any ideas?

EDIT: Wrong repo, sorry.

Trying to run the simple_send example results in an error.

Using Python 2.7:

I know my devices vendor_id, and I know I have found it since I can read input from it by setting the event handler to something simple like:
def handle(data):
print(data)

So I define all of that correctly (i believe), and I set the usage_report to get_full_usage_id(0x01, 0x01).
But when I make the call, it explodes with this error message and I really don't know what to do here. Is it something that I'm doing wrong?

simple_send.py: http://pastebin.com/Rb4nUU5Y
error message: http://pastebin.com/6HDz7bkV

Any input you could provide to help me along would be wonderful and greatly appreciated.

Controls delay on the screen

Hi, thanks for the good work!

I use this code to read data from a racing wheel. The problem is that the data aren't exactly real time, because there is some kind of internal delay. When for example I stop steering the wheel I can see in the screen all the values between my current position and the previous for many seconds. I want to do it exactly real time like this: http://html5gamepad.com/

Thanks!

access violation

Hi,

A came across you project in search of an solution to read out my Dymo usb scale. I'm a php developer and i'm not used to working with python so I hope i didn't make a stupid mistake.

When i run the raw data example i get following error:


D:\pywinusb\examples>python raw_data.py
Choose a device to monitor raw input reports:
0 => Exit
1 => Logitech USB Gaming Mouse(vID=0x046d, pID=0xc049)
2 => Logitech USB Gaming Mouse(vID=0x046d, pID=0xc049)
3 => DYMO M10 10 Kg Digital Postal Scale(vID=0x0922, pID=0x8006)
Device ('0' to '3', '0' to exit?) [press enter after number]:
3
Traceback (most recent call last):
File "raw_data.py", line 67, in
raw_test()
File "raw_data.py", line 39, in raw_test
device.open()
File "C:\Python33\lib\site-packages\pywinusb-0.3.2-py3.3.egg\pywinusb\hid\core
.py", line 468, in open
ptr_preparsed_data) )
OSError: exception: access violation reading 0x000007FE0036F5A0


I'm using Windows 7, I have disabled ACL. First I tried Python 2.7 which didn't work and gave me no error then I switched to 3.3 which produced the error.

thx,

Maarten

Unicode error

Error returned when trying to find a miniLAB 1008 hid interface board. Not sure where the error is, think it's in one of the modules. Any help would be much appreciated!

hid.core.show_hids()
Found HID class devices!, writting details...
Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\lib\site-packages\pywinusb-0.3.2-py2.7.egg\pywinusb\hid\core.py", line 1562, in show_hids
device_name = str(dev)
File "C:\Python27\lib\encodings\cp1252.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0409' in position 47: character maps to

HidReport() class : self.__raw_report_size set to bad value

HidReport() class initialisation starts with the following :

    def __init__(self, hid_object, report_type, report_id):
        hid_caps = hid_object.hid_caps
        if report_type == HidP_Input:
            self.__raw_report_size = hid_caps.input_report_byte_length
        elif report_type == HidP_Output:
            self.__raw_report_size = hid_caps.output_report_byte_length
        elif report_type == HidP_Feature:
            self.__raw_report_size = hid_caps.feature_report_byte_length
        else:
            raise HIDError("Unsupported report type")

self.__raw_report_size is badly set to one of :

  • hid_caps.input_report_byte_length
  • hid_caps.output_report_byte_length
  • hid_caps.feature_report_byte_length.

These values are the max size of each report type.

For example, if there are 2 Report IN, one of size 4 and one of size 8, all HidReport() of type HidP_Input will have self.__raw_report_size set to 8. This is not correct.

Freeze when closing handle from __del__ during python exit

I tried to add a __del__ method for cleanup but it freezes if python exits while the object is alive.

Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
pywinusb 0.4.2

import pywinusb.hid

class C:
  def __init__(self,h):
    self.h = h
  def __del__(self):
    print("closing")
    self.h.close()
    print("closed")

h = pywinusb.hid.HidDeviceFilter().get_devices()[0]
h.open()
c = C(h)
# del c  # works if do this before python exits

Report IN callback

I have custom made HID devices with Vendor defined Features, IN and OUT reports.
Feature Get and Set are ok.
Report OUT is ok.
However, I have not been able to set a callback for Report IN transactions.
I use set_raw_data_handler() as a workaround but it is far from a good solution.

Did I missed something ?

Runtime error

in core.py, line 215 i got an error while calling hid.HidDeviceFilter().get_devices()

File "c:\Python33\lib\site-packages\pywinusb-0.3.1-py3.3.egg\pywinusb\hid\core.py", line 215, in get_devices
for device in results.keys():
RuntimeError: dictionary changed size during iteration

    #first filter out restricted access devices
    for item in results.keys():
        if not item.is_active():
            del results[item]

i think, deleting items while iterarting is not allowed.

Inconsistency on buffer size ?

When trying to send an 8 byte buffer, I get the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:\Users\B48923\Documents\Testchip\04_Software\Client\GUI_Frames\Frame_manual.py", line 35, in send_frame
    self.model.send_frame(data,self.combobox.current())
  File "C:\Users\B48923\Documents\Testchip\04_Software\Client\Model.py", line 32, in send_frame
    self.usb_interface.send_frame(frame)
  File "C:\Users\B48923\Documents\Testchip\04_Software\Client\USB_HID_interface.py", line 49, in send_frame
    report[0].set_raw_data(buffer)
  File "C:\Python34\lib\site-packages\pywinusb\hid\core.py", line 1294, in set_raw_data
    % self.__raw_report_size )
pywinusb.hid.helpers.HIDError: Report size has to be 9 elements (bytes)

Why does the report is supposed to be 9 bytes ? I thought the standard was 8 bytes, such as indicated in ARM mbed cookbook :
https://developer.mbed.org/cookbook/USBHID-bindings-
Is there a way to change the report size ? Tried to search trough the code but couldn't find a simple way

EDIT :

I tried defining 9-bytes input and output reports microcontroller-side, and now pywinsub is requesting 10-bytes buffer data. I should have seen that coming.
What's bothering me is that the received data microcontroller-side only contains 9 bytes (the first one being the report id), so one data byte lost somewhere in the process.

buffer to send (python side):

Buffer :[0, 218, 237, 0, 0, 0, 0, 0, 0, 0]

buffer received (micro side)

218 237 0 0 0 0 0 0 0 

First byte is lost.

can you get the information of the displays I plugin?

I run your pywinusb, it can list only usb device I plugin(but just the keyboard and mouse, others like Bluetooth, cannot figure out. but i think it's already awesome. thanks for your code.), can you help me with that? thanks.

Timing of input

Hi,

First of all, congratulations for this library. It works great!

I have the following issue: I am trying to record the input from a peripheric USB device, specifically a drum kit. What I need is basically to save the temporal information, i.e. the time-stamps of the events (drum beats, I don't really need sound information). The drum kit has 6 different pads, and I got to the point where Python recognizes the input. However, I'm finding trouble to set a clock to record the timing (I' d like Python to detect when the drum is beat and save it in a csv).

My code runs as follows:

from time import sleep
from msvcrt import kbhit

import pywinusb.hid as hid

def sample_handler(data):
print("Gure data: {0}".format(data))

import sys
if sys.version_info >= (3,):
unicode = str
raw_input = input
else:
import codecs
sys.stdout = codecs.getwriter('mbcs')(sys.stdout)

all_hids = hid.find_all_hid_devices()
device = all_hids[0]
device.open()
device.set_raw_data_handler(sample_handler)

device.close()

Thank you very much!

Paula

No all devices are listed in HidDeviceFilter()

I have a DYI device with VID 16C0h. I can see it in USB-debugger, I can see it in Windows device manager and it works - I see reports coming to my PC.
I made a python script with pywinusb and it fails to include the device into devices list. I can see only my keyboards and mices and another DYI device with another VID. Total there 8 devices listed, but in reality there are only 4 devices each listed twice.

THe code is:
all_hids = hid.HidDeviceFilter().get_devices_by_parent()
for parent, hid_items in all_hids.items():
print "Hid devices having hardware (instance) parent id = %d:" % parent
for item in hid_items:
print "\t%s" % repr(item)

Win 7 x64

What else information can I provide to troubleshoot that?

Bugs

Hi,
I'm using pyhton 2.5 and I have problem to even install pywinsub.
For instance in core.py is missing "from future import with_statement". This is for python 2.5 neccessary!
Further I can't import pywinusb. PyDev says: "Unresolt import: pywinusb".
How can I solve this problem?

Thanks in advance!

filtering devices by serial number

Hello, and thanks for the great package!

I am trying to filter HID devices by serial number, using the following code:

filter = hid.HidDeviceFilter(vendor_id=0x2047, product_id=0x0965, serial_number = '123456')
devices_found = filter.get_devices()

The problem I'm facing is that the filter seems to ignore the serial_number = '123456' constraint, i.e. whatever string I put in the serial_number argument the list of devices is always the same. Is this a bug or am I missing something?

I can obviously filter the list manually, but I would have preferred to use the built-in filter...

Ability to exclusively open HID device

Currently pywinusb opens hid devices as shared. This allows multiple processes to open a handle to the same device. This is problematic for devices that need exclusive access. It would be great if there was an option to open a HID device with exclusive access rather than shared access.

No devices reported on Windows 8.1 64-bit, Python 3.4 64-bit

I previously wrote some code that ran on Windows 7 32-bit without any issues. Today I decided to run the same code on Windows 8.1 64-bit, but the device is not found. I then tried the show_hids.py example and I simply get this output even though I have several devices connected:

There's not any non system HID class device available

I tried running as admin, but still nothing.

pnp_sample.py

while running pnp_sample.py, getting following error:

Traceback (most recent call last):
  File "C:\Users\nur\workspace\dm-hw3-p\winusb.py", line 117, in <module>
    frame = MyFrame(None)
  File "C:\Users\nur\workspace\dm-hw3-p\winusb.py", line 28, in __init__
    hid.HidPnPWindowMixin.__init__(self, self.GetHandle())
  File "C:\Python27\lib\site-packages\pywinusb\hid\hid_pnp_mixin.py", line 77, in __init__
    self.__h_notify = self._register_hid_notification()
  File "C:\Python27\lib\site-packages\pywinusb\hid\hid_pnp_mixin.py", line 128, in _register_hid_notification
    notify_obj.prepare()
AttributeError: 'DevBroadcastDevInterface' object has no attribute 'prepare'

read keystrokes from keyboard

How can I reuse the code in raw_data.py to read the keystrokes from a usb keyboard.
I am lost in the codes.

        device = all_hids[int_option-1]
        try:
            device.open()

            #set custom raw data handler
            device.set_raw_data_handler(sample_handler)

            print("\nWaiting for data...\nPress any (system keyboard) key to stop...")
            while not kbhit() and device.is_plugged():
                #just keep the device opened to receive events
                # read keystrokes from keyboard here
                sleep(0.5)
            return
        finally:
            device.close()

Error getting a feature report from the device

I am facing a little bit of difficulty in obtaining feature reports from the device, I am facing this error that seems to suggest that the error is because the data passed on from the device cannot be set into a value array that is used by the library. Do you know of a way I can get around this issue?
'''
Traceback (most recent call last):
print reports[1].get_raw_data()
File "C:\APython27\lib\site-packages\pywinusb\hid\core.py", line 1425, in get_raw_data
self.prepare_raw_data()
File "C:\APython27\lib\site-packages\pywinusb\hid\core.py", line 1416, in __prepare_raw_data
len(self.__raw_data)) )
File "C:\APython27\lib\site-packages\pywinusb\hid\winapi.py", line 382, in __init

raise helpers.HIDError("hidP error: %s" % self.error_message_dict[error_code])
pywinusb.hid.helpers.HIDError: hidP error: not value array
'''

Py2Exe do not include pywinusb

I've create *.exe binary by py2exe.
But at the end of build i've got notes:

The following modules appear to be missing
['pywinusb']

And when i've run *.exe i've got error, that 'pywinusb' not find:

No module named pywinusb

But in another cases, like pyserial it works great.

Win10, amd64 : 'OverflowError'>: int too long to convert

Hi,
after a few days I give up:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
on two machines with Win10 Prof. . python installed in c\python35, not in a program dir.
pywinusb==0.4.0 installed ( says: pip freeze)
With Eclipse release 4.5.1 (on one machine) an : import pywinusb.hid as hid results in: unresolved module
Only after entering pywinusb to the 'Forced Builtins' it is found by Eclipse.
Running the example raw_data.py brings on both PC's (with and without Eclipse):

Traceback (most recent call last):
  File "C:\Python35\lib\site-packages\pywinusb\hid\core.py", line 121, in find_all_hid_devices
    for interface_data in winapi.enum_device_interfaces(h_info, guid):
  File "C:\Python35\lib\site-packages\pywinusb\hid\winapi.py", line 466, in enum_device_interfaces
    byref(dev_interface_data) ):
ctypes.ArgumentError: argument 1: <class 'OverflowError'>: int too long to convert

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Ich\Eclipse_Workspace_3.5\MagScan\raw_data.py", line 65, in <module>
    raw_test()
  File "C:\Users\Ich\Eclipse_Workspace_3.5\MagScan\raw_data.py", line 19, in raw_test
    all_hids = hid.find_all_hid_devices()
  File "C:\Python35\lib\site-packages\pywinusb\hid\core.py", line 152, in find_all_hid_devices
    results.append(hid_device)
  File "C:\Python35\lib\site-packages\pywinusb\hid\winapi.py", line 445, in __exit__
    self.close()
  File "C:\Python35\lib\site-packages\pywinusb\hid\winapi.py", line 451, in close
    setup_api.SetupDiDestroyDeviceInfoList(self.h_info)
ctypes.ArgumentError: argument 1: <class 'OverflowError'>: int too long to convert


I could not find any help/solution for this issue.
All other examples copied from the web show up with the same problem. No one submits info on 32 or 64 bit -machine he is using, because I thougt, that it could be a 64-bit-problem.
Guenter

How to determine if the device is opened!

I use the code below to get a HID device. But I don't whether the device is opened or closed.
I try to use HIDDevice.is_opened() to get the status, but it throw a error SyntaxError: invalid syntax.
What should I do to get the status of the HID device?

filter = hid.HidDeviceFilter()
all_devices = filter.get_devices()
HIDDevice = all_devices[0]

HidPnPWindowMixin not handle pnp events

when i try pnp_sample.py, script not handle any usb event (i.e. connect or disconnect).
python 3.3 x64, pywinusb 0.3.3, wxpython phoenix 3.0.1, pyqt 4.10, win 7 x64

script can find device on start but on_hid_pnp not calling after connect/disconnect devices

Win access violation on sending a report

I'm trying to send a report (through either assigning a value to usage or through setting raw data). And get violation:
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Python27\lib\lib-tk\Tkinter.py", line 1470, in call
return self.func(*args)
File "D:\Development\Python\USB_HID_Client\HID_Client.py", line 98, in led3
r.send()
File "D:\Python27\lib\site-packages\pywinusb\hid\core.py", line 1463, in send
self.__prepare_raw_data()
File "D:\Python27\lib\site-packages\pywinusb\hid\core.py", line 1418, in __prepare_raw_data
byref(self.__raw_data), self.__raw_report_size) )
WindowsError: exception: access violation reading 0xFFFFFFFF002EC590

This is the call for hid_dll.HidP_SetData():
if n_total_usages:
#some usages set
usage_len = c_ulong(n_total_usages)
HidStatus( hid_dll.HidP_SetData(self.__report_kind,
byref(data_list), byref(usage_len),
self.__hid_object.ptr_preparsed_data,
byref(self.__raw_data), self.__raw_report_size) )

I don't think I'm doing something wrong.... It's either Win 7 x64 problem or a bug.

Also, assigning values by usage is a pain. How am I supposed to know page_id and usage_id?
E.g. I have usage page "Vendor define 1". I just spent an hour reverse-finding it from finding all usages and then get_short_usage_id and get_usage_page_id. It was painful...

Error on show_hids.py

Hi Rene,
I tried to install your library, but when trying to execute the test on the object, some errors appear.
This is the output

C:\Downloads\pywinusb-0.3.3\pywinusb-0.3.3\examples>python show_hids.py
Traceback (most recent call last):
  File "show_hids.py", line 19, in <module>
    hid.core.show_hids(output = output)
  File "C:\Python27\lib\site-packages\pywinusb\hid\core.py", line 1556, in show_hids
    all_hids = find_all_hid_devices()
  File "C:\Python27\lib\site-packages\pywinusb\hid\core.py", line 121, in find_all_hid_devices
    with winapi.DeviceInterfaceSetInfo(guid) as h_info:
  File "C:\Python27\lib\site-packages\pywinusb\hid\winapi.py", line 428, in __enter__
    return self.open()
  File "C:\Python27\lib\site-packages\pywinusb\hid\winapi.py", line 439, in open
    (DIGCF.PRESENT | DIGCF.DEVICEINTERFACE) )
ctypes.ArgumentError: argument 3: <type 'exceptions.TypeError'>: wrong type

C:\Downloads\pywinusb-0.3.3\pywinusb-0.3.3\examples>

I run python 2.7.9 on a Windows 7 machine 64bits... Any idea??

cx_Freeze can't find module pywinusb

When trying to cx_Freeze an app using pywinusb 0.4.2 installed with pip, the build fails unable for find module pywinusb.
As described here, it appears that init.py is missing from the installed root package.

Manually- adding an empty init.py to Lib/site-packages/pywinusb/ solves the issue and cx_Freeze builds just fine.

sending output report

Hello I am new to HID Communication Protocols and I only had previous I2C protocol experience and I am having some difficulties with just sending simple hexadecimals patches and receiving them with fixed length of bytes (raw_data).

I want to send the fixed length of 7 bytes to the device and I am receiving an error since the parameter in the send_output_report is not correct. Ithink it may be due to the data type. It must be sent in hexadecimals values.. what should I do to solve this issue?

This is the code I've got:

filter = hid.HidDeviceFilter(vendor_id = 0x1234, product_id = 0x4321)
dev = filter.get_devices()
aqm=dev[0]
aqm.open()
buffer = [(c_ubyte(), 0xD3), (c_ubyte(),0x3D), (c_ubyte(), 0x07), (c_ubyte(),0x03), (c_ubyte(),0x00), (c_ubyte(),0xE2), (c_ubyte(),0x2E)]
print(buffer)
print(int(aqm.hid_handle))
#aqm.send_output_report(buffer)
aqm.close()

Problem on 64-bit Windows?

Ciao.

I have tried to use the lib. I have encountered a problem when I made a switch to 64-bit windows. I think that the problem is in core.py module. HidDevice property ptr_preparsed_data is initialized as c_ulong(). I have changed that to c_void_p() and I was not able to reproduce the error. Can you check that?
I think lib is great and I would like to use it, but I need it to work on 64-bit.

Best wishes, Franis Sirkovic.

pywinusb finds only first device

in different scripts, function find_all_hid_devices() return only first device.
if in debug mode step into HidDevice.init() function, then its normally adds to result. but in that case when referring to a device an error occurs:

Path: ?\hid#vid_3208&pid_4840#6&34655a94&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
Instance: HID\VID_3208&PID_4840\6&34655A94&0&0000
Port (ID): 28
Port (str):USB\VID_3208&PID_4840\00000000002
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm 4.5.1\helpers\pydev\pydevd.py", line 2357, in
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files (x86)\JetBrains\PyCharm 4.5.1\helpers\pydev\pydevd.py", line 1777, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files (x86)\JetBrains\PyCharm 4.5.1\helpers\pydev_pydev_imps_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "D:/Downloads/pywinusb-master-0.3.7/pywinusb-master/examples/show_hids.py", line 19, in
hid.core.show_hids(output = output)
File "D:\Python34\lib\site-packages\pywinusb\hid\core.py", line 1570, in show_hids
dev.open()
File "D:\Python34\lib\site-packages\pywinusb\hid\core.py", line 415, in open
raise HIDError("Failure to get HID pre parsed data")
pywinusb.hid.helpers.HIDError: Failure to get HID pre parsed data

`hid.core.show_hids()` raises UnicodeEncodeError with multibyte device name

because hid.core.HidDevice.product_name can be unicode object (by c_wchar) but hid.core.HidDevice.__repr__ doesn't care about that.

I think __repr__ should check object type, or simply ignore non-ascii characters by encode('ascii', 'replace') explicitly.

Could you consider fixing it?

pywinusb: 0.4.1
CPython: 2.7.8 (x64)
locale: ja

one of my keyboards makes unicode error

may related with #35:

Hello,
I would like to study the library, but facing problem at very first step.
Could you give any help please.
I can provide lsusb -vv result later (I am writing this from windows machine)

condition

  • Windows7 64bit
  • Python 2.7.11 32bit
  • 'FILCO' US ASCII USB keyboard

what i did

  • cloned the repo by usual git clone
  • patched examples/show_hids.py to show python2 env and detail of error
diff --git a/examples/show_hids.py b/examples/show_hids.py
index 18c932f..ff92d9c 100644
--- a/examples/show_hids.py
+++ b/examples/show_hids.py
@@ -10,6 +10,7 @@ import pywinusb.hid as hid

 if __name__ == '__main__':
     if sys.version_info < (3,):
+        print "py2"
         import codecs
         output = codecs.getwriter('mbcs')(sys.stdout)
     else:
@@ -18,5 +19,5 @@ if __name__ == '__main__':
     try:
         hid.core.show_hids(output = output)
     except UnicodeEncodeError:
+        print sys.exc_info()
         print("\nError: Can't manage encodings on terminal, try to run the script on PyScripter or IDLE")
  • run python show_hids.py

result

$ python show_hids.py
py2
Found HID class devices!, writting details...
(<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii', u'HID device (vID=0x04d9, pID=0x2011, v=0x0390); \u040
9; USB Keyboard, Path: \\\\?\\hid#vid_04d9&pid_2011&mi_01&col01#9&3766f47c&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}',
47, 48, 'ordinal not in range(128)'), <traceback object at 0x025FA418>)

what does this code do?

Hello,

This isn't really an issue with pywinusb at all - I'm just hoping you can explain something I am struggling with :)

I am trying to write some code to drive a usb device using libusb. I have found some code that someone else wrote for the device that used pywinusb:

devices = hid.HidDeviceFilter( vendor_id = 0x1294, product_id = 0x1320 ).get_devices()
if 0 != len(devices):
    device = devices[ 0 ]
    if device is None:
        print "Device not found"
        sys.exit( 1 )
    device.open()
    report = device.find_output_reports()[ 0 ]
    report[ 0xff000001 ][ 0 ] = color
    report.send()
    device.close()
    sys.exit(0)

This seems to be sending data to the first output report. I think to do this in libusb you send a usb_control_message something like

libusb_control_transfer(devh,CTRL_OUT,HID_SET_REPORT,(HID_REPORT_TYPE_OUTPUT<<8)|0x00, 0,DATA, DATA_LEN,TIMEOUT)

The problem is I don't know what to send as the DATA. The pywinusb code above has

 report[ 0xff000001 ][ 0 ] = color
 report.send()

but looking through the code I just got confused trying to figure out what this does. Can you explain what data is sent to the device by the above pywinusb code?

Thanks so much for your time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.