NZSmartie / PyHIDParser

A HID descriptor parser written in Python 3
MIT License
23 stars 5 forks source link
bluetooth decode encode hid parse usb

PyHIDParser

V0.0.7

A python library for interpreting a HID descriptor to provide an application with byte structures for reading and writing to without the manual labour.

Pre-Alpha

At this stage, this library is still in early development and adoption is not recommended.

Progress

Goals

Examples

More examples int the examples/ folder:

*Note: This is a working example. But it is subject to change*

import hidparser
from hidparser.UsagePages import GenericDesktop, Button

# ...

mouse_desc = array('B', [
    0x05, 0x01,  # USAGE_PAGE (Generic Desktop)
    0x09, 0x02,  # USAGE (Mouse)
    0xa1, 0x01,  # COLLECTION (Application)
    # ...
    0xc0         # END_COLLECTION
    ])

# This returns a Device object from a descriptor
mouse_from_desc = hidparser.parse(mouse)

# Alternatively, create a mouse device through API instead of parsing bytes
mouse_from_api = hidparser.Device(
    hidparser.Collection(
        usage=GenericDesktop.MOUSE,
        items=hidparser.Collection(
            usage=GenericDesktop.POINTER,
            items=[
                hidparser.Report(
                    report_type=hidparser.ReportType.INPUT,
                    usages=hidparser.UsageRange(
                        minimum=Button(1),
                        maximum=Button(3)
                    ).get_range(),
                    size=1,
                    count=3,
                    logical_range=(0, 1),
                    flags=hidparser.ReportFlags.VARIABLE
                ),
                hidparser.Report(
                    report_type=hidparser.ReportType.INPUT,
                    usages=[],
                    size=5,
                    count=1,
                    flags=hidparser.ReportFlags.CONSTANT | hidparser.ReportFlags.VARIABLE
                ),
                hidparser.Report(
                    report_type=hidparser.ReportType.INPUT,
                    usages=[
                        GenericDesktop.X,
                        GenericDesktop.Y
                    ],
                    size=8,
                    count=2,
                    logical_range=(-127, 127),
                    flags=hidparser.ReportFlags.VARIABLE | hidparser.ReportFlags.RELATIVE
                )
            ]
        )
    )
)

# Read from the physical device
data = bytes([0x00, 0x12, 0x34])
# Deserialize the data and populate the object members
mouse_from_api.deserialize(data)

# Read the x,y members from mouse after deserializing
pointer = mouse_from_api.reports[0].inputs.mouse.pointer
print("pointer: {}, {}".format(pointer.x, pointer.y))
# Example Output:
# pointer: 18, 52