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