SDL  2.0
hid.c
Go to the documentation of this file.
1 /*******************************************************
2  HIDAPI - Multi-Platform library for
3  communication with HID devices.
4 
5  Alan Ott
6  Signal 11 Software
7 
8  8/22/2009
9  Linux Version - 6/2/2010
10  Libusb Version - 8/13/2010
11  FreeBSD Version - 11/1/2011
12 
13  Copyright 2009, All Rights Reserved.
14 
15  At the discretion of the user of this library,
16  this software may be licensed under the terms of the
17  GNU General Public License v3, a BSD-Style license, or the
18  original HIDAPI license as outlined in the LICENSE.txt,
19  LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
20  files located at the root of the source distribution.
21  These files may also be found in the public source
22  code repository located at:
23  http://github.com/signal11/hidapi .
24 ********************************************************/
25 #include "../../SDL_internal.h"
26 
27 #ifdef SDL_JOYSTICK_HIDAPI
28 
29 #ifndef _GNU_SOURCE
30 #define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */
31 #endif
32 
33 /* C */
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <ctype.h>
38 #include <locale.h>
39 #include <errno.h>
40 
41 /* Unix */
42 #include <unistd.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <sys/utsname.h>
47 #include <fcntl.h>
48 #include <pthread.h>
49 #include <wchar.h>
50 
51 /* GNU / LibUSB */
52 #include <libusb.h>
53 #ifndef __ANDROID__
54 #include <iconv.h>
55 #endif
56 
57 #include "hidapi.h"
58 
59 #ifdef NAMESPACE
60 namespace NAMESPACE
61 {
62 #endif
63 
64 #ifdef __ANDROID__
65 
66 /* Barrier implementation because Android/Bionic don't have pthread_barrier.
67  This implementation came from Brent Priddy and was posted on
68  StackOverflow. It is used with his permission. */
69 typedef int pthread_barrierattr_t;
70 typedef struct pthread_barrier {
71  pthread_mutex_t mutex;
72  pthread_cond_t cond;
73  int count;
74  int trip_count;
75 } pthread_barrier_t;
76 
77 static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
78 {
79  if(count == 0) {
80  errno = EINVAL;
81  return -1;
82  }
83 
84  if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
85  return -1;
86  }
87  if(pthread_cond_init(&barrier->cond, 0) < 0) {
88  pthread_mutex_destroy(&barrier->mutex);
89  return -1;
90  }
91  barrier->trip_count = count;
92  barrier->count = 0;
93 
94  return 0;
95 }
96 
97 static int pthread_barrier_destroy(pthread_barrier_t *barrier)
98 {
99  pthread_cond_destroy(&barrier->cond);
100  pthread_mutex_destroy(&barrier->mutex);
101  return 0;
102 }
103 
104 static int pthread_barrier_wait(pthread_barrier_t *barrier)
105 {
106  pthread_mutex_lock(&barrier->mutex);
107  ++(barrier->count);
108  if(barrier->count >= barrier->trip_count)
109  {
110  barrier->count = 0;
111  pthread_cond_broadcast(&barrier->cond);
112  pthread_mutex_unlock(&barrier->mutex);
113  return 1;
114  }
115  else
116  {
117  pthread_cond_wait(&barrier->cond, &(barrier->mutex));
118  pthread_mutex_unlock(&barrier->mutex);
119  return 0;
120  }
121 }
122 
123 #endif
124 
125 #if defined(__cplusplus) && !defined(NAMESPACE)
126 extern "C" {
127 #endif
128 
129 #ifdef DEBUG_PRINTF
130 #define LOG(...) fprintf(stderr, __VA_ARGS__)
131 #else
132 #define LOG(...) do {} while (0)
133 #endif
134 
135 #ifndef __FreeBSD__
136 #define DETACH_KERNEL_DRIVER
137 #endif
138 
139 /* Uncomment to enable the retrieval of Usage and Usage Page in
140 hid_enumerate(). Warning, on platforms different from FreeBSD
141 this is very invasive as it requires the detach
142 and re-attach of the kernel driver. See comments inside hid_enumerate().
143 libusb HIDAPI programs are encouraged to use the interface number
144 instead to differentiate between interfaces on a composite HID device. */
145 /*#define INVASIVE_GET_USAGE*/
146 
147 /* Linked List of input reports received from the device. */
148 struct input_report {
149  uint8_t *data;
150  size_t len;
151  struct input_report *next;
152 };
153 
154 
155 struct hid_device_ {
156  /* Handle to the actual device. */
157  libusb_device_handle *device_handle;
158 
159  /* Endpoint information */
160  int input_endpoint;
161  int output_endpoint;
162  int input_ep_max_packet_size;
163 
164  /* The interface number of the HID */
165  int interface;
166 
167  /* Indexes of Strings */
168  int manufacturer_index;
169  int product_index;
170  int serial_index;
171 
172  /* Whether blocking reads are used */
173  int blocking; /* boolean */
174 
175  /* Read thread objects */
176  pthread_t thread;
177  pthread_mutex_t mutex; /* Protects input_reports */
178  pthread_cond_t condition;
179  pthread_barrier_t barrier; /* Ensures correct startup sequence */
180  int shutdown_thread;
181  int cancelled;
182  struct libusb_transfer *transfer;
183 
184  /* List of received input reports. */
185  struct input_report *input_reports;
186 };
187 
188 static libusb_context *usb_context = NULL;
189 
190 uint16_t get_usb_code_for_current_locale(void);
191 static int return_data(hid_device *dev, unsigned char *data, size_t length);
192 
193 static hid_device *new_hid_device(void)
194 {
195  hid_device *dev = (hid_device *)calloc(1, sizeof(hid_device));
196  dev->blocking = 1;
197 
198  pthread_mutex_init(&dev->mutex, NULL);
199  pthread_cond_init(&dev->condition, NULL);
200  pthread_barrier_init(&dev->barrier, NULL, 2);
201 
202  return dev;
203 }
204 
205 static void free_hid_device(hid_device *dev)
206 {
207  /* Clean up the thread objects */
208  pthread_barrier_destroy(&dev->barrier);
209  pthread_cond_destroy(&dev->condition);
210  pthread_mutex_destroy(&dev->mutex);
211 
212  /* Free the device itself */
213  free(dev);
214 }
215 
216 #if 0
217 /*TODO: Implement this funciton on hidapi/libusb.. */
218 static void register_error(hid_device *device, const char *op)
219 {
220 
221 }
222 #endif
223 
224 #ifdef INVASIVE_GET_USAGE
225 /* Get bytes from a HID Report Descriptor.
226  Only call with a num_bytes of 0, 1, 2, or 4. */
227 static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)
228 {
229  /* Return if there aren't enough bytes. */
230  if (cur + num_bytes >= len)
231  return 0;
232 
233  if (num_bytes == 0)
234  return 0;
235  else if (num_bytes == 1) {
236  return rpt[cur+1];
237  }
238  else if (num_bytes == 2) {
239  return (rpt[cur+2] * 256 + rpt[cur+1]);
240  }
241  else if (num_bytes == 4) {
242  return (rpt[cur+4] * 0x01000000 +
243  rpt[cur+3] * 0x00010000 +
244  rpt[cur+2] * 0x00000100 +
245  rpt[cur+1] * 0x00000001);
246  }
247  else
248  return 0;
249 }
250 
251 /* Retrieves the device's Usage Page and Usage from the report
252  descriptor. The algorithm is simple, as it just returns the first
253  Usage and Usage Page that it finds in the descriptor.
254  The return value is 0 on success and -1 on failure. */
255 static int get_usage(uint8_t *report_descriptor, size_t size,
256  unsigned short *usage_page, unsigned short *usage)
257 {
258  unsigned int i = 0;
259  int size_code;
260  int data_len, key_size;
261  int usage_found = 0, usage_page_found = 0;
262 
263  while (i < size) {
264  int key = report_descriptor[i];
265  int key_cmd = key & 0xfc;
266 
267  //printf("key: %02hhx\n", key);
268 
269  if ((key & 0xf0) == 0xf0) {
270  /* This is a Long Item. The next byte contains the
271  length of the data section (value) for this key.
272  See the HID specification, version 1.11, section
273  6.2.2.3, titled "Long Items." */
274  if (i+1 < size)
275  data_len = report_descriptor[i+1];
276  else
277  data_len = 0; /* malformed report */
278  key_size = 3;
279  }
280  else {
281  /* This is a Short Item. The bottom two bits of the
282  key contain the size code for the data section
283  (value) for this key. Refer to the HID
284  specification, version 1.11, section 6.2.2.2,
285  titled "Short Items." */
286  size_code = key & 0x3;
287  switch (size_code) {
288  case 0:
289  case 1:
290  case 2:
291  data_len = size_code;
292  break;
293  case 3:
294  data_len = 4;
295  break;
296  default:
297  /* Can't ever happen since size_code is & 0x3 */
298  data_len = 0;
299  break;
300  };
301  key_size = 1;
302  }
303 
304  if (key_cmd == 0x4) {
305  *usage_page = get_bytes(report_descriptor, size, data_len, i);
306  usage_page_found = 1;
307  //printf("Usage Page: %x\n", (uint32_t)*usage_page);
308  }
309  if (key_cmd == 0x8) {
310  *usage = get_bytes(report_descriptor, size, data_len, i);
311  usage_found = 1;
312  //printf("Usage: %x\n", (uint32_t)*usage);
313  }
314 
315  if (usage_page_found && usage_found)
316  return 0; /* success */
317 
318  /* Skip over this key and it's associated data */
319  i += data_len + key_size;
320  }
321 
322  return -1; /* failure */
323 }
324 #endif /* INVASIVE_GET_USAGE */
325 
326 #if defined(__FreeBSD__) && __FreeBSD__ < 10
327 /* The libusb version included in FreeBSD < 10 doesn't have this function. In
328  mainline libusb, it's inlined in libusb.h. This function will bear a striking
329  resemblance to that one, because there's about one way to code it.
330 
331  Note that the data parameter is Unicode in UTF-16LE encoding.
332  Return value is the number of bytes in data, or LIBUSB_ERROR_*.
333  */
334 static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
335  uint8_t descriptor_index, uint16_t lang_id,
336  unsigned char *data, int length)
337 {
338  return libusb_control_transfer(dev,
339  LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */
340  LIBUSB_REQUEST_GET_DESCRIPTOR,
341  (LIBUSB_DT_STRING << 8) | descriptor_index,
342  lang_id, data, (uint16_t) length, 1000);
343 }
344 
345 #endif
346 
347 
348 /* Get the first language the device says it reports. This comes from
349  USB string #0. */
350 static uint16_t get_first_language(libusb_device_handle *dev)
351 {
352  uint16_t buf[32];
353  int len;
354 
355  /* Get the string from libusb. */
356  len = libusb_get_string_descriptor(dev,
357  0x0, /* String ID */
358  0x0, /* Language */
359  (unsigned char*)buf,
360  sizeof(buf));
361  if (len < 4)
362  return 0x0;
363 
364  return buf[1]; /* First two bytes are len and descriptor type. */
365 }
366 
367 static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
368 {
369  uint16_t buf[32];
370  int len;
371  int i;
372 
373  /* Get the string from libusb. */
374  len = libusb_get_string_descriptor(dev,
375  0x0, /* String ID */
376  0x0, /* Language */
377  (unsigned char*)buf,
378  sizeof(buf));
379  if (len < 4)
380  return 0x0;
381 
382 
383  len /= 2; /* language IDs are two-bytes each. */
384  /* Start at index 1 because there are two bytes of protocol data. */
385  for (i = 1; i < len; i++) {
386  if (buf[i] == lang)
387  return 1;
388  }
389 
390  return 0;
391 }
392 
393 
394 /* This function returns a newly allocated wide string containing the USB
395  device string numbered by the index. The returned string must be freed
396  by using free(). */
397 static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
398 {
399  char buf[512];
400  int len;
401  wchar_t *str = NULL;
402 
403 #ifndef __ANDROID__ /* we don't use iconv on Android */
404  wchar_t wbuf[256];
405  /* iconv variables */
406  iconv_t ic;
407  size_t inbytes;
408  size_t outbytes;
409  size_t res;
410 #ifdef __FreeBSD__
411  const char *inptr;
412 #else
413  char *inptr;
414 #endif
415  char *outptr;
416 #endif
417 
418  /* Determine which language to use. */
419  uint16_t lang;
420  lang = get_usb_code_for_current_locale();
421  if (!is_language_supported(dev, lang))
422  lang = get_first_language(dev);
423 
424  /* Get the string from libusb. */
425  len = libusb_get_string_descriptor(dev,
426  idx,
427  lang,
428  (unsigned char*)buf,
429  sizeof(buf));
430  if (len < 0)
431  return NULL;
432 
433 #ifdef __ANDROID__
434 
435  /* Bionic does not have iconv support nor wcsdup() function, so it
436  has to be done manually. The following code will only work for
437  code points that can be represented as a single UTF-16 character,
438  and will incorrectly convert any code points which require more
439  than one UTF-16 character.
440 
441  Skip over the first character (2-bytes). */
442  len -= 2;
443  str = malloc((len / 2 + 1) * sizeof(wchar_t));
444  int i;
445  for (i = 0; i < len / 2; i++) {
446  str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8);
447  }
448  str[len / 2] = 0x00000000;
449 
450 #else
451 
452  /* buf does not need to be explicitly NULL-terminated because
453  it is only passed into iconv() which does not need it. */
454 
455  /* Initialize iconv. */
456  ic = iconv_open("WCHAR_T", "UTF-16LE");
457  if (ic == (iconv_t)-1) {
458  LOG("iconv_open() failed\n");
459  return NULL;
460  }
461 
462  /* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
463  Skip the first character (2-bytes). */
464  inptr = buf+2;
465  inbytes = len-2;
466  outptr = (char*) wbuf;
467  outbytes = sizeof(wbuf);
468  res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
469  if (res == (size_t)-1) {
470  LOG("iconv() failed\n");
471  goto err;
472  }
473 
474  /* Write the terminating NULL. */
475  wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
476  if (outbytes >= sizeof(wbuf[0]))
477  *((wchar_t*)outptr) = 0x00000000;
478 
479  /* Allocate and copy the string. */
480  str = wcsdup(wbuf);
481 
482 err:
483  iconv_close(ic);
484 
485 #endif
486 
487  return str;
488 }
489 
490 static char *make_path(libusb_device *dev, int interface_number)
491 {
492  char str[64];
493  snprintf(str, sizeof(str), "%04x:%04x:%02x",
494  libusb_get_bus_number(dev),
495  libusb_get_device_address(dev),
496  interface_number);
497  str[sizeof(str)-1] = '\0';
498 
499  return strdup(str);
500 }
501 
502 
503 int HID_API_EXPORT hid_init(void)
504 {
505  if (!usb_context) {
506  const char *locale;
507 
508  /* Init Libusb */
509  if (libusb_init(&usb_context))
510  return -1;
511 
512  /* Set the locale if it's not set. */
513  locale = setlocale(LC_CTYPE, NULL);
514  if (!locale)
515  setlocale(LC_CTYPE, "");
516  }
517 
518  return 0;
519 }
520 
521 int HID_API_EXPORT hid_exit(void)
522 {
523  if (usb_context) {
524  libusb_exit(usb_context);
525  usb_context = NULL;
526  }
527 
528  return 0;
529 }
530 
531 static int is_xbox360(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc)
532 {
533  static const int XB360_IFACE_SUBCLASS = 93;
534  static const int XB360_IFACE_PROTOCOL = 1; /* Wired only */
535  static const int SUPPORTED_VENDORS[] = {
536  0x0079, /* GPD Win 2 */
537  0x044f, /* Thrustmaster */
538  0x045e, /* Microsoft */
539  0x046d, /* Logitech */
540  0x056e, /* Elecom */
541  0x06a3, /* Saitek */
542  0x0738, /* Mad Catz */
543  0x07ff, /* Mad Catz */
544  0x0e6f, /* Unknown */
545  0x0f0d, /* Hori */
546  0x11c9, /* Nacon */
547  0x12ab, /* Unknown */
548  0x1430, /* RedOctane */
549  0x146b, /* BigBen */
550  0x1532, /* Razer Sabertooth */
551  0x15e4, /* Numark */
552  0x162e, /* Joytech */
553  0x1689, /* Razer Onza */
554  0x1bad, /* Harmonix */
555  0x24c6, /* PowerA */
556  };
557 
558  if (intf_desc->bInterfaceNumber == 0 &&
559  intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC &&
560  intf_desc->bInterfaceSubClass == XB360_IFACE_SUBCLASS &&
561  intf_desc->bInterfaceProtocol == XB360_IFACE_PROTOCOL) {
562  int i;
563  for (i = 0; i < sizeof(SUPPORTED_VENDORS)/sizeof(SUPPORTED_VENDORS[0]); ++i) {
564  if (vendor_id == SUPPORTED_VENDORS[i]) {
565  return 1;
566  }
567  }
568  }
569  return 0;
570 }
571 
572 static int is_xboxone(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc)
573 {
574  static const int XB1_IFACE_SUBCLASS = 71;
575  static const int XB1_IFACE_PROTOCOL = 208;
576  static const int SUPPORTED_VENDORS[] = {
577  0x045e, /* Microsoft */
578  0x0738, /* Mad Catz */
579  0x0e6f, /* Unknown */
580  0x0f0d, /* Hori */
581  0x1532, /* Razer Wildcat */
582  0x24c6, /* PowerA */
583  };
584 
585  if (intf_desc->bInterfaceNumber == 0 &&
586  intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC &&
587  intf_desc->bInterfaceSubClass == XB1_IFACE_SUBCLASS &&
588  intf_desc->bInterfaceProtocol == XB1_IFACE_PROTOCOL) {
589  int i;
590  for (i = 0; i < sizeof(SUPPORTED_VENDORS)/sizeof(SUPPORTED_VENDORS[0]); ++i) {
591  if (vendor_id == SUPPORTED_VENDORS[i]) {
592  return 1;
593  }
594  }
595  }
596  return 0;
597 }
598 
599 static int should_enumerate_interface(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc)
600 {
601  if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID)
602  return 1;
603 
604  /* Also enumerate Xbox 360 controllers */
605  if (is_xbox360(vendor_id, intf_desc))
606  {
607  /* hid_write() to Xbox 360 controllers doesn't seem to work on Linux:
608  - xpad 1-2:1.0: xpad_try_sending_next_out_packet - usb_submit_urb failed with result -2
609  Xbox 360 controller support is good on Linux anyway, so we'll ignore this for now.
610  return 1;
611  */
612  }
613 
614  /* Also enumerate Xbox One controllers */
615  if (is_xboxone(vendor_id, intf_desc))
616  return 1;
617 
618  return 0;
619 }
620 
621 struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
622 {
623  libusb_device **devs;
624  libusb_device *dev;
625  libusb_device_handle *handle;
626  ssize_t num_devs;
627  int i = 0;
628 
629  struct hid_device_info *root = NULL; /* return object */
630  struct hid_device_info *cur_dev = NULL;
631 
632  if(hid_init() < 0)
633  return NULL;
634 
635  num_devs = libusb_get_device_list(usb_context, &devs);
636  if (num_devs < 0)
637  return NULL;
638  while ((dev = devs[i++]) != NULL) {
639  struct libusb_device_descriptor desc;
640  struct libusb_config_descriptor *conf_desc = NULL;
641  int j, k;
642  int interface_num = 0;
643 
644  int res = libusb_get_device_descriptor(dev, &desc);
645  unsigned short dev_vid = desc.idVendor;
646  unsigned short dev_pid = desc.idProduct;
647 
648  res = libusb_get_active_config_descriptor(dev, &conf_desc);
649  if (res < 0)
650  libusb_get_config_descriptor(dev, 0, &conf_desc);
651  if (conf_desc) {
652  for (j = 0; j < conf_desc->bNumInterfaces; j++) {
653  const struct libusb_interface *intf = &conf_desc->interface[j];
654  for (k = 0; k < intf->num_altsetting; k++) {
655  const struct libusb_interface_descriptor *intf_desc;
656  intf_desc = &intf->altsetting[k];
657  if (should_enumerate_interface(dev_vid, intf_desc)) {
658  interface_num = intf_desc->bInterfaceNumber;
659 
660  /* Check the VID/PID against the arguments */
661  if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
662  (product_id == 0x0 || product_id == dev_pid)) {
663  struct hid_device_info *tmp;
664 
665  /* VID/PID match. Create the record. */
666  tmp = (struct hid_device_info *)calloc(1, sizeof(struct hid_device_info));
667  if (cur_dev) {
668  cur_dev->next = tmp;
669  }
670  else {
671  root = tmp;
672  }
673  cur_dev = tmp;
674 
675  /* Fill out the record */
676  cur_dev->next = NULL;
677  cur_dev->path = make_path(dev, interface_num);
678 
679  res = libusb_open(dev, &handle);
680 
681  if (res >= 0) {
682  /* Serial Number */
683  if (desc.iSerialNumber > 0)
684  cur_dev->serial_number =
685  get_usb_string(handle, desc.iSerialNumber);
686 
687  /* Manufacturer and Product strings */
688  if (desc.iManufacturer > 0)
689  cur_dev->manufacturer_string =
690  get_usb_string(handle, desc.iManufacturer);
691  if (desc.iProduct > 0)
692  cur_dev->product_string =
693  get_usb_string(handle, desc.iProduct);
694 
695 #ifdef INVASIVE_GET_USAGE
696 {
697  /*
698  This section is removed because it is too
699  invasive on the system. Getting a Usage Page
700  and Usage requires parsing the HID Report
701  descriptor. Getting a HID Report descriptor
702  involves claiming the interface. Claiming the
703  interface involves detaching the kernel driver.
704  Detaching the kernel driver is hard on the system
705  because it will unclaim interfaces (if another
706  app has them claimed) and the re-attachment of
707  the driver will sometimes change /dev entry names.
708  It is for these reasons that this section is
709  #if 0. For composite devices, use the interface
710  field in the hid_device_info struct to distinguish
711  between interfaces. */
712  unsigned char data[256];
713 #ifdef DETACH_KERNEL_DRIVER
714  int detached = 0;
715  /* Usage Page and Usage */
716  res = libusb_kernel_driver_active(handle, interface_num);
717  if (res == 1) {
718  res = libusb_detach_kernel_driver(handle, interface_num);
719  if (res < 0)
720  LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
721  else
722  detached = 1;
723  }
724 #endif
725  res = libusb_claim_interface(handle, interface_num);
726  if (res >= 0) {
727  /* Get the HID Report Descriptor. */
728  res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
729  if (res >= 0) {
730  unsigned short page=0, usage=0;
731  /* Parse the usage and usage page
732  out of the report descriptor. */
733  get_usage(data, res, &page, &usage);
734  cur_dev->usage_page = page;
735  cur_dev->usage = usage;
736  }
737  else
738  LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);
739 
740  /* Release the interface */
741  res = libusb_release_interface(handle, interface_num);
742  if (res < 0)
743  LOG("Can't release the interface.\n");
744  }
745  else
746  LOG("Can't claim interface %d\n", res);
747 #ifdef DETACH_KERNEL_DRIVER
748  /* Re-attach kernel driver if necessary. */
749  if (detached) {
750  res = libusb_attach_kernel_driver(handle, interface_num);
751  if (res < 0)
752  LOG("Couldn't re-attach kernel driver.\n");
753  }
754 #endif
755 }
756 #endif /* INVASIVE_GET_USAGE */
757 
758  libusb_close(handle);
759  }
760  /* VID/PID */
761  cur_dev->vendor_id = dev_vid;
762  cur_dev->product_id = dev_pid;
763 
764  /* Release Number */
765  cur_dev->release_number = desc.bcdDevice;
766 
767  /* Interface Number */
768  cur_dev->interface_number = interface_num;
769  }
770  }
771  } /* altsettings */
772  } /* interfaces */
773  libusb_free_config_descriptor(conf_desc);
774  }
775  }
776 
777  libusb_free_device_list(devs, 1);
778 
779  return root;
780 }
781 
783 {
784  struct hid_device_info *d = devs;
785  while (d) {
786  struct hid_device_info *next = d->next;
787  free(d->path);
788  free(d->serial_number);
790  free(d->product_string);
791  free(d);
792  d = next;
793  }
794 }
795 
796 hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
797 {
798  struct hid_device_info *devs, *cur_dev;
799  const char *path_to_open = NULL;
800  hid_device *handle = NULL;
801 
802  devs = hid_enumerate(vendor_id, product_id);
803  cur_dev = devs;
804  while (cur_dev) {
805  if (cur_dev->vendor_id == vendor_id &&
806  cur_dev->product_id == product_id) {
807  if (serial_number) {
808  if (cur_dev->serial_number &&
809  wcscmp(serial_number, cur_dev->serial_number) == 0) {
810  path_to_open = cur_dev->path;
811  break;
812  }
813  }
814  else {
815  path_to_open = cur_dev->path;
816  break;
817  }
818  }
819  cur_dev = cur_dev->next;
820  }
821 
822  if (path_to_open) {
823  /* Open the device */
824  handle = hid_open_path(path_to_open, 0);
825  }
826 
827  hid_free_enumeration(devs);
828 
829  return handle;
830 }
831 
832 static void read_callback(struct libusb_transfer *transfer)
833 {
834  hid_device *dev = (hid_device *)transfer->user_data;
835  int res;
836 
837  if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
838 
839  struct input_report *rpt = (struct input_report *)malloc(sizeof(*rpt));
840  rpt->data = (uint8_t *)malloc(transfer->actual_length);
841  memcpy(rpt->data, transfer->buffer, transfer->actual_length);
842  rpt->len = transfer->actual_length;
843  rpt->next = NULL;
844 
845  pthread_mutex_lock(&dev->mutex);
846 
847  /* Attach the new report object to the end of the list. */
848  if (dev->input_reports == NULL) {
849  /* The list is empty. Put it at the root. */
850  dev->input_reports = rpt;
851  pthread_cond_signal(&dev->condition);
852  }
853  else {
854  /* Find the end of the list and attach. */
855  struct input_report *cur = dev->input_reports;
856  int num_queued = 0;
857  while (cur->next != NULL) {
858  cur = cur->next;
859  num_queued++;
860  }
861  cur->next = rpt;
862 
863  /* Pop one off if we've reached 30 in the queue. This
864  way we don't grow forever if the user never reads
865  anything from the device. */
866  if (num_queued > 30) {
867  return_data(dev, NULL, 0);
868  }
869  }
870  pthread_mutex_unlock(&dev->mutex);
871  }
872  else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
873  dev->shutdown_thread = 1;
874  dev->cancelled = 1;
875  return;
876  }
877  else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
878  dev->shutdown_thread = 1;
879  dev->cancelled = 1;
880  return;
881  }
882  else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
883  //LOG("Timeout (normal)\n");
884  }
885  else {
886  LOG("Unknown transfer code: %d\n", transfer->status);
887  }
888 
889  /* Re-submit the transfer object. */
890  res = libusb_submit_transfer(transfer);
891  if (res != 0) {
892  LOG("Unable to submit URB. libusb error code: %d\n", res);
893  dev->shutdown_thread = 1;
894  dev->cancelled = 1;
895  }
896 }
897 
898 
899 static void *read_thread(void *param)
900 {
901  hid_device *dev = (hid_device *)param;
902  unsigned char *buf;
903  const size_t length = dev->input_ep_max_packet_size;
904 
905  /* Set up the transfer object. */
906  buf = (unsigned char *)malloc(length);
907  dev->transfer = libusb_alloc_transfer(0);
908  libusb_fill_interrupt_transfer(dev->transfer,
909  dev->device_handle,
910  dev->input_endpoint,
911  buf,
912  length,
913  read_callback,
914  dev,
915  5000/*timeout*/);
916 
917  /* Make the first submission. Further submissions are made
918  from inside read_callback() */
919  libusb_submit_transfer(dev->transfer);
920 
921  /* Notify the main thread that the read thread is up and running. */
922  pthread_barrier_wait(&dev->barrier);
923 
924  /* Handle all the events. */
925  while (!dev->shutdown_thread) {
926  int res;
927  res = libusb_handle_events(usb_context);
928  if (res < 0) {
929  /* There was an error. */
930  LOG("read_thread(): libusb reports error # %d\n", res);
931 
932  /* Break out of this loop only on fatal error.*/
933  if (res != LIBUSB_ERROR_BUSY &&
934  res != LIBUSB_ERROR_TIMEOUT &&
935  res != LIBUSB_ERROR_OVERFLOW &&
936  res != LIBUSB_ERROR_INTERRUPTED) {
937  break;
938  }
939  }
940  }
941 
942  /* Cancel any transfer that may be pending. This call will fail
943  if no transfers are pending, but that's OK. */
944  libusb_cancel_transfer(dev->transfer);
945 
946  while (!dev->cancelled)
947  libusb_handle_events_completed(usb_context, &dev->cancelled);
948 
949  /* Now that the read thread is stopping, Wake any threads which are
950  waiting on data (in hid_read_timeout()). Do this under a mutex to
951  make sure that a thread which is about to go to sleep waiting on
952  the condition actually will go to sleep before the condition is
953  signaled. */
954  pthread_mutex_lock(&dev->mutex);
955  pthread_cond_broadcast(&dev->condition);
956  pthread_mutex_unlock(&dev->mutex);
957 
958  /* The dev->transfer->buffer and dev->transfer objects are cleaned up
959  in hid_close(). They are not cleaned up here because this thread
960  could end either due to a disconnect or due to a user
961  call to hid_close(). In both cases the objects can be safely
962  cleaned up after the call to pthread_join() (in hid_close()), but
963  since hid_close() calls libusb_cancel_transfer(), on these objects,
964  they can not be cleaned up here. */
965 
966  return NULL;
967 }
968 
969 
970 hid_device * HID_API_EXPORT hid_open_path(const char *path, int bExclusive)
971 {
972  hid_device *dev = NULL;
973 
974  libusb_device **devs;
975  libusb_device *usb_dev;
976  int res;
977  int d = 0;
978  int good_open = 0;
979 
980  if(hid_init() < 0)
981  return NULL;
982 
983  dev = new_hid_device();
984 
985  libusb_get_device_list(usb_context, &devs);
986  while ((usb_dev = devs[d++]) != NULL) {
987  struct libusb_device_descriptor desc;
988  struct libusb_config_descriptor *conf_desc = NULL;
989  int i,j,k;
990  libusb_get_device_descriptor(usb_dev, &desc);
991 
992  if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
993  continue;
994  for (j = 0; j < conf_desc->bNumInterfaces; j++) {
995  const struct libusb_interface *intf = &conf_desc->interface[j];
996  for (k = 0; k < intf->num_altsetting; k++) {
997  const struct libusb_interface_descriptor *intf_desc;
998  intf_desc = &intf->altsetting[k];
999  if (should_enumerate_interface(desc.idVendor, intf_desc)) {
1000  char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
1001  if (!strcmp(dev_path, path)) {
1002  /* Matched Paths. Open this device */
1003 
1004  /* OPEN HERE */
1005  res = libusb_open(usb_dev, &dev->device_handle);
1006  if (res < 0) {
1007  LOG("can't open device\n");
1008  free(dev_path);
1009  break;
1010  }
1011  good_open = 1;
1012 #ifdef DETACH_KERNEL_DRIVER
1013  /* Detach the kernel driver, but only if the
1014  device is managed by the kernel */
1015  if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
1016  res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
1017  if (res < 0) {
1018  libusb_close(dev->device_handle);
1019  LOG("Unable to detach Kernel Driver\n");
1020  free(dev_path);
1021  good_open = 0;
1022  break;
1023  }
1024  }
1025 #endif
1026  res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
1027  if (res < 0) {
1028  LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
1029  free(dev_path);
1030  libusb_close(dev->device_handle);
1031  good_open = 0;
1032  break;
1033  }
1034 
1035  /* Store off the string descriptor indexes */
1036  dev->manufacturer_index = desc.iManufacturer;
1037  dev->product_index = desc.iProduct;
1038  dev->serial_index = desc.iSerialNumber;
1039 
1040  /* Store off the interface number */
1041  dev->interface = intf_desc->bInterfaceNumber;
1042 
1043  /* Find the INPUT and OUTPUT endpoints. An
1044  OUTPUT endpoint is not required. */
1045  for (i = 0; i < intf_desc->bNumEndpoints; i++) {
1046  const struct libusb_endpoint_descriptor *ep
1047  = &intf_desc->endpoint[i];
1048 
1049  /* Determine the type and direction of this
1050  endpoint. */
1051  int is_interrupt =
1052  (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1053  == LIBUSB_TRANSFER_TYPE_INTERRUPT;
1054  int is_output =
1055  (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
1056  == LIBUSB_ENDPOINT_OUT;
1057  int is_input =
1058  (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
1059  == LIBUSB_ENDPOINT_IN;
1060 
1061  /* Decide whether to use it for input or output. */
1062  if (dev->input_endpoint == 0 &&
1063  is_interrupt && is_input) {
1064  /* Use this endpoint for INPUT */
1065  dev->input_endpoint = ep->bEndpointAddress;
1066  dev->input_ep_max_packet_size = ep->wMaxPacketSize;
1067  }
1068  if (dev->output_endpoint == 0 &&
1069  is_interrupt && is_output) {
1070  /* Use this endpoint for OUTPUT */
1071  dev->output_endpoint = ep->bEndpointAddress;
1072  }
1073  }
1074 
1075  pthread_create(&dev->thread, NULL, read_thread, dev);
1076 
1077  /* Wait here for the read thread to be initialized. */
1078  pthread_barrier_wait(&dev->barrier);
1079 
1080  }
1081  free(dev_path);
1082  }
1083  }
1084  }
1085  libusb_free_config_descriptor(conf_desc);
1086 
1087  }
1088 
1089  libusb_free_device_list(devs, 1);
1090 
1091  /* If we have a good handle, return it. */
1092  if (good_open) {
1093  return dev;
1094  }
1095  else {
1096  /* Unable to open any devices. */
1097  free_hid_device(dev);
1098  return NULL;
1099  }
1100 }
1101 
1102 
1103 int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
1104 {
1105  int res;
1106  int report_number = data[0];
1107  int skipped_report_id = 0;
1108 
1109  if (report_number == 0x0) {
1110  data++;
1111  length--;
1112  skipped_report_id = 1;
1113  }
1114 
1115 
1116  if (dev->output_endpoint <= 0) {
1117  /* No interrupt out endpoint. Use the Control Endpoint */
1118  res = libusb_control_transfer(dev->device_handle,
1119  LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
1120  0x09/*HID Set_Report*/,
1121  (2/*HID output*/ << 8) | report_number,
1122  dev->interface,
1123  (unsigned char *)data, length,
1124  1000/*timeout millis*/);
1125 
1126  if (res < 0)
1127  return -1;
1128 
1129  if (skipped_report_id)
1130  length++;
1131 
1132  return length;
1133  }
1134  else {
1135  /* Use the interrupt out endpoint */
1136  int actual_length;
1137  res = libusb_interrupt_transfer(dev->device_handle,
1138  dev->output_endpoint,
1139  (unsigned char*)data,
1140  length,
1141  &actual_length, 1000);
1142 
1143  if (res < 0)
1144  return -1;
1145 
1146  if (skipped_report_id)
1147  actual_length++;
1148 
1149  return actual_length;
1150  }
1151 }
1152 
1153 /* Helper function, to simplify hid_read().
1154  This should be called with dev->mutex locked. */
1155 static int return_data(hid_device *dev, unsigned char *data, size_t length)
1156 {
1157  /* Copy the data out of the linked list item (rpt) into the
1158  return buffer (data), and delete the liked list item. */
1159  struct input_report *rpt = dev->input_reports;
1160  size_t len = (length < rpt->len)? length: rpt->len;
1161  if (data && len > 0)
1162  memcpy(data, rpt->data, len);
1163  dev->input_reports = rpt->next;
1164  free(rpt->data);
1165  free(rpt);
1166  return len;
1167 }
1168 
1169 static void cleanup_mutex(void *param)
1170 {
1171  hid_device *dev = (hid_device *)param;
1172  pthread_mutex_unlock(&dev->mutex);
1173 }
1174 
1175 
1176 int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
1177 {
1178  int bytes_read = -1;
1179 
1180 #if 0
1181  int transferred;
1182  int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
1183  LOG("transferred: %d\n", transferred);
1184  return transferred;
1185 #endif
1186 
1187  pthread_mutex_lock(&dev->mutex);
1188  pthread_cleanup_push(&cleanup_mutex, dev);
1189 
1190  /* There's an input report queued up. Return it. */
1191  if (dev->input_reports) {
1192  /* Return the first one */
1193  bytes_read = return_data(dev, data, length);
1194  goto ret;
1195  }
1196 
1197  if (dev->shutdown_thread) {
1198  /* This means the device has been disconnected.
1199  An error code of -1 should be returned. */
1200  bytes_read = -1;
1201  goto ret;
1202  }
1203 
1204  if (milliseconds == -1) {
1205  /* Blocking */
1206  while (!dev->input_reports && !dev->shutdown_thread) {
1207  pthread_cond_wait(&dev->condition, &dev->mutex);
1208  }
1209  if (dev->input_reports) {
1210  bytes_read = return_data(dev, data, length);
1211  }
1212  }
1213  else if (milliseconds > 0) {
1214  /* Non-blocking, but called with timeout. */
1215  int res;
1216  struct timespec ts;
1217  clock_gettime(CLOCK_REALTIME, &ts);
1218  ts.tv_sec += milliseconds / 1000;
1219  ts.tv_nsec += (milliseconds % 1000) * 1000000;
1220  if (ts.tv_nsec >= 1000000000L) {
1221  ts.tv_sec++;
1222  ts.tv_nsec -= 1000000000L;
1223  }
1224 
1225  while (!dev->input_reports && !dev->shutdown_thread) {
1226  res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
1227  if (res == 0) {
1228  if (dev->input_reports) {
1229  bytes_read = return_data(dev, data, length);
1230  break;
1231  }
1232 
1233  /* If we're here, there was a spurious wake up
1234  or the read thread was shutdown. Run the
1235  loop again (ie: don't break). */
1236  }
1237  else if (res == ETIMEDOUT) {
1238  /* Timed out. */
1239  bytes_read = 0;
1240  break;
1241  }
1242  else {
1243  /* Error. */
1244  bytes_read = -1;
1245  break;
1246  }
1247  }
1248  }
1249  else {
1250  /* Purely non-blocking */
1251  bytes_read = 0;
1252  }
1253 
1254 ret:
1255  pthread_mutex_unlock(&dev->mutex);
1256  pthread_cleanup_pop(0);
1257 
1258  return bytes_read;
1259 }
1260 
1261 int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
1262 {
1263  return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);
1264 }
1265 
1266 int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
1267 {
1268  dev->blocking = !nonblock;
1269 
1270  return 0;
1271 }
1272 
1273 
1274 int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
1275 {
1276  int res = -1;
1277  int skipped_report_id = 0;
1278  int report_number = data[0];
1279 
1280  if (report_number == 0x0) {
1281  data++;
1282  length--;
1283  skipped_report_id = 1;
1284  }
1285 
1286  res = libusb_control_transfer(dev->device_handle,
1287  LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
1288  0x09/*HID set_report*/,
1289  (3/*HID feature*/ << 8) | report_number,
1290  dev->interface,
1291  (unsigned char *)data, length,
1292  1000/*timeout millis*/);
1293 
1294  if (res < 0)
1295  return -1;
1296 
1297  /* Account for the report ID */
1298  if (skipped_report_id)
1299  length++;
1300 
1301  return length;
1302 }
1303 
1304 int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
1305 {
1306  int res = -1;
1307  int skipped_report_id = 0;
1308  int report_number = data[0];
1309 
1310  if (report_number == 0x0) {
1311  /* Offset the return buffer by 1, so that the report ID
1312  will remain in byte 0. */
1313  data++;
1314  length--;
1315  skipped_report_id = 1;
1316  }
1317  res = libusb_control_transfer(dev->device_handle,
1318  LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,
1319  0x01/*HID get_report*/,
1320  (3/*HID feature*/ << 8) | report_number,
1321  dev->interface,
1322  (unsigned char *)data, length,
1323  1000/*timeout millis*/);
1324 
1325  if (res < 0)
1326  return -1;
1327 
1328  if (skipped_report_id)
1329  res++;
1330 
1331  return res;
1332 }
1333 
1334 
1336 {
1337  if (!dev)
1338  return;
1339 
1340  /* Cause read_thread() to stop. */
1341  dev->shutdown_thread = 1;
1342  libusb_cancel_transfer(dev->transfer);
1343 
1344  /* Wait for read_thread() to end. */
1345  pthread_join(dev->thread, NULL);
1346 
1347  /* Clean up the Transfer objects allocated in read_thread(). */
1348  free(dev->transfer->buffer);
1349  libusb_free_transfer(dev->transfer);
1350 
1351  /* release the interface */
1352  libusb_release_interface(dev->device_handle, dev->interface);
1353 
1354  /* Close the handle */
1355  libusb_close(dev->device_handle);
1356 
1357  /* Clear out the queue of received reports. */
1358  pthread_mutex_lock(&dev->mutex);
1359  while (dev->input_reports) {
1360  return_data(dev, NULL, 0);
1361  }
1362  pthread_mutex_unlock(&dev->mutex);
1363 
1364  free_hid_device(dev);
1365 }
1366 
1367 
1368 int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
1369 {
1370  return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);
1371 }
1372 
1373 int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
1374 {
1375  return hid_get_indexed_string(dev, dev->product_index, string, maxlen);
1376 }
1377 
1378 int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
1379 {
1380  return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);
1381 }
1382 
1383 int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
1384 {
1385  wchar_t *str;
1386 
1387  str = get_usb_string(dev->device_handle, string_index);
1388  if (str) {
1389  wcsncpy(string, str, maxlen);
1390  string[maxlen-1] = L'\0';
1391  free(str);
1392  return 0;
1393  }
1394  else
1395  return -1;
1396 }
1397 
1398 
1399 HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
1400 {
1401  return NULL;
1402 }
1403 
1404 
1405 struct lang_map_entry {
1406  const char *name;
1407  const char *string_code;
1408  uint16_t usb_code;
1409 };
1410 
1411 #define LANG(name,code,usb_code) { name, code, usb_code }
1412 static struct lang_map_entry lang_map[] = {
1413  LANG("Afrikaans", "af", 0x0436),
1414  LANG("Albanian", "sq", 0x041C),
1415  LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
1416  LANG("Arabic - Bahrain", "ar_bh", 0x3C01),
1417  LANG("Arabic - Algeria", "ar_dz", 0x1401),
1418  LANG("Arabic - Egypt", "ar_eg", 0x0C01),
1419  LANG("Arabic - Iraq", "ar_iq", 0x0801),
1420  LANG("Arabic - Jordan", "ar_jo", 0x2C01),
1421  LANG("Arabic - Kuwait", "ar_kw", 0x3401),
1422  LANG("Arabic - Lebanon", "ar_lb", 0x3001),
1423  LANG("Arabic - Libya", "ar_ly", 0x1001),
1424  LANG("Arabic - Morocco", "ar_ma", 0x1801),
1425  LANG("Arabic - Oman", "ar_om", 0x2001),
1426  LANG("Arabic - Qatar", "ar_qa", 0x4001),
1427  LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),
1428  LANG("Arabic - Syria", "ar_sy", 0x2801),
1429  LANG("Arabic - Tunisia", "ar_tn", 0x1C01),
1430  LANG("Arabic - Yemen", "ar_ye", 0x2401),
1431  LANG("Armenian", "hy", 0x042B),
1432  LANG("Azeri - Latin", "az_az", 0x042C),
1433  LANG("Azeri - Cyrillic", "az_az", 0x082C),
1434  LANG("Basque", "eu", 0x042D),
1435  LANG("Belarusian", "be", 0x0423),
1436  LANG("Bulgarian", "bg", 0x0402),
1437  LANG("Catalan", "ca", 0x0403),
1438  LANG("Chinese - China", "zh_cn", 0x0804),
1439  LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),
1440  LANG("Chinese - Macau SAR", "zh_mo", 0x1404),
1441  LANG("Chinese - Singapore", "zh_sg", 0x1004),
1442  LANG("Chinese - Taiwan", "zh_tw", 0x0404),
1443  LANG("Croatian", "hr", 0x041A),
1444  LANG("Czech", "cs", 0x0405),
1445  LANG("Danish", "da", 0x0406),
1446  LANG("Dutch - Netherlands", "nl_nl", 0x0413),
1447  LANG("Dutch - Belgium", "nl_be", 0x0813),
1448  LANG("English - Australia", "en_au", 0x0C09),
1449  LANG("English - Belize", "en_bz", 0x2809),
1450  LANG("English - Canada", "en_ca", 0x1009),
1451  LANG("English - Caribbean", "en_cb", 0x2409),
1452  LANG("English - Ireland", "en_ie", 0x1809),
1453  LANG("English - Jamaica", "en_jm", 0x2009),
1454  LANG("English - New Zealand", "en_nz", 0x1409),
1455  LANG("English - Phillippines", "en_ph", 0x3409),
1456  LANG("English - Southern Africa", "en_za", 0x1C09),
1457  LANG("English - Trinidad", "en_tt", 0x2C09),
1458  LANG("English - Great Britain", "en_gb", 0x0809),
1459  LANG("English - United States", "en_us", 0x0409),
1460  LANG("Estonian", "et", 0x0425),
1461  LANG("Farsi", "fa", 0x0429),
1462  LANG("Finnish", "fi", 0x040B),
1463  LANG("Faroese", "fo", 0x0438),
1464  LANG("French - France", "fr_fr", 0x040C),
1465  LANG("French - Belgium", "fr_be", 0x080C),
1466  LANG("French - Canada", "fr_ca", 0x0C0C),
1467  LANG("French - Luxembourg", "fr_lu", 0x140C),
1468  LANG("French - Switzerland", "fr_ch", 0x100C),
1469  LANG("Gaelic - Ireland", "gd_ie", 0x083C),
1470  LANG("Gaelic - Scotland", "gd", 0x043C),
1471  LANG("German - Germany", "de_de", 0x0407),
1472  LANG("German - Austria", "de_at", 0x0C07),
1473  LANG("German - Liechtenstein", "de_li", 0x1407),
1474  LANG("German - Luxembourg", "de_lu", 0x1007),
1475  LANG("German - Switzerland", "de_ch", 0x0807),
1476  LANG("Greek", "el", 0x0408),
1477  LANG("Hebrew", "he", 0x040D),
1478  LANG("Hindi", "hi", 0x0439),
1479  LANG("Hungarian", "hu", 0x040E),
1480  LANG("Icelandic", "is", 0x040F),
1481  LANG("Indonesian", "id", 0x0421),
1482  LANG("Italian - Italy", "it_it", 0x0410),
1483  LANG("Italian - Switzerland", "it_ch", 0x0810),
1484  LANG("Japanese", "ja", 0x0411),
1485  LANG("Korean", "ko", 0x0412),
1486  LANG("Latvian", "lv", 0x0426),
1487  LANG("Lithuanian", "lt", 0x0427),
1488  LANG("F.Y.R.O. Macedonia", "mk", 0x042F),
1489  LANG("Malay - Malaysia", "ms_my", 0x043E),
1490  LANG("Malay – Brunei", "ms_bn", 0x083E),
1491  LANG("Maltese", "mt", 0x043A),
1492  LANG("Marathi", "mr", 0x044E),
1493  LANG("Norwegian - Bokml", "no_no", 0x0414),
1494  LANG("Norwegian - Nynorsk", "no_no", 0x0814),
1495  LANG("Polish", "pl", 0x0415),
1496  LANG("Portuguese - Portugal", "pt_pt", 0x0816),
1497  LANG("Portuguese - Brazil", "pt_br", 0x0416),
1498  LANG("Raeto-Romance", "rm", 0x0417),
1499  LANG("Romanian - Romania", "ro", 0x0418),
1500  LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),
1501  LANG("Russian", "ru", 0x0419),
1502  LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),
1503  LANG("Sanskrit", "sa", 0x044F),
1504  LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),
1505  LANG("Serbian - Latin", "sr_sp", 0x081A),
1506  LANG("Setsuana", "tn", 0x0432),
1507  LANG("Slovenian", "sl", 0x0424),
1508  LANG("Slovak", "sk", 0x041B),
1509  LANG("Sorbian", "sb", 0x042E),
1510  LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),
1511  LANG("Spanish - Argentina", "es_ar", 0x2C0A),
1512  LANG("Spanish - Bolivia", "es_bo", 0x400A),
1513  LANG("Spanish - Chile", "es_cl", 0x340A),
1514  LANG("Spanish - Colombia", "es_co", 0x240A),
1515  LANG("Spanish - Costa Rica", "es_cr", 0x140A),
1516  LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),
1517  LANG("Spanish - Ecuador", "es_ec", 0x300A),
1518  LANG("Spanish - Guatemala", "es_gt", 0x100A),
1519  LANG("Spanish - Honduras", "es_hn", 0x480A),
1520  LANG("Spanish - Mexico", "es_mx", 0x080A),
1521  LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),
1522  LANG("Spanish - Panama", "es_pa", 0x180A),
1523  LANG("Spanish - Peru", "es_pe", 0x280A),
1524  LANG("Spanish - Puerto Rico", "es_pr", 0x500A),
1525  LANG("Spanish - Paraguay", "es_py", 0x3C0A),
1526  LANG("Spanish - El Salvador", "es_sv", 0x440A),
1527  LANG("Spanish - Uruguay", "es_uy", 0x380A),
1528  LANG("Spanish - Venezuela", "es_ve", 0x200A),
1529  LANG("Southern Sotho", "st", 0x0430),
1530  LANG("Swahili", "sw", 0x0441),
1531  LANG("Swedish - Sweden", "sv_se", 0x041D),
1532  LANG("Swedish - Finland", "sv_fi", 0x081D),
1533  LANG("Tamil", "ta", 0x0449),
1534  LANG("Tatar", "tt", 0X0444),
1535  LANG("Thai", "th", 0x041E),
1536  LANG("Turkish", "tr", 0x041F),
1537  LANG("Tsonga", "ts", 0x0431),
1538  LANG("Ukrainian", "uk", 0x0422),
1539  LANG("Urdu", "ur", 0x0420),
1540  LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),
1541  LANG("Uzbek – Latin", "uz_uz", 0x0443),
1542  LANG("Vietnamese", "vi", 0x042A),
1543  LANG("Xhosa", "xh", 0x0434),
1544  LANG("Yiddish", "yi", 0x043D),
1545  LANG("Zulu", "zu", 0x0435),
1546  LANG(NULL, NULL, 0x0),
1547 };
1548 
1549 uint16_t get_usb_code_for_current_locale(void)
1550 {
1551  char *locale;
1552  char search_string[64];
1553  char *ptr;
1554  struct lang_map_entry *lang;
1555 
1556  /* Get the current locale. */
1557  locale = setlocale(0, NULL);
1558  if (!locale)
1559  return 0x0;
1560 
1561  /* Make a copy of the current locale string. */
1562  strncpy(search_string, locale, sizeof(search_string));
1563  search_string[sizeof(search_string)-1] = '\0';
1564 
1565  /* Chop off the encoding part, and make it lower case. */
1566  ptr = search_string;
1567  while (*ptr) {
1568  *ptr = tolower(*ptr);
1569  if (*ptr == '.') {
1570  *ptr = '\0';
1571  break;
1572  }
1573  ptr++;
1574  }
1575 
1576  /* Find the entry which matches the string code of our locale. */
1577  lang = lang_map;
1578  while (lang->string_code) {
1579  if (!strcmp(lang->string_code, search_string)) {
1580  return lang->usb_code;
1581  }
1582  lang++;
1583  }
1584 
1585  /* There was no match. Find with just the language only. */
1586  /* Chop off the variant. Chop it off at the '_'. */
1587  ptr = search_string;
1588  while (*ptr) {
1589  *ptr = tolower(*ptr);
1590  if (*ptr == '_') {
1591  *ptr = '\0';
1592  break;
1593  }
1594  ptr++;
1595  }
1596 
1597 #if 0 /* TODO: Do we need this? */
1598  /* Find the entry which matches the string code of our language. */
1599  lang = lang_map;
1600  while (lang->string_code) {
1601  if (!strcmp(lang->string_code, search_string)) {
1602  return lang->usb_code;
1603  }
1604  lang++;
1605  }
1606 #endif
1607 
1608  /* Found nothing. */
1609  return 0x0;
1610 }
1611 
1612 #if defined(__cplusplus) && !defined(NAMESPACE)
1613 }
1614 #endif
1615 
1616 #ifdef NAMESPACE
1617 }
1618 #endif
1619 
1620 #endif /* SDL_JOYSTICK_HIDAPI */
#define NAMESPACE
Definition: hidusb.cpp:2
HID_API_EXPORT const wchar_t *HID_API_CALL hid_error(hid_device *device)
Get a string describing the last error which occurred.
int interface_number
Definition: hidapi.h:79
unsigned short uint16_t
GLuint GLuint GLsizei count
Definition: SDL_opengl.h:1571
#define HID_API_EXPORT
Definition: hidapi.h:36
void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
Free an enumeration Linked List.
SDL_EventEntry * free
Definition: SDL_events.c:82
GLint GLenum GLsizei GLsizei GLsizei GLint GLsizei const GLvoid * data
Definition: SDL_opengl.h:1974
static SDL_mutex * mutex
Definition: testlock.c:23
wchar_t * manufacturer_string
Definition: hidapi.h:66
char * path
Definition: hidapi.h:55
int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length)
Write an Output report to a HID device.
int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen)
Get a string from a HID device, based on its string index.
GLenum GLsizei len
GLuint const GLchar * name
GLuint res
static SDL_AudioDeviceID device
Definition: loopwave.c:37
int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *device, unsigned char *data, size_t length, int milliseconds)
Read an Input report from a HID device with timeout.
struct hid_device_info * next
Definition: hidapi.h:82
int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock)
Set the device handle to be non-blocking.
GLsizeiptr const void GLenum usage
void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device)
Close a HID device.
int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen)
Get The Product String from a HID device.
GLuint64 key
Definition: gl2ext.h:2192
unsigned short product_id
Definition: hidapi.h:59
EGLImageKHR EGLint EGLint * handle
Definition: eglext.h:937
SDL_PRINTF_FORMAT_STRING const char int SDL_PRINTF_FORMAT_STRING const char int SDL_PRINTF_FORMAT_STRING const char int SDL_PRINTF_FORMAT_STRING const char const char SDL_SCANF_FORMAT_STRING const char return SDL_ThreadFunction const char void return Uint32 return Uint32 SDL_AssertionHandler void SDL_SpinLock SDL_atomic_t int int return SDL_atomic_t return void void void return void return int return SDL_AudioSpec SDL_AudioSpec return int int return return int SDL_RWops int SDL_AudioSpec Uint8 ** d
wchar_t * serial_number
Definition: hidapi.h:61
int HID_API_EXPORT HID_API_CALL hid_exit(void)
Finalize the HIDAPI library.
return Display return Display Bool Bool int int int return Display XEvent Bool(*) XPointer return Display return Display Drawable _Xconst char unsigned int unsigned int return Display Pixmap Pixmap XColor XColor unsigned int unsigned int return Display _Xconst char char int char return Display Visual unsigned int int int char unsigned int unsigned int int in j)
Definition: SDL_x11sym.h:50
unsigned short vendor_id
Definition: hidapi.h:57
HID_API_EXPORT hid_device *HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number...
#define strdup
int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length)
Get a feature report from a HID device.
wchar_t * product_string
Definition: hidapi.h:68
unsigned short usage
Definition: hidapi.h:74
GLenum GLuint GLenum GLsizei const GLchar * buf
int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen)
Get The Serial Number String from a HID device.
GLsizeiptr size
struct hid_device_ hid_device
Definition: hidapi.h:50
return Display return Display Bool Bool int int int return Display XEvent Bool(*) XPointer return Display return Display Drawable _Xconst char unsigned int unsigned int return Display Pixmap Pixmap XColor XColor unsigned int unsigned int return Display _Xconst char char int char return Display Visual unsigned int int int char unsigned int unsigned int in i)
Definition: SDL_x11sym.h:50
#define HID_API_EXPORT_CALL
Definition: hidapi.h:40
#define NULL
Definition: begin_code.h:167
unsigned char uint8_t
unsigned int uint32_t
int HID_API_EXPORT HID_API_CALL hid_init(void)
Initialize the HIDAPI library.
unsigned short usage_page
Definition: hidapi.h:71
#define memcpy
Definition: SDL_malloc.c:630
GLenum condition
GLuint GLfloat x0
HID_API_EXPORT hid_device *HID_API_CALL hid_open_path(const char *path, int bExclusive)
Open a HID device by its path name.
return Display return Display Bool Bool int int int return Display XEvent Bool(*) XPointer return Display return Display Drawable _Xconst char unsigned int unsigned int return Display Pixmap Pixmap XColor XColor unsigned int unsigned int return Display _Xconst char char int char return Display Visual unsigned int int int char unsigned int unsigned int int int return Display Window Cursor return Display Window return Display Drawable GC int int unsigned int unsigned int return Display Drawable GC int int _Xconst char int return Display Drawable GC int int unsigned int unsigned int return Display return Display Cursor return Display GC return XModifierKeymap return char Display Window int return Display return Display Atom return Display Window XWindowAttributes return Display Window return Display XEvent Bool(*) XPointer return Display Window Bool unsigned int int int Window Cursor Time return Display Window int return KeySym return Display _Xconst char Bool return Display _Xconst char return XKeyEvent char int KeySym XComposeStatus return Display int int int XVisualInfo return Display Window int int return _Xconst char return Display XEvent return Display Drawable GC XImage int int int int unsigned int unsigned int return Display Window Window Window int int int int unsigned int return Display Window Window int int return Display Window unsigned int unsigned int return Display Window Bool long XEvent return Display GC unsigned long return Display Window int Time return Display Window Window return Display Window unsigned long return Display Window XSizeHints Display Colormap XColor int return char int XTextProperty return XFontStruct _Xconst char int int int int XCharStruct return Display Window return Display Time return Display Colormap return Display Window Window int int unsigned int unsigned int int int return Display Window int return XExtensionInfo Display char XExtensionHooks int XPointer return XExtensionInfo XExtensionInfo Display return Display return Display unsigned long Display GC Display char long Display xReply int Bool return Display Bool return Display int SDL_X11_XESetEventToWireRetType return Display Window Window Window Window unsigned int return Display XShmSegmentInfo return Display Drawable GC XImage int int int int unsigned int unsigned int Boo k)
Definition: SDL_x11sym.h:213
GLsizei const GLchar *const * path
int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length)
Send a Feature report to the device.
int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen)
Get The Manufacturer String from a HID device.
GLuint GLsizei GLsizei * length
GLfloat param
struct hid_device_info HID_API_EXPORT *HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
Enumerate the HID Devices.
#define HID_API_CALL
Definition: hidapi.h:37
#define malloc
Definition: SDL_qsort.c:47
unsigned short release_number
Definition: hidapi.h:64
int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length)
Read an Input report from a HID device.