Update other PyWinUSB Python host scripts to use the hidapi library.
[pub/USBasp.git] / Demos / Device / ClassDriver / GenericHID / HostTestApp / test_generic_hid_libusb.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 PyUSB library (http://sourceforge.net/apps/trac/pyusb/).
18 """
19
20 import sys
21 from time import sleep
22 import usb.core
23 import usb.util
24
25
26 def get_and_init_hid_device():
27 device = usb.core.find(idVendor=0x03EB, idProduct=0x204F)
28
29 if device is None:
30 sys.exit("Could not find USB device.")
31
32 if device.is_kernel_driver_active(0):
33 try:
34 device.detach_kernel_driver(0)
35 except usb.core.USBError as exception:
36 sys.exit("Could not detatch kernel driver: %s" % str(exception))
37
38 try:
39 device.set_configuration()
40 except usb.core.USBError as exception:
41 sys.exit("Could not set configuration: %s" % str(exception))
42
43 return device
44
45
46 def send_led_pattern(device, led1, led2, led3, led4):
47 # Report data for the demo is LED on/off data
48 report_data = [led1, led2, led3, led4]
49
50 # Send the generated report to the device
51 number_of_bytes_written = device.ctrl_transfer( # Set Report control request
52 0b00100001, # bmRequestType (constant for this control request)
53 0x09, # bmRequest (constant for this control request)
54 0, # wValue (MSB is report type, LSB is report number)
55 0, # wIndex (interface number)
56 report_data # report data to be sent
57 );
58 assert number_of_bytes_written == len(report_data)
59
60 print("Sent LED Pattern: {0}".format(report_data))
61
62
63 def receive_led_pattern(hid_device):
64 endpoint = hid_device[0][(0,0)][0]
65 report_data = hid_device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
66 return list(report_data)
67
68
69 def main():
70 hid_device = get_and_init_hid_device()
71
72 print("Connected to device 0x%04X/0x%04X - %s [%s]" %
73 (hid_device.idVendor, hid_device.idProduct,
74 usb.util.get_string(hid_device, 256, hid_device.iProduct),
75 usb.util.get_string(hid_device, 256, hid_device.iManufacturer)))
76
77 p = 0
78 while (True):
79 # Convert the current pattern index to a bit-mask and send
80 send_led_pattern(hid_device,
81 (p >> 3) & 1,
82 (p >> 2) & 1,
83 (p >> 1) & 1,
84 (p >> 0) & 1)
85
86 # Receive and print the current LED pattern
87 led_pattern = receive_led_pattern(hid_device)[0:4]
88 print("Received LED Pattern: {0}".format(led_pattern))
89
90 # Compute next LED pattern in sequence
91 p = (p + 1) % 16
92
93 # Delay a bit for visual effect
94 sleep(.2)
95
96 if __name__ == '__main__':
97 main()