hid.c 38 KB

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