hid.c 31 KB

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