[Pkg-running-devel] [openambit] 32/131: Updated to latest HIDAPI version Fixes #10

Christian Perrier bubulle at moszumanska.debian.org
Thu Jul 17 20:19:08 UTC 2014


This is an automated email from the git hooks/post-receive script.

bubulle pushed a commit to branch master
in repository openambit.

commit 0c5491f4f4654ecb85a2e6cc4d0633fda3421037
Author: Emil Ljungdahl <emil at kratern.se>
Date:   Thu Jan 9 23:15:14 2014 +0100

    Updated to latest HIDAPI version
    Fixes #10
---
 src/libambit/hid-libusb.c    | 357 ++++++++++++++++-------------
 src/libambit/hid.c           | 522 ++++++++++++++++++++++++++++++-------------
 src/libambit/hidapi/hidapi.h |  12 +-
 3 files changed, 568 insertions(+), 323 deletions(-)

diff --git a/src/libambit/hid-libusb.c b/src/libambit/hid-libusb.c
index cf3172a..6c1d247 100644
--- a/src/libambit/hid-libusb.c
+++ b/src/libambit/hid-libusb.c
@@ -8,12 +8,13 @@
  8/22/2009
  Linux Version - 6/2/2010
  Libusb Version - 8/13/2010
+ FreeBSD Version - 11/1/2011
 
  Copyright 2009, All Rights Reserved.
- 
+
  At the discretion of the user of this library,
  this software may be licensed under the terms of the
- GNU Public License v3, a BSD-Style license, or the
+ GNU General Public License v3, a BSD-Style license, or the
  original HIDAPI license as outlined in the LICENSE.txt,
  LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
  files located at the root of the source distribution.
@@ -22,7 +23,7 @@
         http://github.com/signal11/hidapi .
 ********************************************************/
 
-#define _GNU_SOURCE // needed for wcsdup() before glibc 2.10
+#define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */
 
 /* C */
 #include <stdio.h>
@@ -58,11 +59,15 @@ extern "C" {
 #define LOG(...) do {} while (0)
 #endif
 
+#ifndef __FreeBSD__
+#define DETACH_KERNEL_DRIVER
+#endif
 
 /* Uncomment to enable the retrieval of Usage and Usage Page in
-hid_enumerate(). Warning, this is very invasive as it requires the detach
+hid_enumerate(). Warning, on platforms different from FreeBSD
+this is very invasive as it requires the detach
 and re-attach of the kernel driver. See comments inside hid_enumerate().
-Linux/libusb HIDAPI programs are encouraged to use the interface number
+libusb HIDAPI programs are encouraged to use the interface number
 instead to differentiate between interfaces on a composite HID device. */
 /*#define INVASIVE_GET_USAGE*/
 
@@ -77,36 +82,37 @@ struct input_report {
 struct hid_device_ {
 	/* Handle to the actual device. */
 	libusb_device_handle *device_handle;
-	
+
 	/* Endpoint information */
 	int input_endpoint;
 	int output_endpoint;
 	int input_ep_max_packet_size;
 
-	/* The interface number of the HID */	
+	/* The interface number of the HID */
 	int interface;
-	
+
 	/* Indexes of Strings */
 	int manufacturer_index;
 	int product_index;
 	int serial_index;
-	
+
 	/* Whether blocking reads are used */
 	int blocking; /* boolean */
-	
+
 	/* Read thread objects */
 	pthread_t thread;
 	pthread_mutex_t mutex; /* Protects input_reports */
 	pthread_cond_t condition;
 	pthread_barrier_t barrier; /* Ensures correct startup sequence */
 	int shutdown_thread;
+	int cancelled;
 	struct libusb_transfer *transfer;
 
 	/* List of received input reports. */
 	struct input_report *input_reports;
 };
 
-static int initialized = 0;
+static libusb_context *usb_context = NULL;
 
 uint16_t get_usb_code_for_current_locale(void);
 static int return_data(hid_device *dev, unsigned char *data, size_t length);
@@ -114,23 +120,12 @@ static int return_data(hid_device *dev, unsigned char *data, size_t length);
 static hid_device *new_hid_device(void)
 {
 	hid_device *dev = calloc(1, sizeof(hid_device));
-	dev->device_handle = NULL;
-	dev->input_endpoint = 0;
-	dev->output_endpoint = 0;
-	dev->input_ep_max_packet_size = 0;
-	dev->interface = 0;
-	dev->manufacturer_index = 0;
-	dev->product_index = 0;
-	dev->serial_index = 0;
 	dev->blocking = 1;
-	dev->shutdown_thread = 0;
-	dev->transfer = NULL;
-	dev->input_reports = NULL;
-	
+
 	pthread_mutex_init(&dev->mutex, NULL);
 	pthread_cond_init(&dev->condition, NULL);
 	pthread_barrier_init(&dev->barrier, NULL, 2);
-	
+
 	return dev;
 }
 
@@ -146,7 +141,7 @@ static void free_hid_device(hid_device *dev)
 }
 
 #if 0
-//TODO: Implement this funciton on Linux.
+/*TODO: Implement this funciton on hidapi/libusb.. */
 static void register_error(hid_device *device, const char *op)
 {
 
@@ -187,17 +182,17 @@ static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur
 static int get_usage(uint8_t *report_descriptor, size_t size,
                      unsigned short *usage_page, unsigned short *usage)
 {
-	int i = 0;
+	unsigned int i = 0;
 	int size_code;
 	int data_len, key_size;
 	int usage_found = 0, usage_page_found = 0;
-	
+
 	while (i < size) {
 		int key = report_descriptor[i];
 		int key_cmd = key & 0xfc;
 
 		//printf("key: %02hhx\n", key);
-		
+
 		if ((key & 0xf0) == 0xf0) {
 			/* This is a Long Item. The next byte contains the
 			   length of the data section (value) for this key.
@@ -232,7 +227,7 @@ static int get_usage(uint8_t *report_descriptor, size_t size,
 			};
 			key_size = 1;
 		}
-		
+
 		if (key_cmd == 0x4) {
 			*usage_page  = get_bytes(report_descriptor, size, data_len, i);
 			usage_page_found = 1;
@@ -246,14 +241,35 @@ static int get_usage(uint8_t *report_descriptor, size_t size,
 
 		if (usage_page_found && usage_found)
 			return 0; /* success */
-		
+
 		/* Skip over this key and it's associated data */
 		i += data_len + key_size;
 	}
-	
+
 	return -1; /* failure */
 }
-#endif // INVASIVE_GET_USAGE
+#endif /* INVASIVE_GET_USAGE */
+
+#ifdef __FreeBSD__
+/* The FreeBSD version of libusb doesn't have this funciton. In mainline
+   libusb, it's inlined in libusb.h. This function will bear a striking
+   resemblence to that one, because there's about one way to code it.
+
+   Note that the data parameter is Unicode in UTF-16LE encoding.
+   Return value is the number of bytes in data, or LIBUSB_ERROR_*.
+ */
+static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
+	uint8_t descriptor_index, uint16_t lang_id,
+	unsigned char *data, int length)
+{
+	return libusb_control_transfer(dev,
+		LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */
+		LIBUSB_REQUEST_GET_DESCRIPTOR,
+		(LIBUSB_DT_STRING << 8) | descriptor_index,
+		lang_id, data, (uint16_t) length, 1000);
+}
+
+#endif
 
 
 /* Get the first language the device says it reports. This comes from
@@ -262,7 +278,7 @@ static uint16_t get_first_language(libusb_device_handle *dev)
 {
 	uint16_t buf[32];
 	int len;
-	
+
 	/* Get the string from libusb. */
 	len = libusb_get_string_descriptor(dev,
 			0x0, /* String ID */
@@ -271,8 +287,8 @@ static uint16_t get_first_language(libusb_device_handle *dev)
 			sizeof(buf));
 	if (len < 4)
 		return 0x0;
-	
-	return buf[1]; // First two bytes are len and descriptor type.
+
+	return buf[1]; /* First two bytes are len and descriptor type. */
 }
 
 static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
@@ -280,7 +296,7 @@ static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
 	uint16_t buf[32];
 	int len;
 	int i;
-	
+
 	/* Get the string from libusb. */
 	len = libusb_get_string_descriptor(dev,
 			0x0, /* String ID */
@@ -289,8 +305,8 @@ static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
 			sizeof(buf));
 	if (len < 4)
 		return 0x0;
-	
-	
+
+
 	len /= 2; /* language IDs are two-bytes each. */
 	/* Start at index 1 because there are two bytes of protocol data. */
 	for (i = 1; i < len; i++) {
@@ -317,7 +333,11 @@ static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
 	size_t inbytes;
 	size_t outbytes;
 	size_t res;
+#ifdef __FreeBSD__
+	const char *inptr;
+#else
 	char *inptr;
+#endif
 	char *outptr;
 
 	/* Determine which language to use. */
@@ -325,7 +345,7 @@ static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
 	lang = get_usb_code_for_current_locale();
 	if (!is_language_supported(dev, lang))
 		lang = get_first_language(dev);
-		
+
 	/* Get the string from libusb. */
 	len = libusb_get_string_descriptor(dev,
 			idx,
@@ -334,38 +354,40 @@ static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
 			sizeof(buf));
 	if (len < 0)
 		return NULL;
-	
-	buf[sizeof(buf)-1] = '\0';
-	
-	if (len+1 < sizeof(buf))
-		buf[len+1] = '\0';
-	
+
+	/* buf does not need to be explicitly NULL-terminated because
+	   it is only passed into iconv() which does not need it. */
+
 	/* Initialize iconv. */
-	ic = iconv_open("UTF-32", "UTF-16");
-	if (ic == (iconv_t)-1)
+	ic = iconv_open("WCHAR_T", "UTF-16LE");
+	if (ic == (iconv_t)-1) {
+		LOG("iconv_open() failed\n");
 		return NULL;
-	
-	/* Convert to UTF-32 (wchar_t on glibc systems).
+	}
+
+	/* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
 	   Skip the first character (2-bytes). */
 	inptr = buf+2;
 	inbytes = len-2;
 	outptr = (char*) wbuf;
 	outbytes = sizeof(wbuf);
 	res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
-	if (res == (size_t)-1)
+	if (res == (size_t)-1) {
+		LOG("iconv() failed\n");
 		goto err;
+	}
 
 	/* Write the terminating NULL. */
 	wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
 	if (outbytes >= sizeof(wbuf[0]))
 		*((wchar_t*)outptr) = 0x00000000;
-	
+
 	/* Allocate and copy the string. */
-	str = wcsdup(wbuf+1);
+	str = wcsdup(wbuf);
 
 err:
 	iconv_close(ic);
-	
+
 	return str;
 }
 
@@ -377,17 +399,24 @@ static char *make_path(libusb_device *dev, int interface_number)
 		libusb_get_device_address(dev),
 		interface_number);
 	str[sizeof(str)-1] = '\0';
-	
+
 	return strdup(str);
 }
 
 
 int HID_API_EXPORT hid_init(void)
 {
-	if (!initialized) {
-		if (libusb_init(NULL))
+	if (!usb_context) {
+		const char *locale;
+
+		/* Init Libusb */
+		if (libusb_init(&usb_context))
 			return -1;
-		initialized = 1;
+
+		/* Set the locale if it's not set. */
+		locale = setlocale(LC_CTYPE, NULL);
+		if (!locale)
+			setlocale(LC_CTYPE, "");
 	}
 
 	return 0;
@@ -395,9 +424,9 @@ int HID_API_EXPORT hid_init(void)
 
 int HID_API_EXPORT hid_exit(void)
 {
-	if (initialized) {
-		libusb_exit(NULL);
-		initialized = 0;
+	if (usb_context) {
+		libusb_exit(usb_context);
+		usb_context = NULL;
 	}
 
 	return 0;
@@ -410,16 +439,14 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 	libusb_device_handle *handle;
 	ssize_t num_devs;
 	int i = 0;
-	
-	struct hid_device_info *root = NULL; // return object
+
+	struct hid_device_info *root = NULL; /* return object */
 	struct hid_device_info *cur_dev = NULL;
-	
-	setlocale(LC_ALL,"");
-	
-	if (!initialized)
-		hid_init();
 
-	num_devs = libusb_get_device_list(NULL, &devs);
+	if(hid_init() < 0)
+		return NULL;
+
+	num_devs = libusb_get_device_list(usb_context, &devs);
 	if (num_devs < 0)
 		return NULL;
 	while ((dev = devs[i++]) != NULL) {
@@ -431,10 +458,6 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 		int res = libusb_get_device_descriptor(dev, &desc);
 		unsigned short dev_vid = desc.idVendor;
 		unsigned short dev_pid = desc.idProduct;
-		
-		/* HID's are defined at the interface level. */
-		if (desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE)
-			continue;
 
 		res = libusb_get_active_config_descriptor(dev, &conf_desc);
 		if (res < 0)
@@ -449,8 +472,8 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 						interface_num = intf_desc->bInterfaceNumber;
 
 						/* Check the VID/PID against the arguments */
-						if ((vendor_id == 0x0 && product_id == 0x0) ||
-						    (vendor_id == dev_vid && product_id == dev_pid)) {
+						if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
+						    (product_id == 0x0 || product_id == dev_pid)) {
 							struct hid_device_info *tmp;
 
 							/* VID/PID match. Create the record. */
@@ -462,11 +485,11 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 								root = tmp;
 							}
 							cur_dev = tmp;
-							
+
 							/* Fill out the record */
 							cur_dev->next = NULL;
 							cur_dev->path = make_path(dev, interface_num);
-							
+
 							res = libusb_open(dev, &handle);
 
 							if (res >= 0) {
@@ -484,6 +507,7 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 										get_usb_string(handle, desc.iProduct);
 
 #ifdef INVASIVE_GET_USAGE
+{
 							/*
 							This section is removed because it is too
 							invasive on the system. Getting a Usage Page
@@ -499,9 +523,9 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 							#if 0. For composite devices, use the interface
 							field in the hid_device_info struct to distinguish
 							between interfaces. */
-								int detached = 0;
 								unsigned char data[256];
-							
+#ifdef DETACH_KERNEL_DRIVER
+								int detached = 0;
 								/* Usage Page and Usage */
 								res = libusb_kernel_driver_active(handle, interface_num);
 								if (res == 1) {
@@ -511,6 +535,7 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 									else
 										detached = 1;
 								}
+#endif
 								res = libusb_claim_interface(handle, interface_num);
 								if (res >= 0) {
 									/* Get the HID Report Descriptor. */
@@ -533,14 +558,16 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 								}
 								else
 									LOG("Can't claim interface %d\n", res);
-
+#ifdef DETACH_KERNEL_DRIVER
 								/* Re-attach kernel driver if necessary. */
 								if (detached) {
 									res = libusb_attach_kernel_driver(handle, interface_num);
 									if (res < 0)
 										LOG("Couldn't re-attach kernel driver.\n");
 								}
-#endif /*******************/
+#endif
+}
+#endif /* INVASIVE_GET_USAGE */
 
 								libusb_close(handle);
 							}
@@ -550,7 +577,7 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 
 							/* Release Number */
 							cur_dev->release_number = desc.bcdDevice;
-							
+
 							/* Interface Number */
 							cur_dev->interface_number = interface_num;
 						}
@@ -580,12 +607,12 @@ void  HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
 	}
 }
 
-hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)
+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
 {
 	struct hid_device_info *devs, *cur_dev;
 	const char *path_to_open = NULL;
 	hid_device *handle = NULL;
-	
+
 	devs = hid_enumerate(vendor_id, product_id);
 	cur_dev = devs;
 	while (cur_dev) {
@@ -611,14 +638,15 @@ hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar
 	}
 
 	hid_free_enumeration(devs);
-	
+
 	return handle;
 }
 
 static void read_callback(struct libusb_transfer *transfer)
 {
 	hid_device *dev = transfer->user_data;
-	
+	int res;
+
 	if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
 
 		struct input_report *rpt = malloc(sizeof(*rpt));
@@ -644,22 +672,24 @@ static void read_callback(struct libusb_transfer *transfer)
 				num_queued++;
 			}
 			cur->next = rpt;
-			
+
 			/* Pop one off if we've reached 30 in the queue. This
 			   way we don't grow forever if the user never reads
 			   anything from the device. */
 			if (num_queued > 30) {
 				return_data(dev, NULL, 0);
-			}			
+			}
 		}
 		pthread_mutex_unlock(&dev->mutex);
 	}
 	else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
 		dev->shutdown_thread = 1;
+		dev->cancelled = 1;
 		return;
 	}
 	else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
 		dev->shutdown_thread = 1;
+		dev->cancelled = 1;
 		return;
 	}
 	else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
@@ -668,9 +698,14 @@ static void read_callback(struct libusb_transfer *transfer)
 	else {
 		LOG("Unknown transfer code: %d\n", transfer->status);
 	}
-	
+
 	/* Re-submit the transfer object. */
-	libusb_submit_transfer(transfer);
+	res = libusb_submit_transfer(transfer);
+	if (res != 0) {
+		LOG("Unable to submit URB. libusb error code: %d\n", res);
+		dev->shutdown_thread = 1;
+		dev->cancelled = 1;
+	}
 }
 
 
@@ -691,31 +726,39 @@ static void *read_thread(void *param)
 		read_callback,
 		dev,
 		5000/*timeout*/);
-	
+
 	/* Make the first submission. Further submissions are made
 	   from inside read_callback() */
 	libusb_submit_transfer(dev->transfer);
 
-	// Notify the main thread that the read thread is up and running.
+	/* Notify the main thread that the read thread is up and running. */
 	pthread_barrier_wait(&dev->barrier);
-	
+
 	/* Handle all the events. */
 	while (!dev->shutdown_thread) {
 		int res;
-		res = libusb_handle_events(NULL);
+		res = libusb_handle_events(usb_context);
 		if (res < 0) {
-			/* There was an error. Break out of this loop. */
-			break;
+			/* There was an error. */
+			LOG("read_thread(): libusb reports error # %d\n", res);
+
+			/* Break out of this loop only on fatal error.*/
+			if (res != LIBUSB_ERROR_BUSY &&
+			    res != LIBUSB_ERROR_TIMEOUT &&
+			    res != LIBUSB_ERROR_OVERFLOW &&
+			    res != LIBUSB_ERROR_INTERRUPTED) {
+				break;
+			}
 		}
 	}
-	
+
 	/* Cancel any transfer that may be pending. This call will fail
 	   if no transfers are pending, but that's OK. */
-	if (libusb_cancel_transfer(dev->transfer) == 0) {
-		/* The transfer was cancelled, so wait for its completion. */
-		libusb_handle_events(NULL);
-	}
-	
+	libusb_cancel_transfer(dev->transfer);
+
+	while (!dev->cancelled)
+		libusb_handle_events_completed(usb_context, &dev->cancelled);
+
 	/* Now that the read thread is stopping, Wake any threads which are
 	   waiting on data (in hid_read_timeout()). Do this under a mutex to
 	   make sure that a thread which is about to go to sleep waiting on
@@ -732,7 +775,7 @@ static void *read_thread(void *param)
 	   cleaned up after the call to pthread_join() (in hid_close()), but
 	   since hid_close() calls libusb_cancel_transfer(), on these objects,
 	   they can not be cleaned up here. */
-	
+
 	return NULL;
 }
 
@@ -741,21 +784,18 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 {
 	hid_device *dev = NULL;
 
-	dev = new_hid_device();
-
 	libusb_device **devs;
 	libusb_device *usb_dev;
-	ssize_t num_devs;
 	int res;
 	int d = 0;
 	int good_open = 0;
-	
-	setlocale(LC_ALL,"");
-	
-	if (!initialized)
-		hid_init();
 
-	num_devs = libusb_get_device_list(NULL, &devs);
+	if(hid_init() < 0)
+		return NULL;
+
+	dev = new_hid_device();
+
+	libusb_get_device_list(usb_context, &devs);
 	while ((usb_dev = devs[d++]) != NULL) {
 		struct libusb_device_descriptor desc;
 		struct libusb_config_descriptor *conf_desc = NULL;
@@ -774,15 +814,15 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 					if (!strcmp(dev_path, path)) {
 						/* Matched Paths. Open this device */
 
-						// OPEN HERE //
+						/* OPEN HERE */
 						res = libusb_open(usb_dev, &dev->device_handle);
 						if (res < 0) {
 							LOG("can't open device\n");
 							free(dev_path);
- 							break;
+							break;
 						}
 						good_open = 1;
-						
+#ifdef DETACH_KERNEL_DRIVER
 						/* Detach the kernel driver, but only if the
 						   device is managed by the kernel */
 						if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
@@ -795,7 +835,7 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 								break;
 							}
 						}
-						
+#endif
 						res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
 						if (res < 0) {
 							LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
@@ -812,7 +852,7 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 
 						/* Store off the interface number */
 						dev->interface = intf_desc->bInterfaceNumber;
-												
+
 						/* Find the INPUT and OUTPUT endpoints. An
 						   OUTPUT endpoint is not required. */
 						for (i = 0; i < intf_desc->bNumEndpoints; i++) {
@@ -824,10 +864,10 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 							int is_interrupt =
 								(ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
 							      == LIBUSB_TRANSFER_TYPE_INTERRUPT;
-							int is_output = 
+							int is_output =
 								(ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
 							      == LIBUSB_ENDPOINT_OUT;
-							int is_input = 
+							int is_input =
 								(ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
 							      == LIBUSB_ENDPOINT_IN;
 
@@ -844,12 +884,12 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 								dev->output_endpoint = ep->bEndpointAddress;
 							}
 						}
-						
+
 						pthread_create(&dev->thread, NULL, read_thread, dev);
-						
-						// Wait here for the read thread to be initialized.
+
+						/* Wait here for the read thread to be initialized. */
 						pthread_barrier_wait(&dev->barrier);
-						
+
 					}
 					free(dev_path);
 				}
@@ -860,13 +900,13 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 	}
 
 	libusb_free_device_list(devs, 1);
-	
-	// If we have a good handle, return it.
+
+	/* If we have a good handle, return it. */
 	if (good_open) {
 		return dev;
 	}
 	else {
-		// Unable to open any devices.
+		/* Unable to open any devices. */
 		free_hid_device(dev);
 		return NULL;
 	}
@@ -895,13 +935,13 @@ int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t
 			dev->interface,
 			(unsigned char *)data, length,
 			1000/*timeout millis*/);
-		
+
 		if (res < 0)
 			return -1;
-		
+
 		if (skipped_report_id)
 			length++;
-		
+
 		return length;
 	}
 	else {
@@ -912,13 +952,13 @@ int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t
 			(unsigned char*)data,
 			length,
 			&actual_length, 1000);
-		
+
 		if (res < 0)
 			return -1;
-		
+
 		if (skipped_report_id)
 			actual_length++;
-		
+
 		return actual_length;
 	}
 }
@@ -966,14 +1006,14 @@ int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t
 		bytes_read = return_data(dev, data, length);
 		goto ret;
 	}
-	
+
 	if (dev->shutdown_thread) {
 		/* This means the device has been disconnected.
 		   An error code of -1 should be returned. */
 		bytes_read = -1;
 		goto ret;
 	}
-	
+
 	if (milliseconds == -1) {
 		/* Blocking */
 		while (!dev->input_reports && !dev->shutdown_thread) {
@@ -994,7 +1034,7 @@ int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t
 			ts.tv_sec++;
 			ts.tv_nsec -= 1000000000L;
 		}
-		
+
 		while (!dev->input_reports && !dev->shutdown_thread) {
 			res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
 			if (res == 0) {
@@ -1002,7 +1042,7 @@ int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t
 					bytes_read = return_data(dev, data, length);
 					break;
 				}
-				
+
 				/* If we're here, there was a spurious wake up
 				   or the read thread was shutdown. Run the
 				   loop again (ie: don't break). */
@@ -1039,7 +1079,7 @@ int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
 int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
 {
 	dev->blocking = !nonblock;
-	
+
 	return 0;
 }
 
@@ -1063,14 +1103,14 @@ int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char
 		dev->interface,
 		(unsigned char *)data, length,
 		1000/*timeout millis*/);
-	
+
 	if (res < 0)
 		return -1;
-	
+
 	/* Account for the report ID */
 	if (skipped_report_id)
 		length++;
-	
+
 	return length;
 }
 
@@ -1094,13 +1134,13 @@ int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data,
 		dev->interface,
 		(unsigned char *)data, length,
 		1000/*timeout millis*/);
-	
+
 	if (res < 0)
 		return -1;
 
 	if (skipped_report_id)
 		res++;
-	
+
 	return res;
 }
 
@@ -1109,31 +1149,31 @@ void HID_API_EXPORT hid_close(hid_device *dev)
 {
 	if (!dev)
 		return;
-	
+
 	/* Cause read_thread() to stop. */
 	dev->shutdown_thread = 1;
 	libusb_cancel_transfer(dev->transfer);
 
 	/* Wait for read_thread() to end. */
 	pthread_join(dev->thread, NULL);
-	
+
 	/* Clean up the Transfer objects allocated in read_thread(). */
 	free(dev->transfer->buffer);
 	libusb_free_transfer(dev->transfer);
-	
+
 	/* release the interface */
 	libusb_release_interface(dev->device_handle, dev->interface);
-	
+
 	/* Close the handle */
 	libusb_close(dev->device_handle);
-	
+
 	/* Clear out the queue of received reports. */
 	pthread_mutex_lock(&dev->mutex);
 	while (dev->input_reports) {
 		return_data(dev, NULL, 0);
 	}
 	pthread_mutex_unlock(&dev->mutex);
-	
+
 	free_hid_device(dev);
 }
 
@@ -1316,7 +1356,7 @@ static struct lang_map_entry lang_map[] = {
 	LANG("Xhosa", "xh", 0x0434),
 	LANG("Yiddish", "yi", 0x043D),
 	LANG("Zulu", "zu", 0x0435),
-	LANG(NULL, NULL, 0x0),	
+	LANG(NULL, NULL, 0x0),
 };
 
 uint16_t get_usb_code_for_current_locale(void)
@@ -1324,16 +1364,17 @@ uint16_t get_usb_code_for_current_locale(void)
 	char *locale;
 	char search_string[64];
 	char *ptr;
-	
+	struct lang_map_entry *lang;
+
 	/* Get the current locale. */
 	locale = setlocale(0, NULL);
 	if (!locale)
 		return 0x0;
-	
+
 	/* Make a copy of the current locale string. */
 	strncpy(search_string, locale, sizeof(search_string));
 	search_string[sizeof(search_string)-1] = '\0';
-	
+
 	/* Chop off the encoding part, and make it lower case. */
 	ptr = search_string;
 	while (*ptr) {
@@ -1346,14 +1387,14 @@ uint16_t get_usb_code_for_current_locale(void)
 	}
 
 	/* Find the entry which matches the string code of our locale. */
-	struct lang_map_entry *lang = lang_map;
+	lang = lang_map;
 	while (lang->string_code) {
 		if (!strcmp(lang->string_code, search_string)) {
 			return lang->usb_code;
-		}	
+		}
 		lang++;
 	}
-	
+
 	/* There was no match. Find with just the language only. */
 	/* Chop off the variant. Chop it off at the '_'. */
 	ptr = search_string;
@@ -1365,18 +1406,18 @@ uint16_t get_usb_code_for_current_locale(void)
 		}
 		ptr++;
 	}
-	
-#if 0 // TODO: Do we need this?
+
+#if 0 /* TODO: Do we need this? */
 	/* Find the entry which matches the string code of our language. */
 	lang = lang_map;
 	while (lang->string_code) {
 		if (!strcmp(lang->string_code, search_string)) {
 			return lang->usb_code;
-		}	
+		}
 		lang++;
 	}
 #endif
-	
+
 	/* Found nothing. */
 	return 0x0;
 }
diff --git a/src/libambit/hid.c b/src/libambit/hid.c
index 5a0d41b..bb206e8 100644
--- a/src/libambit/hid.c
+++ b/src/libambit/hid.c
@@ -9,10 +9,10 @@
  Linux Version - 6/2/2009
 
  Copyright 2009, All Rights Reserved.
- 
+
  At the discretion of the user of this library,
  this software may be licensed under the terms of the
- GNU Public License v3, a BSD-Style license, or the
+ GNU General Public License v3, a BSD-Style license, or the
  original HIDAPI license as outlined in the LICENSE.txt,
  LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
  files located at the root of the source distribution.
@@ -40,6 +40,7 @@
 /* Linux */
 #include <linux/hidraw.h>
 #include <linux/version.h>
+#include <linux/input.h>
 #include <libudev.h>
 
 #include "hidapi.h"
@@ -53,6 +54,23 @@
 #define HIDIOCGFEATURE(len)    _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
 #endif
 
+
+/* USB HID device property names */
+const char *device_string_names[] = {
+	"manufacturer",
+	"product",
+	"serial",
+};
+
+/* Symbolic names for the properties above */
+enum device_string_id {
+	DEVICE_STRING_MANUFACTURER,
+	DEVICE_STRING_PRODUCT,
+	DEVICE_STRING_SERIAL,
+
+	DEVICE_STRING_COUNT,
+};
+
 struct hid_device_ {
 	int device_handle;
 	int blocking;
@@ -62,7 +80,28 @@ struct hid_device_ {
 
 static __u32 kernel_version = 0;
 
-hid_device *new_hid_device()
+static __u32 detect_kernel_version(void)
+{
+	struct utsname name;
+	int major, minor, release;
+	int ret;
+
+	uname(&name);
+	ret = sscanf(name.release, "%d.%d.%d", &major, &minor, &release);
+	if (ret == 3) {
+		return KERNEL_VERSION(major, minor, release);
+	}
+
+	ret = sscanf(name.release, "%d.%d", &major, &minor);
+	if (ret == 2) {
+		return KERNEL_VERSION(major, minor, 0);
+	}
+
+	printf("Couldn't determine kernel version from version string \"%s\"\n", name.release);
+	return 0;
+}
+
+static hid_device *new_hid_device(void)
 {
 	hid_device *dev = calloc(1, sizeof(hid_device));
 	dev->device_handle = -1;
@@ -72,36 +111,39 @@ hid_device *new_hid_device()
 	return dev;
 }
 
-static void register_error(hid_device *device, const char *op)
+
+/* The caller must free the returned string with free(). */
+static wchar_t *utf8_to_wchar_t(const char *utf8)
 {
+	wchar_t *ret = NULL;
 
+	if (utf8) {
+		size_t wlen = mbstowcs(NULL, utf8, 0);
+		if ((size_t) -1 == wlen) {
+			return wcsdup(L"");
+		}
+		ret = calloc(wlen+1, sizeof(wchar_t));
+		mbstowcs(ret, utf8, wlen+1);
+		ret[wlen] = 0x0000;
+	}
+
+	return ret;
 }
 
 /* Get an attribute value from a udev_device and return it as a whar_t
    string. The returned string must be freed with free() when done.*/
 static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name)
 {
-	const char *str;
-	wchar_t *ret = NULL;
-	str = udev_device_get_sysattr_value(dev, udev_name);
-	if (str) {
-		/* Convert the string from UTF-8 to wchar_t */
-		size_t wlen = mbstowcs(NULL, str, 0);
-		ret = calloc(wlen+1, sizeof(wchar_t));
-		mbstowcs(ret, str, wlen+1);
-		ret[wlen] = 0x0000;
-	}
-	
-	return ret;
+	return utf8_to_wchar_t(udev_device_get_sysattr_value(dev, udev_name));
 }
 
 /* uses_numbered_reports() returns 1 if report_descriptor describes a device
-   which contains numbered reports. */ 
+   which contains numbered reports. */
 static int uses_numbered_reports(__u8 *report_descriptor, __u32 size) {
-	int i = 0;
+	unsigned int i = 0;
 	int size_code;
 	int data_len, key_size;
-	
+
 	while (i < size) {
 		int key = report_descriptor[i];
 
@@ -111,9 +153,9 @@ static int uses_numbered_reports(__u8 *report_descriptor, __u32 size) {
 			   numbered reports. */
 			return 1;
 		}
-		
+
 		//printf("key: %02hhx\n", key);
-		
+
 		if ((key & 0xf0) == 0xf0) {
 			/* This is a Long Item. The next byte contains the
 			   length of the data section (value) for this key.
@@ -148,23 +190,81 @@ static int uses_numbered_reports(__u8 *report_descriptor, __u32 size) {
 			};
 			key_size = 1;
 		}
-		
+
 		/* Skip over this key and it's associated data */
 		i += data_len + key_size;
 	}
-	
+
 	/* Didn't find a Report ID key. Device doesn't use numbered reports. */
 	return 0;
 }
 
-static int get_device_string(hid_device *dev, const char *key, wchar_t *string, size_t maxlen)
+/*
+ * The caller is responsible for free()ing the (newly-allocated) character
+ * strings pointed to by serial_number_utf8 and product_name_utf8 after use.
+ */
+static int
+parse_uevent_info(const char *uevent, int *bus_type,
+	unsigned short *vendor_id, unsigned short *product_id,
+	char **serial_number_utf8, char **product_name_utf8)
+{
+	char *tmp = strdup(uevent);
+	char *saveptr = NULL;
+	char *line;
+	char *key;
+	char *value;
+
+	int found_id = 0;
+	int found_serial = 0;
+	int found_name = 0;
+
+	line = strtok_r(tmp, "\n", &saveptr);
+	while (line != NULL) {
+		/* line: "KEY=value" */
+		key = line;
+		value = strchr(line, '=');
+		if (!value) {
+			goto next_line;
+		}
+		*value = '\0';
+		value++;
+
+		if (strcmp(key, "HID_ID") == 0) {
+			/**
+			 *        type vendor   product
+			 * HID_ID=0003:000005AC:00008242
+			 **/
+			int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id);
+			if (ret == 3) {
+				found_id = 1;
+			}
+		} else if (strcmp(key, "HID_NAME") == 0) {
+			/* The caller has to free the product name */
+			*product_name_utf8 = strdup(value);
+			found_name = 1;
+		} else if (strcmp(key, "HID_UNIQ") == 0) {
+			/* The caller has to free the serial number */
+			*serial_number_utf8 = strdup(value);
+			found_serial = 1;
+		}
+
+next_line:
+		line = strtok_r(NULL, "\n", &saveptr);
+	}
+
+	free(tmp);
+	return (found_id && found_name && found_serial);
+}
+
+
+static int get_device_string(hid_device *dev, enum device_string_id key, wchar_t *string, size_t maxlen)
 {
 	struct udev *udev;
-	struct udev_device *udev_dev, *parent;
+	struct udev_device *udev_dev, *parent, *hid_dev;
 	struct stat s;
 	int ret = -1;
-	
-	setlocale(LC_ALL,"");
+        char *serial_number_utf8 = NULL;
+        char *product_name_utf8 = NULL;
 
 	/* Create the udev object */
 	udev = udev_new();
@@ -178,26 +278,80 @@ static int get_device_string(hid_device *dev, const char *key, wchar_t *string,
 	/* Open a udev device from the dev_t. 'c' means character device. */
 	udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
 	if (udev_dev) {
-		const char *str;
-		/* Find the parent USB Device */
-		parent = udev_device_get_parent_with_subsystem_devtype(
-		       udev_dev,
-		       "usb",
-		       "usb_device");
-		if (parent) {
-			str = udev_device_get_sysattr_value(parent, key);
-			if (str) {
-				/* Convert the string from UTF-8 to wchar_t */
-				ret = mbstowcs(string, str, maxlen);
-				goto end;
+		hid_dev = udev_device_get_parent_with_subsystem_devtype(
+			udev_dev,
+			"hid",
+			NULL);
+		if (hid_dev) {
+			unsigned short dev_vid;
+			unsigned short dev_pid;
+			int bus_type;
+			size_t retm;
+
+			ret = parse_uevent_info(
+			           udev_device_get_sysattr_value(hid_dev, "uevent"),
+			           &bus_type,
+			           &dev_vid,
+			           &dev_pid,
+			           &serial_number_utf8,
+			           &product_name_utf8);
+
+			if (bus_type == BUS_BLUETOOTH) {
+				switch (key) {
+					case DEVICE_STRING_MANUFACTURER:
+						wcsncpy(string, L"", maxlen);
+						ret = 0;
+						break;
+					case DEVICE_STRING_PRODUCT:
+						retm = mbstowcs(string, product_name_utf8, maxlen);
+						ret = (retm == (size_t)-1)? -1: 0;
+						break;
+					case DEVICE_STRING_SERIAL:
+						retm = mbstowcs(string, serial_number_utf8, maxlen);
+						ret = (retm == (size_t)-1)? -1: 0;
+						break;
+					case DEVICE_STRING_COUNT:
+					default:
+						ret = -1;
+						break;
+				}
+			}
+			else {
+				/* This is a USB device. Find its parent USB Device node. */
+				parent = udev_device_get_parent_with_subsystem_devtype(
+					   udev_dev,
+					   "usb",
+					   "usb_device");
+				if (parent) {
+					const char *str;
+					const char *key_str = NULL;
+
+					if (key >= 0 && key < DEVICE_STRING_COUNT) {
+						key_str = device_string_names[key];
+					} else {
+						ret = -1;
+						goto end;
+					}
+
+					str = udev_device_get_sysattr_value(parent, key_str);
+					if (str) {
+						/* Convert the string from UTF-8 to wchar_t */
+						retm = mbstowcs(string, str, maxlen);
+						ret = (retm == (size_t)-1)? -1: 0;
+						goto end;
+					}
+				}
 			}
 		}
 	}
 
 end:
+        free(serial_number_utf8);
+        free(product_name_utf8);
+
 	udev_device_unref(udev_dev);
-	// parent doesn't need to be (and can't be) unref'd.
-	// I'm not sure why, but it'll throw double-free() errors.
+	/* parent and hid_dev don't need to be (and can't be) unref'd.
+	   I'm not sure why, but they'll throw double-free() errors. */
 	udev_unref(udev);
 
 	return ret;
@@ -205,7 +359,15 @@ end:
 
 int HID_API_EXPORT hid_init(void)
 {
-	/* Nothing to do for this in the Linux/hidraw implementation. */
+	const char *locale;
+
+	/* Set the locale if it's not set. */
+	locale = setlocale(LC_CTYPE, NULL);
+	if (!locale)
+		setlocale(LC_CTYPE, "");
+
+	kernel_version = detect_kernel_version();
+
 	return 0;
 }
 
@@ -215,16 +377,18 @@ int HID_API_EXPORT hid_exit(void)
 	return 0;
 }
 
+
 struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
 {
 	struct udev *udev;
 	struct udev_enumerate *enumerate;
 	struct udev_list_entry *devices, *dev_list_entry;
-	
-	struct hid_device_info *root = NULL; // return object
+
+	struct hid_device_info *root = NULL; /* return object */
 	struct hid_device_info *cur_dev = NULL;
-	
-	setlocale(LC_ALL,"");
+	struct hid_device_info *prev_dev = NULL; /* previous device */
+
+	hid_init();
 
 	/* Create the udev object */
 	udev = udev_new();
@@ -244,46 +408,57 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 		const char *sysfs_path;
 		const char *dev_path;
 		const char *str;
-		struct udev_device *hid_dev; // The device's HID udev node.
-		struct udev_device *dev; // The actual hardware device.
-		struct udev_device *intf_dev; // The device's interface (in the USB sense).
+		struct udev_device *raw_dev; /* The device's hidraw udev node. */
+		struct udev_device *hid_dev; /* The device's HID udev node. */
+		struct udev_device *usb_dev; /* The device's USB udev node. */
+		struct udev_device *intf_dev; /* The device's interface (in the USB sense). */
 		unsigned short dev_vid;
 		unsigned short dev_pid;
-		
+		char *serial_number_utf8 = NULL;
+		char *product_name_utf8 = NULL;
+		int bus_type;
+		int result;
+
 		/* Get the filename of the /sys entry for the device
 		   and create a udev_device object (dev) representing it */
 		sysfs_path = udev_list_entry_get_name(dev_list_entry);
-		hid_dev = udev_device_new_from_syspath(udev, sysfs_path);
-		dev_path = udev_device_get_devnode(hid_dev);
-		
-		/* The device pointed to by hid_dev contains information about
-		   the hidraw device. In order to get information about the
-		   USB device, get the parent device with the
-		   subsystem/devtype pair of "usb"/"usb_device". This will
-		   be several levels up the tree, but the function will find
-		   it.*/
-		dev = udev_device_get_parent_with_subsystem_devtype(
-		       hid_dev,
-		       "usb",
-		       "usb_device");
-		if (!dev) {
-			/* Unable to find parent usb device. */
+		raw_dev = udev_device_new_from_syspath(udev, sysfs_path);
+		dev_path = udev_device_get_devnode(raw_dev);
+
+		hid_dev = udev_device_get_parent_with_subsystem_devtype(
+			raw_dev,
+			"hid",
+			NULL);
+
+		if (!hid_dev) {
+			/* Unable to find parent hid device. */
 			goto next;
 		}
 
-		/* Get the VID/PID of the device */
-		str = udev_device_get_sysattr_value(dev,"idVendor");
-		dev_vid = (str)? strtol(str, NULL, 16): 0x0;
-		str = udev_device_get_sysattr_value(dev, "idProduct");
-		dev_pid = (str)? strtol(str, NULL, 16): 0x0;
+		result = parse_uevent_info(
+			udev_device_get_sysattr_value(hid_dev, "uevent"),
+			&bus_type,
+			&dev_vid,
+			&dev_pid,
+			&serial_number_utf8,
+			&product_name_utf8);
+
+		if (!result) {
+			/* parse_uevent_info() failed for at least one field. */
+			goto next;
+		}
+
+		if (bus_type != BUS_USB && bus_type != BUS_BLUETOOTH) {
+			/* We only know how to handle USB and BT devices. */
+			goto next;
+		}
 
 		/* Check the VID/PID against the arguments */
-		if ((vendor_id == 0x0 && product_id == 0x0) ||
-		    (vendor_id == dev_vid && product_id == dev_pid)) {
+		if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
+		    (product_id == 0x0 || product_id == dev_pid)) {
 			struct hid_device_info *tmp;
-			size_t len;
 
-		    	/* VID/PID match. Create the record. */
+			/* VID/PID match. Create the record. */
 			tmp = malloc(sizeof(struct hid_device_info));
 			if (cur_dev) {
 				cur_dev->next = tmp;
@@ -291,63 +466,103 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 			else {
 				root = tmp;
 			}
+			prev_dev = cur_dev;
 			cur_dev = tmp;
-			
+
 			/* Fill out the record */
 			cur_dev->next = NULL;
-			str = dev_path;
-			if (str) {
-				len = strlen(str);
-				cur_dev->path = calloc(len+1, sizeof(char));
-				strncpy(cur_dev->path, str, len+1);
-				cur_dev->path[len] = '\0';
-			}
-			else
-				cur_dev->path = NULL;
-			
-			/* Serial Number */
-			cur_dev->serial_number
-				= copy_udev_string(dev, "serial");
-
-			/* Manufacturer and Product strings */
-			cur_dev->manufacturer_string
-				= copy_udev_string(dev, "manufacturer");
-			cur_dev->product_string
-				= copy_udev_string(dev, "product");
-			
+			cur_dev->path = dev_path? strdup(dev_path): NULL;
+
 			/* VID/PID */
 			cur_dev->vendor_id = dev_vid;
 			cur_dev->product_id = dev_pid;
 
+			/* Serial Number */
+			cur_dev->serial_number = utf8_to_wchar_t(serial_number_utf8);
+
 			/* Release Number */
-			str = udev_device_get_sysattr_value(dev, "bcdDevice");
-			cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0;
-			
+			cur_dev->release_number = 0x0;
+
 			/* Interface Number */
 			cur_dev->interface_number = -1;
-			/* Get a handle to the interface's udev node. */
-			intf_dev = udev_device_get_parent_with_subsystem_devtype(
-				   hid_dev,
-				   "usb",
-				   "usb_interface");
-			if (intf_dev) {
-				str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber");
-				cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1;
+
+			switch (bus_type) {
+				case BUS_USB:
+					/* The device pointed to by raw_dev contains information about
+					   the hidraw device. In order to get information about the
+					   USB device, get the parent device with the
+					   subsystem/devtype pair of "usb"/"usb_device". This will
+					   be several levels up the tree, but the function will find
+					   it. */
+					usb_dev = udev_device_get_parent_with_subsystem_devtype(
+							raw_dev,
+							"usb",
+							"usb_device");
+
+					if (!usb_dev) {
+						/* Free this device */
+						free(cur_dev->serial_number);
+						free(cur_dev->path);
+						free(cur_dev);
+
+						/* Take it off the device list. */
+						if (prev_dev) {
+							prev_dev->next = NULL;
+							cur_dev = prev_dev;
+						}
+						else {
+							cur_dev = root = NULL;
+						}
+
+						goto next;
+					}
+
+					/* Manufacturer and Product strings */
+					cur_dev->manufacturer_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_MANUFACTURER]);
+					cur_dev->product_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_PRODUCT]);
+
+					/* Release Number */
+					str = udev_device_get_sysattr_value(usb_dev, "bcdDevice");
+					cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0;
+
+					/* Get a handle to the interface's udev node. */
+					intf_dev = udev_device_get_parent_with_subsystem_devtype(
+							raw_dev,
+							"usb",
+							"usb_interface");
+					if (intf_dev) {
+						str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber");
+						cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1;
+					}
+
+					break;
+
+				case BUS_BLUETOOTH:
+					/* Manufacturer and Product strings */
+					cur_dev->manufacturer_string = wcsdup(L"");
+					cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
+
+					break;
+
+				default:
+					/* Unknown device type - this should never happen, as we
+					 * check for USB and Bluetooth devices above */
+					break;
 			}
 		}
-		else
-			goto next;
 
 	next:
-		udev_device_unref(hid_dev);
-		/* dev and intf_dev don't need to be (and can't be)
+		free(serial_number_utf8);
+		free(product_name_utf8);
+		udev_device_unref(raw_dev);
+		/* hid_dev, usb_dev and intf_dev don't need to be (and can't be)
 		   unref()d.  It will cause a double-free() error.  I'm not
 		   sure why.  */
 	}
 	/* Free the enumerator and udev objects. */
 	udev_enumerate_unref(enumerate);
 	udev_unref(udev);
-	
+
 	return root;
 }
 
@@ -365,12 +580,12 @@ void  HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
 	}
 }
 
-hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)
+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
 {
 	struct hid_device_info *devs, *cur_dev;
 	const char *path_to_open = NULL;
 	hid_device *handle = NULL;
-	
+
 	devs = hid_enumerate(vendor_id, product_id);
 	cur_dev = devs;
 	while (cur_dev) {
@@ -396,7 +611,7 @@ hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar
 	}
 
 	hid_free_enumeration(devs);
-	
+
 	return handle;
 }
 
@@ -404,27 +619,14 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 {
 	hid_device *dev = NULL;
 
-	dev = new_hid_device();
+	hid_init();
 
-	if (kernel_version == 0) {
-		struct utsname name;
-		int major, minor, release;
-		int ret;
-		uname(&name);
-		ret = sscanf(name.release, "%d.%d.%d", &major, &minor, &release);
-		if (ret == 3) {
-			kernel_version = major << 16 | minor << 8 | release;
-			//printf("Kernel Version: %d\n", kernel_version);
-		}
-		else {
-			printf("Couldn't sscanf() version string %s\n", name.release);
-		}
-	}
+	dev = new_hid_device();
 
-	// OPEN HERE //
+	/* OPEN HERE */
 	dev->device_handle = open(path, O_RDWR);
 
-	// If we have a good handle, return it.
+	/* If we have a good handle, return it. */
 	if (dev->device_handle > 0) {
 
 		/* Get the report descriptor */
@@ -450,11 +652,11 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
 				uses_numbered_reports(rpt_desc.value,
 				                      rpt_desc.size);
 		}
-		
+
 		return dev;
 	}
 	else {
-		// Unable to open any devices.
+		/* Unable to open any devices. */
 		free(dev);
 		return NULL;
 	}
@@ -475,10 +677,13 @@ int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t
 {
 	int bytes_read;
 
-	if (milliseconds != 0) {
-		/* milliseconds is -1 or > 0. In both cases, we want to
-		   call poll() and wait for data to arrive. -1 means
-		   INFINITE. */
+	if (milliseconds >= 0) {
+		/* Milliseconds is either 0 (non-blocking) or > 0 (contains
+		   a valid timeout). In both cases we want to call poll()
+		   and wait for data to arrive.  Don't rely on non-blocking
+		   operation (O_NONBLOCK) since some kernels don't seem to
+		   properly report device disconnection through read() when
+		   in non-blocking mode.  */
 		int ret;
 		struct pollfd fds;
 
@@ -486,16 +691,24 @@ int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t
 		fds.events = POLLIN;
 		fds.revents = 0;
 		ret = poll(&fds, 1, milliseconds);
-		if (ret == -1 || ret == 0)
+		if (ret == -1 || ret == 0) {
 			/* Error or timeout */
 			return ret;
+		}
+		else {
+			/* Check for errors on the file descriptor. This will
+			   indicate a device disconnection. */
+			if (fds.revents & (POLLERR | POLLHUP | POLLNVAL))
+				return -1;
+		}
 	}
 
 	bytes_read = read(dev->device_handle, data, length);
-	if (bytes_read < 0 && errno == EAGAIN)
+	if (bytes_read < 0 && (errno == EAGAIN || errno == EINPROGRESS))
 		bytes_read = 0;
-	
+
 	if (bytes_read >= 0 &&
+	    kernel_version != 0 &&
 	    kernel_version < KERNEL_VERSION(2,6,34) &&
 	    dev->uses_numbered_reports) {
 		/* Work around a kernel bug. Chop off the first byte. */
@@ -513,25 +726,12 @@ int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
 
 int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
 {
-	int flags, res;
-
-	flags = fcntl(dev->device_handle, F_GETFL, 0);
-	if (flags >= 0) {
-		if (nonblock)
-			res = fcntl(dev->device_handle, F_SETFL, flags | O_NONBLOCK);
-		else
-			res = fcntl(dev->device_handle, F_SETFL, flags & ~O_NONBLOCK);
-	}
-	else
-		return -1;
+	/* Do all non-blocking in userspace using poll(), since it looks
+	   like there's a bug in the kernel in some versions where
+	   read() will not return -1 on disconnection of the USB device */
 
-	if (res < 0) {
-		return -1;
-	}
-	else {
-		dev->blocking = !nonblock;
-		return 0; /* Success */
-	}
+	dev->blocking = !nonblock;
+	return 0; /* Success */
 }
 
 
@@ -570,17 +770,17 @@ void HID_API_EXPORT hid_close(hid_device *dev)
 
 int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
 {
-	return get_device_string(dev, "manufacturer", string, maxlen);
+	return get_device_string(dev, DEVICE_STRING_MANUFACTURER, string, maxlen);
 }
 
 int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
 {
-	return get_device_string(dev, "product", string, maxlen);
+	return get_device_string(dev, DEVICE_STRING_PRODUCT, string, maxlen);
 }
 
 int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
 {
-	return get_device_string(dev, "serial", string, maxlen);
+	return get_device_string(dev, DEVICE_STRING_SERIAL, string, maxlen);
 }
 
 int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
diff --git a/src/libambit/hidapi/hidapi.h b/src/libambit/hidapi/hidapi.h
index 6c8c483..5730f86 100644
--- a/src/libambit/hidapi/hidapi.h
+++ b/src/libambit/hidapi/hidapi.h
@@ -11,7 +11,7 @@
 
  At the discretion of the user of this library,
  this software may be licensed under the terms of the
- GNU Public License v3, a BSD-Style license, or the
+ GNU General Public License v3, a BSD-Style license, or the
  original HIDAPI license as outlined in the LICENSE.txt,
  LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
  files located at the root of the source distribution.
@@ -112,6 +112,8 @@ extern "C" {
 
 			This function returns a linked list of all the HID devices
 			attached to the system which match vendor_id and product_id.
+			If @p vendor_id is set to 0 then any vendor matches.
+			If @p product_id is set to 0 then any product matches.
 			If @p vendor_id and @p product_id are both set to 0, then
 			all HID devices will be returned.
 
@@ -155,7 +157,7 @@ extern "C" {
 				This function returns a pointer to a #hid_device object on
 				success or NULL on failure.
 		*/
-		HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number);
+		HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number);
 
 		/** @brief Open a HID device by its path name.
 
@@ -216,7 +218,8 @@ extern "C" {
 
 			@returns
 				This function returns the actual number of bytes read and
-				-1 on error.
+				-1 on error. If no packet was available to be read within
+				the timeout period, this function returns 0.
 		*/
 		int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds);
 
@@ -235,7 +238,8 @@ extern "C" {
 
 			@returns
 				This function returns the actual number of bytes read and
-				-1 on error.
+				-1 on error. If no packet was available to be read and
+				the handle is in non-blocking mode, this function returns 0.
 		*/
 		int  HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);
 

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-running/openambit.git



More information about the Pkg-running-devel mailing list