Add Python test script using pywinusb for the Class Driver Generic HID Device demo...
[pub/USBasp.git] / Demos / Device / ClassDriver / GenericHID / HostTestApp / test_generic_hid.py
1 """
2 LUFA Library
3 Copyright (C) Dean Camera, 2013.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 """
8
9 """
10 LUFA Generic HID device demo host test script. This script will send a
11 continuous stream of generic reports to the device, to show a variable LED
12 pattern on the target board. Send and received report data is printed to
13 the terminal.
14
15 Requires the pywinusb library (https://pypi.python.org/pypi/pywinusb/).
16 """
17
18 import sys
19 from time import sleep
20 import pywinusb.hid as hid
21
22
23 def get_hid_device_handle(VID, PID):
24 hid_device_filter = hid.HidDeviceFilter(vendor_id = VID, product_id = PID)
25 valid_hid_devices = hid_device_filter.get_devices()
26
27 if len(valid_hid_devices) is 0:
28 return None
29 else:
30 return valid_hid_devices[0]
31
32
33 def send_led_pattern(device, led1, led2, led3, led4):
34 # Length of the report: one byte for the report ID, remainder is the
35 # payload length as set in the demo
36 generic_report_size = 1 + 8
37
38 # Report data for the demo is the report ID (always zero) followed by the
39 # LED on/off data
40 report_data = [0, led1, led2, led3, led4]
41
42 # Zero-extend the array to the length the report should be
43 report_data.extend([0] * (generic_report_size - len(report_data)))
44
45 # Send the generated report to the device
46 device.send_output_report(report_data)
47
48 print("Sent LED Pattern: {0}".format(report_data[1:5]))
49
50
51 def received_led_pattern(report_data):
52 print("Received LED Pattern: {0}".format(report_data[1:5]))
53
54
55 def main():
56 hid_device = get_hid_device_handle(VID=0x03EB, PID=0x204F)
57
58 if hid_device is None:
59 print("No valid HID device found.")
60 sys.exit(1)
61
62 try:
63 hid_device.open()
64
65 print("Connected to device 0x%04X/0x%04X - %s [%s]" %
66 (hid_device.vendor_id, hid_device.product_id,
67 hid_device.product_name, hid_device.vendor_name))
68
69 # Set up the HID input report handler to receive reports
70 hid_device.set_raw_data_handler(received_led_pattern)
71
72 p = 0
73 while (hid_device.is_plugged()):
74 # Convert the current pattern index to a bit-mask and send
75 send_led_pattern(hid_device,
76 (p >> 3) & 1,
77 (p >> 2) & 1,
78 (p >> 1) & 1,
79 (p >> 0) & 1)
80
81 # Compute next LED pattern in sequence
82 p = (p + 1) % 16
83
84 # Delay a bit for visual effect
85 sleep(.2)
86
87 finally:
88 hid_device.close()
89
90
91 if __name__ == '__main__':
92 main()