hid.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /*******************************************************
  2. HIDAPI - Multi-Platform library for
  3. communication with HID devices.
  4. Alan Ott
  5. Signal 11 Software
  6. 8/22/2009
  7. Copyright 2009, 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. #include "../../SDL_internal.h"
  19. #ifdef SDL_JOYSTICK_HIDAPI
  20. #include <windows.h>
  21. #if 0 /* can cause redefinition errors on some toolchains */
  22. #ifdef __MINGW32__
  23. #include <ntdef.h>
  24. #include <winbase.h>
  25. #endif
  26. #ifdef __CYGWIN__
  27. #include <ntdef.h>
  28. #define _wcsdup wcsdup
  29. #endif
  30. #endif /* */
  31. #ifndef _NTDEF_
  32. typedef LONG NTSTATUS;
  33. #endif
  34. /* SDL C runtime functions */
  35. #include "SDL_stdinc.h"
  36. #define calloc SDL_calloc
  37. #define free SDL_free
  38. #define malloc SDL_malloc
  39. #define memcpy SDL_memcpy
  40. #define memset SDL_memset
  41. #define strcmp SDL_strcmp
  42. #define strlen SDL_strlen
  43. #define strncpy SDL_strlcpy
  44. #define strstr SDL_strstr
  45. #define strtol SDL_strtol
  46. #define wcscmp SDL_wcscmp
  47. #define _wcsdup SDL_wcsdup
  48. /* The maximum number of characters that can be passed into the
  49. HidD_Get*String() functions without it failing.*/
  50. #define MAX_STRING_WCHARS 0xFFF
  51. /*#define HIDAPI_USE_DDK*/
  52. /* The timeout in milliseconds for waiting on WriteFile to
  53. complete in hid_write. The longest observed time to do a output
  54. report that we've seen is ~200-250ms so let's double that */
  55. #define HID_WRITE_TIMEOUT_MILLISECONDS 500
  56. /* We will only enumerate devices that match these usages */
  57. #define USAGE_PAGE_GENERIC_DESKTOP 0x0001
  58. #define USAGE_JOYSTICK 0x0004
  59. #define USAGE_GAMEPAD 0x0005
  60. #define USAGE_MULTIAXISCONTROLLER 0x0008
  61. #define USB_VENDOR_VALVE 0x28de
  62. #ifdef __cplusplus
  63. extern "C" {
  64. #endif
  65. #include <setupapi.h>
  66. #include <winioctl.h>
  67. #ifdef HIDAPI_USE_DDK
  68. #include <hidsdi.h>
  69. #endif
  70. /* Copied from inc/ddk/hidclass.h, part of the Windows DDK. */
  71. #define HID_OUT_CTL_CODE(id) \
  72. CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
  73. #define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100)
  74. #ifdef __cplusplus
  75. } /* extern "C" */
  76. #endif
  77. #include <stdio.h>
  78. #include <stdlib.h>
  79. #include "../hidapi/hidapi.h"
  80. #undef MIN
  81. #define MIN(x,y) ((x) < (y)? (x): (y))
  82. #ifdef _MSC_VER
  83. /* Thanks Microsoft, but I know how to use strncpy(). */
  84. #pragma warning(disable:4996)
  85. #endif
  86. #ifdef __cplusplus
  87. extern "C" {
  88. #endif
  89. #ifndef HIDAPI_USE_DDK
  90. /* Since we're not building with the DDK, and the HID header
  91. files aren't part of the SDK, we have to define all this
  92. stuff here. In lookup_functions(), the function pointers
  93. defined below are set. */
  94. typedef struct _HIDD_ATTRIBUTES{
  95. ULONG Size;
  96. USHORT VendorID;
  97. USHORT ProductID;
  98. USHORT VersionNumber;
  99. } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
  100. typedef USHORT USAGE;
  101. typedef struct _HIDP_CAPS {
  102. USAGE Usage;
  103. USAGE UsagePage;
  104. USHORT InputReportByteLength;
  105. USHORT OutputReportByteLength;
  106. USHORT FeatureReportByteLength;
  107. USHORT Reserved[17];
  108. USHORT fields_not_used_by_hidapi[10];
  109. } HIDP_CAPS, *PHIDP_CAPS;
  110. typedef void* PHIDP_PREPARSED_DATA;
  111. #define HIDP_STATUS_SUCCESS 0x110000
  112. typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib);
  113. typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len);
  114. typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
  115. typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
  116. typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length);
  117. typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length);
  118. typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len);
  119. typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, PHIDP_PREPARSED_DATA *preparsed_data);
  120. typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(PHIDP_PREPARSED_DATA preparsed_data);
  121. typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS *caps);
  122. typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers);
  123. typedef BOOLEAN(__stdcall *HidD_SetOutputReport_ )(HANDLE handle, PVOID buffer, ULONG buffer_len);
  124. static HidD_GetAttributes_ HidD_GetAttributes;
  125. static HidD_GetSerialNumberString_ HidD_GetSerialNumberString;
  126. static HidD_GetManufacturerString_ HidD_GetManufacturerString;
  127. static HidD_GetProductString_ HidD_GetProductString;
  128. static HidD_SetFeature_ HidD_SetFeature;
  129. static HidD_GetFeature_ HidD_GetFeature;
  130. static HidD_GetIndexedString_ HidD_GetIndexedString;
  131. static HidD_GetPreparsedData_ HidD_GetPreparsedData;
  132. static HidD_FreePreparsedData_ HidD_FreePreparsedData;
  133. static HidP_GetCaps_ HidP_GetCaps;
  134. static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers;
  135. static HidD_SetOutputReport_ HidD_SetOutputReport;
  136. static HMODULE lib_handle = NULL;
  137. static BOOLEAN initialized = FALSE;
  138. #endif /* HIDAPI_USE_DDK */
  139. struct hid_device_ {
  140. HANDLE device_handle;
  141. BOOL blocking;
  142. USHORT output_report_length;
  143. size_t input_report_length;
  144. void *last_error_str;
  145. DWORD last_error_num;
  146. BOOL read_pending;
  147. char *read_buf;
  148. OVERLAPPED ol;
  149. OVERLAPPED write_ol;
  150. };
  151. static hid_device *new_hid_device()
  152. {
  153. hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
  154. dev->device_handle = INVALID_HANDLE_VALUE;
  155. dev->blocking = TRUE;
  156. dev->output_report_length = 0;
  157. dev->input_report_length = 0;
  158. dev->last_error_str = NULL;
  159. dev->last_error_num = 0;
  160. dev->read_pending = FALSE;
  161. dev->read_buf = NULL;
  162. memset(&dev->ol, 0, sizeof(dev->ol));
  163. dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL);
  164. memset(&dev->write_ol, 0, sizeof(dev->write_ol));
  165. dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL);
  166. return dev;
  167. }
  168. static void free_hid_device(hid_device *dev)
  169. {
  170. CloseHandle(dev->ol.hEvent);
  171. CloseHandle(dev->write_ol.hEvent);
  172. CloseHandle(dev->device_handle);
  173. LocalFree(dev->last_error_str);
  174. free(dev->read_buf);
  175. free(dev);
  176. }
  177. static void register_error(hid_device *device, const char *op)
  178. {
  179. WCHAR *ptr, *msg;
  180. DWORD count = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  181. FORMAT_MESSAGE_FROM_SYSTEM |
  182. FORMAT_MESSAGE_IGNORE_INSERTS,
  183. NULL,
  184. GetLastError(),
  185. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  186. (LPWSTR)&msg, 0/*sz*/,
  187. NULL);
  188. if (!count)
  189. return;
  190. /* Get rid of the CR and LF that FormatMessage() sticks at the
  191. end of the message. Thanks Microsoft! */
  192. ptr = msg;
  193. while (*ptr) {
  194. if (*ptr == '\r') {
  195. *ptr = 0x0000;
  196. break;
  197. }
  198. ptr++;
  199. }
  200. /* Store the message off in the Device entry so that
  201. the hid_error() function can pick it up. */
  202. LocalFree(device->last_error_str);
  203. device->last_error_str = msg;
  204. }
  205. #ifndef HIDAPI_USE_DDK
  206. static int lookup_functions()
  207. {
  208. lib_handle = LoadLibraryA("hid.dll");
  209. if (lib_handle) {
  210. #define RESOLVE(x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) return -1;
  211. RESOLVE(HidD_GetAttributes);
  212. RESOLVE(HidD_GetSerialNumberString);
  213. RESOLVE(HidD_GetManufacturerString);
  214. RESOLVE(HidD_GetProductString);
  215. RESOLVE(HidD_SetFeature);
  216. RESOLVE(HidD_GetFeature);
  217. RESOLVE(HidD_GetIndexedString);
  218. RESOLVE(HidD_GetPreparsedData);
  219. RESOLVE(HidD_FreePreparsedData);
  220. RESOLVE(HidP_GetCaps);
  221. RESOLVE(HidD_SetNumInputBuffers);
  222. RESOLVE(HidD_SetOutputReport);
  223. #undef RESOLVE
  224. }
  225. else
  226. return -1;
  227. return 0;
  228. }
  229. #endif
  230. static HANDLE open_device(const char *path, BOOL enumerate, BOOL bExclusive )
  231. {
  232. HANDLE handle;
  233. // Opening with access 0 causes keyboards to stop responding in some system configurations
  234. // http://steamcommunity.com/discussions/forum/1/1843493219428923893
  235. // Thanks to co-wie (Ka-wei Low <kawei@mac.com>) for help narrowing down the problem on his system
  236. //DWORD desired_access = (enumerate)? 0: (GENERIC_WRITE | GENERIC_READ);
  237. DWORD desired_access = ( GENERIC_WRITE | GENERIC_READ );
  238. DWORD share_mode = bExclusive ? 0 : ( FILE_SHARE_READ | FILE_SHARE_WRITE );
  239. handle = CreateFileA(path,
  240. desired_access,
  241. share_mode,
  242. NULL,
  243. OPEN_EXISTING,
  244. FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/
  245. 0);
  246. return handle;
  247. }
  248. int HID_API_EXPORT hid_init(void)
  249. {
  250. #ifndef HIDAPI_USE_DDK
  251. if (!initialized) {
  252. if (lookup_functions() < 0) {
  253. hid_exit();
  254. return -1;
  255. }
  256. initialized = TRUE;
  257. }
  258. #endif
  259. return 0;
  260. }
  261. int HID_API_EXPORT hid_exit(void)
  262. {
  263. #ifndef HIDAPI_USE_DDK
  264. if (lib_handle)
  265. FreeLibrary(lib_handle);
  266. lib_handle = NULL;
  267. initialized = FALSE;
  268. #endif
  269. return 0;
  270. }
  271. int hid_blacklist(unsigned short vendor_id, unsigned short product_id)
  272. {
  273. size_t i;
  274. static const struct { unsigned short vid; unsigned short pid; } known_bad[] = {
  275. /* Causes deadlock when asking for device details... */
  276. { 0x1B1C, 0x1B3D }, /* Corsair Gaming keyboard */
  277. { 0x1532, 0x0109 }, /* Razer Lycosa Gaming keyboard */
  278. { 0x1532, 0x010B }, /* Razer Arctosa Gaming keyboard */
  279. { 0x045E, 0x0822 }, /* Microsoft Precision Mouse */
  280. /* Turns into an Android controller when enumerated... */
  281. { 0x0738, 0x2217 } /* SPEEDLINK COMPETITION PRO */
  282. };
  283. for (i = 0; i < (sizeof(known_bad)/sizeof(known_bad[0])); i++) {
  284. if ((vendor_id == known_bad[i].vid) && (product_id == known_bad[i].pid)) {
  285. return 1;
  286. }
  287. }
  288. return 0;
  289. }
  290. struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
  291. {
  292. BOOL res;
  293. struct hid_device_info *root = NULL; /* return object */
  294. struct hid_device_info *cur_dev = NULL;
  295. /* Windows objects for interacting with the driver. */
  296. GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} };
  297. SP_DEVINFO_DATA devinfo_data;
  298. SP_DEVICE_INTERFACE_DATA device_interface_data;
  299. SP_DEVICE_INTERFACE_DETAIL_DATA_A *device_interface_detail_data = NULL;
  300. HDEVINFO device_info_set = INVALID_HANDLE_VALUE;
  301. int device_index = 0;
  302. if (hid_init() < 0)
  303. return NULL;
  304. /* Initialize the Windows objects. */
  305. memset(&devinfo_data, 0x0, sizeof(devinfo_data));
  306. devinfo_data.cbSize = sizeof(SP_DEVINFO_DATA);
  307. device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  308. /* Get information for all the devices belonging to the HID class. */
  309. device_info_set = SetupDiGetClassDevsA(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  310. /* Iterate over each device in the HID class, looking for the right one. */
  311. for (;;) {
  312. HANDLE write_handle = INVALID_HANDLE_VALUE;
  313. DWORD required_size = 0;
  314. HIDD_ATTRIBUTES attrib;
  315. res = SetupDiEnumDeviceInterfaces(device_info_set,
  316. NULL,
  317. &InterfaceClassGuid,
  318. device_index,
  319. &device_interface_data);
  320. if (!res) {
  321. /* A return of FALSE from this function means that
  322. there are no more devices. */
  323. break;
  324. }
  325. /* Call with 0-sized detail size, and let the function
  326. tell us how long the detail struct needs to be. The
  327. size is put in &required_size. */
  328. res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
  329. &device_interface_data,
  330. NULL,
  331. 0,
  332. &required_size,
  333. NULL);
  334. /* Allocate a long enough structure for device_interface_detail_data. */
  335. device_interface_detail_data = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) malloc(required_size);
  336. device_interface_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
  337. /* Get the detailed data for this device. The detail data gives us
  338. the device path for this device, which is then passed into
  339. CreateFile() to get a handle to the device. */
  340. res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
  341. &device_interface_data,
  342. device_interface_detail_data,
  343. required_size,
  344. NULL,
  345. NULL);
  346. if (!res) {
  347. /* register_error(dev, "Unable to call SetupDiGetDeviceInterfaceDetail");
  348. Continue to the next device. */
  349. goto cont;
  350. }
  351. /* XInput devices don't get real HID reports and are better handled by the raw input driver */
  352. if (strstr(device_interface_detail_data->DevicePath, "&ig_") != NULL) {
  353. goto cont;
  354. }
  355. /* Make sure this device is of Setup Class "HIDClass" and has a
  356. driver bound to it. */
  357. /* In the main HIDAPI tree this is a loop which will erroneously open
  358. devices that aren't HID class. Please preserve this delta if we ever
  359. update to take new changes */
  360. {
  361. char driver_name[256];
  362. /* Populate devinfo_data. This function will return failure
  363. when there are no more interfaces left. */
  364. res = SetupDiEnumDeviceInfo(device_info_set, device_index, &devinfo_data);
  365. if (!res)
  366. goto cont;
  367. res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
  368. SPDRP_CLASS, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
  369. if (!res)
  370. goto cont;
  371. if (strcmp(driver_name, "HIDClass") == 0) {
  372. /* See if there's a driver bound. */
  373. res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
  374. SPDRP_DRIVER, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
  375. if (!res)
  376. goto cont;
  377. }
  378. else
  379. {
  380. goto cont;
  381. }
  382. }
  383. //wprintf(L"HandleName: %s\n", device_interface_detail_data->DevicePath);
  384. /* Open a handle to the device */
  385. write_handle = open_device(device_interface_detail_data->DevicePath, TRUE, FALSE);
  386. /* Check validity of write_handle. */
  387. if (write_handle == INVALID_HANDLE_VALUE) {
  388. /* Unable to open the device. */
  389. //register_error(dev, "CreateFile");
  390. goto cont;
  391. }
  392. /* Get the Vendor ID and Product ID for this device. */
  393. attrib.Size = sizeof(HIDD_ATTRIBUTES);
  394. HidD_GetAttributes(write_handle, &attrib);
  395. //wprintf(L"Product/Vendor: %x %x\n", attrib.ProductID, attrib.VendorID);
  396. /* Check the VID/PID to see if we should add this
  397. device to the enumeration list. */
  398. if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) &&
  399. (product_id == 0x0 || attrib.ProductID == product_id) &&
  400. !hid_blacklist(attrib.VendorID, attrib.ProductID)) {
  401. #define WSTR_LEN 512
  402. const char *str;
  403. struct hid_device_info *tmp;
  404. PHIDP_PREPARSED_DATA pp_data = NULL;
  405. HIDP_CAPS caps;
  406. BOOLEAN hidp_res;
  407. NTSTATUS nt_res;
  408. wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */
  409. size_t len;
  410. /* Get the Usage Page and Usage for this device. */
  411. hidp_res = HidD_GetPreparsedData(write_handle, &pp_data);
  412. if (hidp_res) {
  413. nt_res = HidP_GetCaps(pp_data, &caps);
  414. HidD_FreePreparsedData(pp_data);
  415. if (nt_res != HIDP_STATUS_SUCCESS) {
  416. goto cont_close;
  417. }
  418. }
  419. else {
  420. goto cont_close;
  421. }
  422. /* SDL Modification: Ignore the device if it's not a gamepad. This limits compatibility
  423. risk from devices that may respond poorly to our string queries below. */
  424. if (attrib.VendorID != USB_VENDOR_VALVE) {
  425. if (caps.UsagePage != USAGE_PAGE_GENERIC_DESKTOP) {
  426. goto cont_close;
  427. }
  428. if (caps.Usage != USAGE_JOYSTICK && caps.Usage != USAGE_GAMEPAD && caps.Usage != USAGE_MULTIAXISCONTROLLER) {
  429. goto cont_close;
  430. }
  431. }
  432. /* VID/PID match. Create the record. */
  433. tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
  434. if (cur_dev) {
  435. cur_dev->next = tmp;
  436. }
  437. else {
  438. root = tmp;
  439. }
  440. cur_dev = tmp;
  441. /* Fill out the record */
  442. cur_dev->usage_page = caps.UsagePage;
  443. cur_dev->usage = caps.Usage;
  444. cur_dev->next = NULL;
  445. str = device_interface_detail_data->DevicePath;
  446. if (str) {
  447. len = strlen(str);
  448. cur_dev->path = (char*) calloc(len+1, sizeof(char));
  449. strncpy(cur_dev->path, str, len+1);
  450. cur_dev->path[len] = '\0';
  451. }
  452. else
  453. cur_dev->path = NULL;
  454. /* Serial Number */
  455. hidp_res = HidD_GetSerialNumberString(write_handle, wstr, sizeof(wstr));
  456. wstr[WSTR_LEN-1] = 0x0000;
  457. if (hidp_res) {
  458. cur_dev->serial_number = _wcsdup(wstr);
  459. }
  460. /* Manufacturer String */
  461. hidp_res = HidD_GetManufacturerString(write_handle, wstr, sizeof(wstr));
  462. wstr[WSTR_LEN-1] = 0x0000;
  463. if (hidp_res) {
  464. cur_dev->manufacturer_string = _wcsdup(wstr);
  465. }
  466. /* Product String */
  467. hidp_res = HidD_GetProductString(write_handle, wstr, sizeof(wstr));
  468. wstr[WSTR_LEN-1] = 0x0000;
  469. if (hidp_res) {
  470. cur_dev->product_string = _wcsdup(wstr);
  471. }
  472. /* VID/PID */
  473. cur_dev->vendor_id = attrib.VendorID;
  474. cur_dev->product_id = attrib.ProductID;
  475. /* Release Number */
  476. cur_dev->release_number = attrib.VersionNumber;
  477. /* Interface Number. It can sometimes be parsed out of the path
  478. on Windows if a device has multiple interfaces. See
  479. http://msdn.microsoft.com/en-us/windows/hardware/gg487473 or
  480. search for "Hardware IDs for HID Devices" at MSDN. If it's not
  481. in the path, it's set to -1. */
  482. cur_dev->interface_number = -1;
  483. if (cur_dev->path) {
  484. char *interface_component = strstr(cur_dev->path, "&mi_");
  485. if (interface_component) {
  486. char *hex_str = interface_component + 4;
  487. char *endptr = NULL;
  488. cur_dev->interface_number = strtol(hex_str, &endptr, 16);
  489. if (endptr == hex_str) {
  490. /* The parsing failed. Set interface_number to -1. */
  491. cur_dev->interface_number = -1;
  492. }
  493. }
  494. }
  495. }
  496. cont_close:
  497. CloseHandle(write_handle);
  498. cont:
  499. /* We no longer need the detail data. It can be freed */
  500. free(device_interface_detail_data);
  501. device_index++;
  502. }
  503. /* Close the device information handle. */
  504. SetupDiDestroyDeviceInfoList(device_info_set);
  505. return root;
  506. }
  507. void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
  508. {
  509. /* TODO: Merge this with the Linux version. This function is platform-independent. */
  510. struct hid_device_info *d = devs;
  511. while (d) {
  512. struct hid_device_info *next = d->next;
  513. free(d->path);
  514. free(d->serial_number);
  515. free(d->manufacturer_string);
  516. free(d->product_string);
  517. free(d);
  518. d = next;
  519. }
  520. }
  521. HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
  522. {
  523. /* TODO: Merge this functions with the Linux version. This function should be platform independent. */
  524. struct hid_device_info *devs, *cur_dev;
  525. const char *path_to_open = NULL;
  526. hid_device *handle = NULL;
  527. devs = hid_enumerate(vendor_id, product_id);
  528. cur_dev = devs;
  529. while (cur_dev) {
  530. if (cur_dev->vendor_id == vendor_id &&
  531. cur_dev->product_id == product_id) {
  532. if (serial_number) {
  533. if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
  534. path_to_open = cur_dev->path;
  535. break;
  536. }
  537. }
  538. else {
  539. path_to_open = cur_dev->path;
  540. break;
  541. }
  542. }
  543. cur_dev = cur_dev->next;
  544. }
  545. if (path_to_open) {
  546. /* Open the device */
  547. handle = hid_open_path(path_to_open, 0);
  548. }
  549. hid_free_enumeration(devs);
  550. return handle;
  551. }
  552. HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path, int bExclusive)
  553. {
  554. hid_device *dev;
  555. HIDP_CAPS caps;
  556. PHIDP_PREPARSED_DATA pp_data = NULL;
  557. BOOLEAN res;
  558. NTSTATUS nt_res;
  559. if (hid_init() < 0) {
  560. return NULL;
  561. }
  562. dev = new_hid_device();
  563. /* Open a handle to the device */
  564. dev->device_handle = open_device(path, FALSE, bExclusive);
  565. /* Check validity of write_handle. */
  566. if (dev->device_handle == INVALID_HANDLE_VALUE) {
  567. /* Unable to open the device. */
  568. register_error(dev, "CreateFile");
  569. goto err;
  570. }
  571. /* Set the Input Report buffer size to 64 reports. */
  572. res = HidD_SetNumInputBuffers(dev->device_handle, 64);
  573. if (!res) {
  574. register_error(dev, "HidD_SetNumInputBuffers");
  575. goto err;
  576. }
  577. /* Get the Input Report length for the device. */
  578. res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
  579. if (!res) {
  580. register_error(dev, "HidD_GetPreparsedData");
  581. goto err;
  582. }
  583. nt_res = HidP_GetCaps(pp_data, &caps);
  584. if (nt_res != HIDP_STATUS_SUCCESS) {
  585. register_error(dev, "HidP_GetCaps");
  586. goto err_pp_data;
  587. }
  588. dev->output_report_length = caps.OutputReportByteLength;
  589. dev->input_report_length = caps.InputReportByteLength;
  590. HidD_FreePreparsedData(pp_data);
  591. dev->read_buf = (char*) malloc(dev->input_report_length);
  592. return dev;
  593. err_pp_data:
  594. HidD_FreePreparsedData(pp_data);
  595. err:
  596. free_hid_device(dev);
  597. return NULL;
  598. }
  599. int HID_API_EXPORT HID_API_CALL hid_write_output_report(hid_device *dev, const unsigned char *data, size_t length)
  600. {
  601. BOOL res;
  602. res = HidD_SetOutputReport(dev->device_handle, (void *)data, (ULONG)length);
  603. if (res)
  604. return (int)length;
  605. else
  606. return -1;
  607. }
  608. static int hid_write_timeout(hid_device *dev, const unsigned char *data, size_t length, int milliseconds)
  609. {
  610. DWORD bytes_written;
  611. BOOL res;
  612. size_t stashed_length = length;
  613. unsigned char *buf;
  614. #if 1
  615. /* If the application is writing to the device, it knows how much data to write.
  616. * This matches the behavior on other platforms. It's also important when writing
  617. * to Sony game controllers over Bluetooth, where there's a CRC at the end which
  618. * must not be tampered with.
  619. */
  620. buf = (unsigned char *) data;
  621. #else
  622. /* Make sure the right number of bytes are passed to WriteFile. Windows
  623. expects the number of bytes which are in the _longest_ report (plus
  624. one for the report number) bytes even if the data is a report
  625. which is shorter than that. Windows gives us this value in
  626. caps.OutputReportByteLength. If a user passes in fewer bytes than this,
  627. create a temporary buffer which is the proper size. */
  628. if (length >= dev->output_report_length) {
  629. /* The user passed the right number of bytes. Use the buffer as-is. */
  630. buf = (unsigned char *) data;
  631. } else {
  632. /* Create a temporary buffer and copy the user's data
  633. into it, padding the rest with zeros. */
  634. buf = (unsigned char *) malloc(dev->output_report_length);
  635. memcpy(buf, data, length);
  636. memset(buf + length, 0, dev->output_report_length - length);
  637. length = dev->output_report_length;
  638. }
  639. #endif
  640. if (length > 512)
  641. {
  642. return hid_write_output_report( dev, data, stashed_length );
  643. }
  644. else
  645. {
  646. res = WriteFile( dev->device_handle, buf, ( DWORD ) length, NULL, &dev->write_ol );
  647. if (!res) {
  648. if (GetLastError() != ERROR_IO_PENDING) {
  649. /* WriteFile() failed. Return error. */
  650. register_error(dev, "WriteFile");
  651. bytes_written = (DWORD) -1;
  652. goto end_of_function;
  653. }
  654. }
  655. /* Wait here until the write is done. This makes
  656. hid_write() synchronous. */
  657. res = WaitForSingleObject(dev->write_ol.hEvent, milliseconds);
  658. if (res != WAIT_OBJECT_0)
  659. {
  660. // There was a Timeout.
  661. bytes_written = (DWORD) -1;
  662. register_error(dev, "WriteFile/WaitForSingleObject Timeout");
  663. goto end_of_function;
  664. }
  665. res = GetOverlappedResult(dev->device_handle, &dev->write_ol, &bytes_written, FALSE/*F=don't_wait*/);
  666. if (!res) {
  667. /* The Write operation failed. */
  668. register_error(dev, "WriteFile");
  669. bytes_written = (DWORD) -1;
  670. goto end_of_function;
  671. }
  672. }
  673. end_of_function:
  674. if (buf != data)
  675. free(buf);
  676. return bytes_written;
  677. }
  678. int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length)
  679. {
  680. return hid_write_timeout(dev, data, length, HID_WRITE_TIMEOUT_MILLISECONDS);
  681. }
  682. int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
  683. {
  684. DWORD bytes_read = 0;
  685. size_t copy_len = 0;
  686. BOOL res;
  687. /* Copy the handle for convenience. */
  688. HANDLE ev = dev->ol.hEvent;
  689. if (!dev->read_pending) {
  690. /* Start an Overlapped I/O read. */
  691. dev->read_pending = TRUE;
  692. memset(dev->read_buf, 0, dev->input_report_length);
  693. ResetEvent(ev);
  694. res = ReadFile(dev->device_handle, dev->read_buf, (DWORD)dev->input_report_length, &bytes_read, &dev->ol);
  695. if (!res) {
  696. if (GetLastError() != ERROR_IO_PENDING) {
  697. /* ReadFile() has failed.
  698. Clean up and return error. */
  699. CancelIo(dev->device_handle);
  700. dev->read_pending = FALSE;
  701. goto end_of_function;
  702. }
  703. }
  704. }
  705. if (milliseconds >= 0) {
  706. /* See if there is any data yet. */
  707. res = WaitForSingleObject(ev, milliseconds);
  708. if (res != WAIT_OBJECT_0) {
  709. /* There was no data this time. Return zero bytes available,
  710. but leave the Overlapped I/O running. */
  711. return 0;
  712. }
  713. }
  714. /* Either WaitForSingleObject() told us that ReadFile has completed, or
  715. we are in non-blocking mode. Get the number of bytes read. The actual
  716. data has been copied to the data[] array which was passed to ReadFile(). */
  717. res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);
  718. /* Set pending back to false, even if GetOverlappedResult() returned error. */
  719. dev->read_pending = FALSE;
  720. if (res && bytes_read > 0) {
  721. if (dev->read_buf[0] == 0x0) {
  722. /* If report numbers aren't being used, but Windows sticks a report
  723. number (0x0) on the beginning of the report anyway. To make this
  724. work like the other platforms, and to make it work more like the
  725. HID spec, we'll skip over this byte. */
  726. bytes_read--;
  727. copy_len = length > bytes_read ? bytes_read : length;
  728. memcpy(data, dev->read_buf+1, copy_len);
  729. }
  730. else {
  731. /* Copy the whole buffer, report number and all. */
  732. copy_len = length > bytes_read ? bytes_read : length;
  733. memcpy(data, dev->read_buf, copy_len);
  734. }
  735. }
  736. end_of_function:
  737. if (!res) {
  738. register_error(dev, "GetOverlappedResult");
  739. return -1;
  740. }
  741. return (int)copy_len;
  742. }
  743. int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
  744. {
  745. return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
  746. }
  747. int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock)
  748. {
  749. dev->blocking = !nonblock;
  750. return 0; /* Success */
  751. }
  752. int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
  753. {
  754. BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, (ULONG)length);
  755. if (!res) {
  756. register_error(dev, "HidD_SetFeature");
  757. return -1;
  758. }
  759. return (int)length;
  760. }
  761. int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
  762. {
  763. BOOL res;
  764. #if 0
  765. res = HidD_GetFeature(dev->device_handle, (PVOID)data, (ULONG)length);
  766. if (!res) {
  767. register_error(dev, "HidD_GetFeature");
  768. return -1;
  769. }
  770. return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */
  771. #else
  772. DWORD bytes_returned;
  773. OVERLAPPED ol;
  774. memset(&ol, 0, sizeof(ol));
  775. res = DeviceIoControl(dev->device_handle,
  776. IOCTL_HID_GET_FEATURE,
  777. data, (DWORD)length,
  778. data, (DWORD)length,
  779. &bytes_returned, &ol);
  780. if (!res) {
  781. if (GetLastError() != ERROR_IO_PENDING) {
  782. /* DeviceIoControl() failed. Return error. */
  783. register_error(dev, "Send Feature Report DeviceIoControl");
  784. return -1;
  785. }
  786. }
  787. /* Wait here until the write is done. This makes
  788. hid_get_feature_report() synchronous. */
  789. res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/);
  790. if (!res) {
  791. /* The operation failed. */
  792. register_error(dev, "Send Feature Report GetOverLappedResult");
  793. return -1;
  794. }
  795. return bytes_returned;
  796. #endif
  797. }
  798. void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev)
  799. {
  800. typedef BOOL (WINAPI *CancelIoEx_t)(HANDLE hFile, LPOVERLAPPED lpOverlapped);
  801. CancelIoEx_t CancelIoExFunc = (CancelIoEx_t)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "CancelIoEx");
  802. if (!dev)
  803. return;
  804. if (CancelIoExFunc) {
  805. CancelIoExFunc(dev->device_handle, NULL);
  806. } else {
  807. /* Windows XP, this will only cancel I/O on the current thread */
  808. CancelIo(dev->device_handle);
  809. }
  810. if (dev->read_pending) {
  811. DWORD bytes_read = 0;
  812. GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);
  813. }
  814. free_hid_device(dev);
  815. }
  816. int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
  817. {
  818. BOOL res;
  819. res = HidD_GetManufacturerString(dev->device_handle, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  820. if (!res) {
  821. register_error(dev, "HidD_GetManufacturerString");
  822. return -1;
  823. }
  824. return 0;
  825. }
  826. int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
  827. {
  828. BOOL res;
  829. res = HidD_GetProductString(dev->device_handle, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  830. if (!res) {
  831. register_error(dev, "HidD_GetProductString");
  832. return -1;
  833. }
  834. return 0;
  835. }
  836. int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
  837. {
  838. BOOL res;
  839. res = HidD_GetSerialNumberString(dev->device_handle, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  840. if (!res) {
  841. register_error(dev, "HidD_GetSerialNumberString");
  842. return -1;
  843. }
  844. return 0;
  845. }
  846. int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
  847. {
  848. BOOL res;
  849. res = HidD_GetIndexedString(dev->device_handle, string_index, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  850. if (!res) {
  851. register_error(dev, "HidD_GetIndexedString");
  852. return -1;
  853. }
  854. return 0;
  855. }
  856. HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
  857. {
  858. return (wchar_t*)dev->last_error_str;
  859. }
  860. #if 0
  861. /*#define PICPGM*/
  862. /*#define S11*/
  863. #define P32
  864. #ifdef S11
  865. unsigned short VendorID = 0xa0a0;
  866. unsigned short ProductID = 0x0001;
  867. #endif
  868. #ifdef P32
  869. unsigned short VendorID = 0x04d8;
  870. unsigned short ProductID = 0x3f;
  871. #endif
  872. #ifdef PICPGM
  873. unsigned short VendorID = 0x04d8;
  874. unsigned short ProductID = 0x0033;
  875. #endif
  876. int __cdecl main(int argc, char* argv[])
  877. {
  878. int i, res;
  879. unsigned char buf[65];
  880. UNREFERENCED_PARAMETER(argc);
  881. UNREFERENCED_PARAMETER(argv);
  882. /* Set up the command buffer. */
  883. memset(buf,0x00,sizeof(buf));
  884. buf[0] = 0;
  885. buf[1] = 0x81;
  886. /* Open the device. */
  887. int handle = open(VendorID, ProductID, L"12345");
  888. if (handle < 0)
  889. printf("unable to open device\n");
  890. /* Toggle LED (cmd 0x80) */
  891. buf[1] = 0x80;
  892. res = write(handle, buf, 65);
  893. if (res < 0)
  894. printf("Unable to write()\n");
  895. /* Request state (cmd 0x81) */
  896. buf[1] = 0x81;
  897. write(handle, buf, 65);
  898. if (res < 0)
  899. printf("Unable to write() (2)\n");
  900. /* Read requested state */
  901. read(handle, buf, 65);
  902. if (res < 0)
  903. printf("Unable to read()\n");
  904. /* Print out the returned buffer. */
  905. for (i = 0; i < 4; i++)
  906. printf("buf[%d]: %d\n", i, buf[i]);
  907. return 0;
  908. }
  909. #endif
  910. #ifdef __cplusplus
  911. } /* extern "C" */
  912. #endif
  913. #endif /* SDL_JOYSTICK_HIDAPI */