hid.c 60 KB

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