Permalink
Browse files

Better python 3 support.

  • Loading branch information...
1 parent 80392d3 commit 27581bf145b4311f7dea5464c88ed9ff31c3dd6e @rene-aguirre committed Apr 7, 2012
View
@@ -20,7 +20,7 @@ def test_telephony_hook():
all_devices = hid.HidDeviceFilter().get_devices()
if not all_devices:
- print "No HID class devices attached."
+ print("No HID class devices attached.")
else:
# search for our target usage (the hook button)
#target pageId, usageId
@@ -33,9 +33,9 @@ def hook_pressed(new_value, event_type):
# no need to check the value
event_type = event_type #avoid pylint warnings
if new_value:
- print "On Hook!"
+ print("On Hook!")
else:
- print "Off Hook!"
+ print("Off Hook!")
for device in all_devices:
try:
@@ -47,10 +47,10 @@ def hook_pressed(new_value, event_type):
for input_report in all_input_reports:
if usage_telephony_hook in input_report:
#found a telephony device w/ hook button
- print "\nMonitoring %s %s device.\n" \
- % (device.vendor_name, device.product_name)
- print "Press any key to exit monitoring "\
- "(or remove HID device)..."
+ print("\nMonitoring {0.vendor_name} {0.product_name} "\
+ "device.\n".format(device))
+ print("Press any key to exit monitoring " \
+ "(or remove HID device)...")
# add event handler (example of other available
# events: EVT_PRESSED, EVT_RELEASED, EVT_ALL, ...)
@@ -68,8 +68,9 @@ def hook_pressed(new_value, event_type):
return
finally:
device.close()
- print "Sorry, no one of the attached HID class devices "\
- "provide any Telephony Hook button"
+ print("Sorry, no one of the attached HID class devices "\
+ "provide any Telephony Hook button")
#
if __name__ == '__main__':
test_telephony_hook()
+
View
@@ -1,109 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: latin-1 -*-
-
-import pywinusb.hid as hid
-
-"""
-This example shows how to communicate with a GenericHID LUFA device
-(Demos\Device\ClassDriver), refer to the LUFA projects for more details:
- * http://www.fourwalledcubicle.com/LUFA.php
-
-This is the descriptor used in the device:
-
-USB_Descriptor_HIDReport_Datatype_t PROGMEM GenericReport[] =
-{
- 0x06, 0x9c, 0xff, /* Usage Page (Vendor Defined) */
- 0x09, 0x01, /* Usage (Vendor Defined) */
- 0xa1, 0x01, /* Collection (Vendor Defined) */
- 0x09, 0x02, /* Usage (Vendor Defined) */
- 0x75, 0x08, /* Report Size (8) */
- 0x95, GENERIC_REPORT_SIZE, /* Report Count (GENERIC_REPORT_SIZE) */
- 0x15, 0x80, /* Logical Minimum (-128) */
- 0x25, 0x7F, /* Logical Maximum (127) */
- 0x81, 0x02, /* Input (Data, Variable, Absolute) */
- 0x09, 0x03, /* Usage (Vendor Defined) */
- 0x75, 0x08, /* Report Size (8) */
- 0x95, GENERIC_REPORT_SIZE, /* Report Count (GENERIC_REPORT_SIZE) */
- 0x15, 0x00, /* Logical Minimum (0) */
- 0x25, 0xff, /* Logical Maximum (255) */
- 0x91, 0x02, /* Output (Data, Variable, Absolute) */
- 0xc0 /* End Collection */
-};
-
-"""
-# using latest repository values
-vendor_id = 0x03eb
-product_id = 0x204f
-
-# usage definitions
-usage_page_id = 0xff9c
-input_usage_id = 0x02
-output_usage_id = 0x03
-
-#
-input_usage = hid.get_full_usage_id(usage_page_id, input_usage_id)
-output_usage = hid.get_full_usage_id(usage_page_id, output_usage_id)
-
-def ubyte_list_to_int(data):
- """ Convert a c_ubyte array to a plain integer array
- Due performance reasons, data is received as an array of c_ubyte"""
- [x.value for x in data]
-
-def setup_monitor(device):
- def data_handler(data, event_type):
- event_type = event_type #avoid pylint warnings
- print "New Data: ", [hex(x) for x in ubyte_list_to_int(data)]
-
- # add event handler
- device.add_event_handler(target_usage,
- data_handler, hid.HID_EVT_ALL) #level usage
-
-if __name__ == '__main__':
- # search for any target device
- connected_devices = hid.HidDeviceFilter(vendor_id = vendor_id,
- product_id = product_id).get_devices()
- if connected_devices:
- print "Multiple devices found, picking anyone..."
- device = connected_devices[0]
- try:
- device.open()
-
- print "\nWhat do you want to do?"
- print " 1) Monitor data"
- print " 2) Send data"
- print " 0) Exit"
-
- response = int( raw_input().strip() )
-
- if response == 1:
- # setup input report monitor
- setup_monitor()
-
- print "\nData handler ready..., ",
- print "press any key to exit (or unplug device)"
- while not kbhit() and device.is_plugged():
- #just keep the device opened to receive events
- sleep(0.5)
- elif reponse == 2:
- report = device.find_output_reports(usage_page = usage_page_id,
- usage_id = output_usage_id)
- if report:
- print "Input (hex format) data, comma separated,",
- print "%d values:" % len(report[output_usage])
- data = [int(x, 16) for x in raw_input().strip().split(',')]
- if len(data) == len(report[output_usage]):
- # now set report and send the data
- report[output_usage] = data
- report.send()
- print "Ready!"
- else:
- print "Error, expecting %d data elements," % len(data),
- print "got %d!" % len(report[output_usage])
- else:
- print "Sorry, not able to find the output usage"
- finally:
- device.close()
- else:
- print "Target GenericHID LUFA device not found!"
- print "Verify your .VendorID and .ProductID device firmware settings"
-
View
@@ -23,7 +23,8 @@ class MyFrame(wx.Frame,hid.HidPnPWindowMixin):
my_hid_target = hid.HidDeviceFilter(vendor_id = target_vendor_id, product_id = target_product_id)
def __init__(self,parent):
- wx.Frame.__init__(self,parent,-1,"Re-plug your USB HID device, watch the command window!...")
+ wx.Frame.__init__(self,parent,-1,
+ "Re-plug your USB HID device, watch the command window!...")
hid.HidPnPWindowMixin.__init__(self, self.GetHandle())
wx.EVT_CLOSE(self, self.on_close)
self.device = None #no hid device... yet
@@ -32,10 +33,10 @@ def __init__(self,parent):
self.on_hid_pnp()
def on_hid_pnp(self, hid_event = None):
- """This function will be called on per class event changes,
- so we need to test if our device has being connected or is just gone"""
+ """This function will be called on per class event changes, so we need
+ to test if our device has being connected or is just gone"""
if hid_event:
- print "Hey, a hid device just %s!" % hid_event
+ print("Hey, a hid device just %s!" % hid_event)
if hid_event == "connected":
# test if our device is available
@@ -46,11 +47,12 @@ def on_hid_pnp(self, hid_event = None):
else:
self.test_for_connection()
elif hid_event == "disconnected":
- # the hid object is automatically closed on disconnection
- # we just test if still is plugged (important as the object might be closing)
+ # the hid object is automatically closed on disconnection we just
+ # test if still is plugged (important as the object might be
+ # closing)
if self.device and not self.device.is_plugged():
self.device = None
- print "you removed my hid device!"
+ print("you removed my hid device!")
else:
# poll for devices
self.test_for_connection()
@@ -61,41 +63,46 @@ def on_hid_pnp(self, hid_event = None):
def test_for_connection(self):
all_items = MyFrame.my_hid_target.get_devices()
if all_items:
- # at this point, what we decided to be a valid hid target is already plugged
+ # at this point, what we decided to be a valid hid target is
+ # already plugged
if len(all_items) == 1:
# this is easy, we only have a single hid device
self.device = all_items[0]
else:
# at this point you might have multiple scenarios
grouped_items = MyFrame.my_hid_target.get_devices_by_parent()
- print "%d devices now connected" % len(grouped_items)
+ print("%d devices now connected" % len(grouped_items))
if len(grouped_items) > 1:
- # 1) Really you have multiple devices connected
- # so, make your rules, how do you help your user to handle multiple devices?
- # maybe you here will find out wich is the new device, and tag this device
- # so is easily identified (i.e. the WiiMote uses LEDs), or just your GUI
- # shows some arbitrary identification for the user (device 2 connected)
+ # 1) Really you have multiple devices connected so, make
+ # your rules, how do you help your user to handle multiple
+ # devices?
+ # maybe you here will find out wich is the new device, and
+ # tag this device so is easily identified (i.e. the WiiMote
+ # uses LEDs), or just your GUI shows some arbitrary
+ # identification for the user (device 2 connected)
pass
else:
- # 2) We have a single physical device, but the descriptors might
- # might cause the OS to report is as multiple devices (collections maybe)
- # so, what would be your target device?
- # if you designed the device firmware, you already know the answer...
- # otherwise one approach might be to browse the hid usages for a particular
- # target...
- # anyway, this could be complex, especially handling multiple physical devices
- # that are reported as multiple hid paths (objects)... so...
- # I recommend you creating a proxy class that is able to handle all your
- # 'per parent id' grouped devices, (like a single .open() able to handle
- # your buch of HidDevice() items
+ # 2) We have a single physical device, but the descriptors
+ # might might cause the OS to report is as multiple devices
+ # (collections maybe) so, what would be your target device?
+ # if you designed the device firmware, you already know the
+ # answer... otherwise one approach might be to browse the
+ # hid usages for a particular target... anyway, this could
+ # be complex, especially handling multiple physical devices
+ # that are reported as multiple hid paths (objects)...
+ # so... I recommend you creating a proxy class that is
+ # able to handle all your 'per parent id' grouped devices,
+ # (like a single .open() able to handle your buch of
+ # HidDevice() items
pass
- # but... we just arbitrarly select the first hid object path (how creative!)
+ # but... we just arbitrarly select the first hid object path
+ # (how creative!)
self.device = all_items[0]
if self.device:
self.device.open()
- print "got my device: %s!" % repr(self.device)
+ print("got my device: %s!" % repr(self.device))
else:
- print "saddly my device is not here... yet :-( "
+ print("saddly my device is not here... yet :-( ")
def on_close(self, event):
event.Skip()
@@ -107,3 +114,4 @@ def on_close(self, event):
frame = MyFrame(None)
frame.Show()
app.MainLoop()
+
View
@@ -11,26 +11,26 @@
import pywinusb.hid as hid
def sample_handler(data):
- print "Raw data: ", data
+ print("Raw data: {0}".format(data))
def raw_test():
# simple test
- # first be kind with local encodings
- import codecs, sys
- sys.stdout = codecs.getwriter('mbcs')(sys.stdout)
# browse devices...
all_hids = hid.find_all_hid_devices()
if all_hids:
while True:
- print "Choose a device to monitor raw input reports:\n"
- print "0 => Exit"
- for index, dev in enumerate(all_hids):
- device_name = unicode("%s %s (vID=%04x, pID=%04x)" % \
- (dev.vendor_name, dev.product_name, dev.vendor_id, dev.product_id))
- print index+1, '=>', device_name
- print "\n\tDevice ('0' to '%d', '0' to exit?) [press enter after number]:" % len(all_hids),
+ print("Choose a device to monitor raw input reports:\n")
+ print("0 => Exit")
+ for index, device in enumerate(all_hids):
+ device_name = unicode("{0.vendor_name} {0.product_name}" \
+ "(vID=0x{1:04x}, pID=0x{2:04x})"\
+ "".format(device, device.vendor_id, device.product_id))
+ print("{0} => {1}".format(index+1, device_name))
+ print("\n\tDevice ('0' to '%d', '0' to exit?) " \
+ "[press enter after number]:" % len(all_hids))
index_option = raw_input()
if index_option.isdigit() and int(index_option) <= len(all_hids):
+ # invalid
break;
int_option = int(index_option)
if int_option:
@@ -41,16 +41,26 @@ def raw_test():
#set custom raw data handler
device.set_raw_data_handler(sample_handler)
- print "\nWaiting for data...\nPress any (system keyboard) key to stop..."
+ 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
sleep(0.5)
return
finally:
device.close()
else:
- print "There's not any non system HID class device available"
+ print("There's not any non system HID class device available")
#
if __name__ == '__main__':
+ # first be kind with local encodings
+ import sys
+ if sys.version_info >= (3,):
+ # as is, don't handle unicodes
+ unicode = str
+ raw_input = input
+ else:
+ # allow to show encoded strings
+ import codecs
+ sys.stdout = codecs.getwriter('mbcs')(sys.stdout)
raw_test()
@@ -12,7 +12,7 @@ def read_values(target_usage):
all_devices = hid.HidDeviceFilter().get_devices()
if not all_devices:
- print "Can't find any non system HID device connected"
+ print("Can't find any non system HID device connected")
else:
# search for our target usage
usage_found = False
@@ -25,13 +25,13 @@ def read_values(target_usage):
# we found our usage
report.get()
# print result
- print "The value:", list(report[target_usage])
- print "All the report:", report.get_raw_data()
+ print("The value:", list(report[target_usage]))
+ print("All the report: {0}".format(report.get_raw_data()))
usage_found = True
finally:
device.close()
if not usage_found:
- print "The target device was found, but the requested usage does not exist!\n"
+ print("The target device was found, but the requested usage does not exist!\n")
#
if __name__ == '__main__':
target_usage = hid.get_full_usage_id(0xff00, 0x02) # generic vendor page, usage_id = 2
View
@@ -13,7 +13,7 @@ def click_signal(target_usage, target_vendor_id):
all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()
if not all_devices:
- print "Can't find target device (vendor_id = 0x%04x)!" % target_vendor_id
+ print("Can't find target device (vendor_id = 0x%04x)!" % target_vendor_id)
else:
# search for our target usage
# target pageId, usageId
@@ -33,11 +33,11 @@ def click_signal(target_usage, target_vendor_id):
# now toggle back the signal
report[target_usage] = 0
report.send()
- print "\nUsage clicked!\n"
+ print("\nUsage clicked!\n")
return
finally:
device.close()
- print "The target device was found, but the requested usage does not exist!\n"
+ print("The target device was found, but the requested usage does not exist!\n")
#
if __name__ == '__main__':
target_vendor_id = 0x1234 # just an example, change it to the actual vendor_id
Oops, something went wrong.

0 comments on commit 27581bf

Please sign in to comment.