hid.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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. #include <devpropdef.h>
  56. #include "hidapi_cfgmgr32.h"
  57. #include "hidapi_hidclass.h"
  58. #include "hidapi_hidsdi.h"
  59. #ifdef __cplusplus
  60. } /* extern "C" */
  61. #endif
  62. #include "../hidapi/hidapi.h"
  63. /*#include <stdio.h>*/
  64. /*#include <stdlib.h>*/
  65. /* SDL C runtime functions */
  66. #define calloc SDL_calloc
  67. #define free SDL_free
  68. #define malloc SDL_malloc
  69. #define memcpy SDL_memcpy
  70. #define memset SDL_memset
  71. #define strcmp SDL_strcmp
  72. #define strlen SDL_strlen
  73. #define strstr SDL_strstr
  74. #define strtol SDL_strtol
  75. #define towupper SDL_toupper
  76. #define wcscmp SDL_wcscmp
  77. #define wcslen SDL_wcslen
  78. #define _wcsdup SDL_wcsdup
  79. #define wcsstr SDL_wcsstr
  80. #undef MIN
  81. #define MIN(x,y) ((x) < (y)? (x): (y))
  82. #ifdef _MSC_VER
  83. /* Yes, we have some unreferenced formal parameters */
  84. #pragma warning(disable:4100)
  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 Windows SDK, we define what we need ourselves.
  92. In lookup_functions(), the function pointers
  93. defined below are set. */
  94. static HidD_GetHidGuid_ HidD_GetHidGuid;
  95. static HidD_GetAttributes_ HidD_GetAttributes;
  96. static HidD_GetSerialNumberString_ HidD_GetSerialNumberString;
  97. static HidD_GetManufacturerString_ HidD_GetManufacturerString;
  98. static HidD_GetProductString_ HidD_GetProductString;
  99. static HidD_SetFeature_ HidD_SetFeature;
  100. static HidD_GetFeature_ HidD_GetFeature;
  101. static HidD_GetInputReport_ HidD_GetInputReport;
  102. static HidD_GetIndexedString_ HidD_GetIndexedString;
  103. static HidD_GetPreparsedData_ HidD_GetPreparsedData;
  104. static HidD_FreePreparsedData_ HidD_FreePreparsedData;
  105. static HidP_GetCaps_ HidP_GetCaps;
  106. static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers;
  107. static HidD_SetOutputReport_ HidD_SetOutputReport;
  108. static CM_Locate_DevNodeW_ CM_Locate_DevNodeW = NULL;
  109. static CM_Get_Parent_ CM_Get_Parent = NULL;
  110. static CM_Get_DevNode_PropertyW_ CM_Get_DevNode_PropertyW = NULL;
  111. static CM_Get_Device_Interface_PropertyW_ CM_Get_Device_Interface_PropertyW = NULL;
  112. static CM_Get_Device_Interface_List_SizeW_ CM_Get_Device_Interface_List_SizeW = NULL;
  113. static CM_Get_Device_Interface_ListW_ CM_Get_Device_Interface_ListW = NULL;
  114. static HMODULE hid_lib_handle = NULL;
  115. static HMODULE cfgmgr32_lib_handle = NULL;
  116. static BOOLEAN hidapi_initialized = FALSE;
  117. static void free_library_handles(void)
  118. {
  119. if (hid_lib_handle)
  120. FreeLibrary(hid_lib_handle);
  121. hid_lib_handle = NULL;
  122. if (cfgmgr32_lib_handle)
  123. FreeLibrary(cfgmgr32_lib_handle);
  124. cfgmgr32_lib_handle = NULL;
  125. }
  126. #if defined(__GNUC__)
  127. # pragma GCC diagnostic push
  128. # pragma GCC diagnostic ignored "-Wcast-function-type"
  129. #endif
  130. static int lookup_functions(void)
  131. {
  132. hid_lib_handle = LoadLibraryW(L"hid.dll");
  133. if (hid_lib_handle == NULL) {
  134. goto err;
  135. }
  136. cfgmgr32_lib_handle = LoadLibraryW(L"cfgmgr32.dll");
  137. if (cfgmgr32_lib_handle == NULL) {
  138. goto err;
  139. }
  140. #define RESOLVE(lib_handle, x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) goto err;
  141. RESOLVE(hid_lib_handle, HidD_GetHidGuid);
  142. RESOLVE(hid_lib_handle, HidD_GetAttributes);
  143. RESOLVE(hid_lib_handle, HidD_GetSerialNumberString);
  144. RESOLVE(hid_lib_handle, HidD_GetManufacturerString);
  145. RESOLVE(hid_lib_handle, HidD_GetProductString);
  146. RESOLVE(hid_lib_handle, HidD_SetFeature);
  147. RESOLVE(hid_lib_handle, HidD_GetFeature);
  148. RESOLVE(hid_lib_handle, HidD_GetInputReport);
  149. RESOLVE(hid_lib_handle, HidD_GetIndexedString);
  150. RESOLVE(hid_lib_handle, HidD_GetPreparsedData);
  151. RESOLVE(hid_lib_handle, HidD_FreePreparsedData);
  152. RESOLVE(hid_lib_handle, HidP_GetCaps);
  153. RESOLVE(hid_lib_handle, HidD_SetNumInputBuffers);
  154. RESOLVE(hid_lib_handle, HidD_SetOutputReport);
  155. RESOLVE(cfgmgr32_lib_handle, CM_Locate_DevNodeW);
  156. RESOLVE(cfgmgr32_lib_handle, CM_Get_Parent);
  157. RESOLVE(cfgmgr32_lib_handle, CM_Get_DevNode_PropertyW);
  158. RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_PropertyW);
  159. RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_List_SizeW);
  160. RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_ListW);
  161. #undef RESOLVE
  162. return 0;
  163. err:
  164. free_library_handles();
  165. return -1;
  166. }
  167. #if defined(__GNUC__)
  168. # pragma GCC diagnostic pop
  169. #endif
  170. #endif /* HIDAPI_USE_DDK */
  171. struct hid_device_ {
  172. HANDLE device_handle;
  173. BOOL blocking;
  174. USHORT output_report_length;
  175. size_t input_report_length;
  176. void *last_error_str;
  177. DWORD last_error_num;
  178. BOOL read_pending;
  179. char *read_buf;
  180. OVERLAPPED ol;
  181. OVERLAPPED write_ol;
  182. BOOL use_hid_write_output_report;
  183. };
  184. static BOOL
  185. IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
  186. {
  187. OSVERSIONINFOEXW osvi;
  188. DWORDLONG const dwlConditionMask = VerSetConditionMask(
  189. VerSetConditionMask(
  190. VerSetConditionMask(
  191. 0, VER_MAJORVERSION, VER_GREATER_EQUAL ),
  192. VER_MINORVERSION, VER_GREATER_EQUAL ),
  193. VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL );
  194. memset(&osvi, 0, sizeof(osvi));
  195. osvi.dwOSVersionInfoSize = sizeof( osvi );
  196. osvi.dwMajorVersion = wMajorVersion;
  197. osvi.dwMinorVersion = wMinorVersion;
  198. osvi.wServicePackMajor = wServicePackMajor;
  199. return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE;
  200. }
  201. static hid_device *new_hid_device(void)
  202. {
  203. hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
  204. dev->device_handle = INVALID_HANDLE_VALUE;
  205. dev->blocking = TRUE;
  206. dev->output_report_length = 0;
  207. dev->input_report_length = 0;
  208. dev->last_error_str = NULL;
  209. dev->last_error_num = 0;
  210. dev->read_pending = FALSE;
  211. dev->read_buf = NULL;
  212. memset(&dev->ol, 0, sizeof(dev->ol));
  213. dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL);
  214. memset(&dev->write_ol, 0, sizeof(dev->write_ol));
  215. dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL);
  216. return dev;
  217. }
  218. static void free_hid_device(hid_device *dev)
  219. {
  220. CloseHandle(dev->ol.hEvent);
  221. CloseHandle(dev->write_ol.hEvent);
  222. CloseHandle(dev->device_handle);
  223. LocalFree(dev->last_error_str);
  224. free(dev->read_buf);
  225. free(dev);
  226. }
  227. static void register_error(hid_device *device, const char *op)
  228. {
  229. WCHAR *ptr, *msg;
  230. DWORD count = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  231. FORMAT_MESSAGE_FROM_SYSTEM |
  232. FORMAT_MESSAGE_IGNORE_INSERTS,
  233. NULL,
  234. GetLastError(),
  235. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  236. (LPWSTR)&msg, 0/*sz*/,
  237. NULL);
  238. if (!count)
  239. return;
  240. /* Get rid of the CR and LF that FormatMessage() sticks at the
  241. end of the message. Thanks Microsoft! */
  242. ptr = msg;
  243. while (*ptr) {
  244. if (*ptr == '\r') {
  245. *ptr = 0x0000;
  246. break;
  247. }
  248. ptr++;
  249. }
  250. /* Store the message off in the Device entry so that
  251. the hid_error() function can pick it up. */
  252. LocalFree(device->last_error_str);
  253. device->last_error_str = msg;
  254. }
  255. static HANDLE open_device(const char *path, BOOL enumerate, BOOL bExclusive )
  256. {
  257. HANDLE handle;
  258. // Opening with access 0 causes keyboards to stop responding in some system configurations
  259. // http://steamcommunity.com/discussions/forum/1/1843493219428923893
  260. // Thanks to co-wie (Ka-wei Low <kawei@mac.com>) for help narrowing down the problem on his system
  261. //DWORD desired_access = (enumerate)? 0: (GENERIC_WRITE | GENERIC_READ);
  262. DWORD desired_access = ( GENERIC_WRITE | GENERIC_READ );
  263. DWORD share_mode = bExclusive ? 0 : ( FILE_SHARE_READ | FILE_SHARE_WRITE );
  264. handle = CreateFileA(path,
  265. desired_access,
  266. share_mode,
  267. NULL,
  268. OPEN_EXISTING,
  269. FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/
  270. 0);
  271. return handle;
  272. }
  273. int HID_API_EXPORT hid_init(void)
  274. {
  275. #ifndef HIDAPI_USE_DDK
  276. if (!hidapi_initialized) {
  277. if (lookup_functions() < 0) {
  278. return -1;
  279. }
  280. hidapi_initialized = TRUE;
  281. }
  282. #endif
  283. return 0;
  284. }
  285. int HID_API_EXPORT hid_exit(void)
  286. {
  287. #ifndef HIDAPI_USE_DDK
  288. free_library_handles();
  289. hidapi_initialized = FALSE;
  290. #endif
  291. return 0;
  292. }
  293. static void* hid_internal_get_devnode_property(DEVINST dev_node, const DEVPROPKEY* property_key, DEVPROPTYPE expected_property_type)
  294. {
  295. ULONG len = 0;
  296. CONFIGRET cr;
  297. DEVPROPTYPE property_type;
  298. PBYTE property_value = NULL;
  299. cr = CM_Get_DevNode_PropertyW(dev_node, property_key, &property_type, NULL, &len, 0);
  300. if (cr != CR_BUFFER_SMALL || property_type != expected_property_type)
  301. return NULL;
  302. property_value = (PBYTE)calloc(len, sizeof(BYTE));
  303. cr = CM_Get_DevNode_PropertyW(dev_node, property_key, &property_type, property_value, &len, 0);
  304. if (cr != CR_SUCCESS) {
  305. free(property_value);
  306. return NULL;
  307. }
  308. return property_value;
  309. }
  310. static void* hid_internal_get_device_interface_property(const wchar_t* interface_path, const DEVPROPKEY* property_key, DEVPROPTYPE expected_property_type)
  311. {
  312. ULONG len = 0;
  313. CONFIGRET cr;
  314. DEVPROPTYPE property_type;
  315. PBYTE property_value = NULL;
  316. cr = CM_Get_Device_Interface_PropertyW(interface_path, property_key, &property_type, NULL, &len, 0);
  317. if (cr != CR_BUFFER_SMALL || property_type != expected_property_type)
  318. return NULL;
  319. property_value = (PBYTE)calloc(len, sizeof(BYTE));
  320. cr = CM_Get_Device_Interface_PropertyW(interface_path, property_key, &property_type, property_value, &len, 0);
  321. if (cr != CR_SUCCESS) {
  322. free(property_value);
  323. return NULL;
  324. }
  325. return property_value;
  326. }
  327. static void hid_internal_get_ble_info(struct hid_device_info* dev, DEVINST dev_node)
  328. {
  329. wchar_t *manufacturer_string, *serial_number, *product_string;
  330. /* Manufacturer String */
  331. manufacturer_string = hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_Manufacturer, DEVPROP_TYPE_STRING);
  332. if (manufacturer_string) {
  333. free(dev->manufacturer_string);
  334. dev->manufacturer_string = manufacturer_string;
  335. }
  336. /* Serial Number String (MAC Address) */
  337. serial_number = hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_DeviceAddress, DEVPROP_TYPE_STRING);
  338. if (serial_number) {
  339. free(dev->serial_number);
  340. dev->serial_number = serial_number;
  341. }
  342. /* Get devnode grandparent to reach out Bluetooth LE device node */
  343. if (CM_Get_Parent(&dev_node, dev_node, 0) != CR_SUCCESS)
  344. return;
  345. /* Product String */
  346. product_string = hid_internal_get_devnode_property(dev_node, &DEVPKEY_NAME, DEVPROP_TYPE_STRING);
  347. if (product_string) {
  348. free(dev->product_string);
  349. dev->product_string = product_string;
  350. }
  351. }
  352. #if 0
  353. /* USB Device Interface Number.
  354. It can be parsed out of the Hardware ID if a USB device is has multiple interfaces (composite device).
  355. See https://docs.microsoft.com/windows-hardware/drivers/hid/hidclass-hardware-ids-for-top-level-collections
  356. and https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers
  357. hardware_id is always expected to be uppercase.
  358. */
  359. static int hid_internal_get_interface_number(const wchar_t* hardware_id)
  360. {
  361. int interface_number;
  362. wchar_t *startptr, *endptr;
  363. const wchar_t *interface_token = L"&MI_";
  364. startptr = wcsstr(hardware_id, interface_token);
  365. if (!startptr)
  366. return -1;
  367. startptr += wcslen(interface_token);
  368. interface_number = wcstol(startptr, &endptr, 16);
  369. if (endptr == startptr)
  370. return -1;
  371. return interface_number;
  372. }
  373. static void hid_internal_get_info(const wchar_t* interface_path, struct hid_device_info* dev)
  374. {
  375. wchar_t *device_id = NULL, *compatible_ids = NULL, *hardware_ids = NULL;
  376. wchar_t *id;
  377. CONFIGRET cr;
  378. DEVINST dev_node;
  379. /* Get the device id from interface path */
  380. device_id = hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING);
  381. if (!device_id)
  382. goto end;
  383. /* Open devnode from device id */
  384. cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL);
  385. if (cr != CR_SUCCESS)
  386. goto end;
  387. /* Get the hardware ids from devnode */
  388. hardware_ids = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_HardwareIds, DEVPROP_TYPE_STRING_LIST);
  389. if (!hardware_ids)
  390. goto end;
  391. /* Search for interface number in hardware ids */
  392. for (id = hardware_ids; *id; id += wcslen(id) + 1) {
  393. /* Normalize to upper case */
  394. wchar_t* p = id;
  395. for (; *p; ++p) *p = towupper(*p);
  396. dev->interface_number = hid_internal_get_interface_number(id);
  397. if (dev->interface_number != -1)
  398. break;
  399. }
  400. /* Get devnode parent */
  401. cr = CM_Get_Parent(&dev_node, dev_node, 0);
  402. if (cr != CR_SUCCESS)
  403. goto end;
  404. /* Get the compatible ids from parent devnode */
  405. compatible_ids = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_CompatibleIds, DEVPROP_TYPE_STRING_LIST);
  406. if (!compatible_ids)
  407. goto end;
  408. /* Now we can parse parent's compatible IDs to find out the device bus type */
  409. for (id = compatible_ids; *id; id += wcslen(id) + 1) {
  410. /* Normalize to upper case */
  411. wchar_t* p = id;
  412. for (; *p; ++p) *p = towupper(*p);
  413. /* USB devices
  414. https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support
  415. https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers */
  416. if (wcsstr(id, L"USB") != NULL) {
  417. dev->bus_type = HID_API_BUS_USB;
  418. break;
  419. }
  420. /* Bluetooth devices
  421. https://docs.microsoft.com/windows-hardware/drivers/bluetooth/installing-a-bluetooth-device */
  422. if (wcsstr(id, L"BTHENUM") != NULL) {
  423. dev->bus_type = HID_API_BUS_BLUETOOTH;
  424. break;
  425. }
  426. /* Bluetooth LE devices */
  427. if (wcsstr(id, L"BTHLEDEVICE") != NULL) {
  428. /* HidD_GetProductString/HidD_GetManufacturerString/HidD_GetSerialNumberString is not working for BLE HID devices
  429. Request this info via dev node properties instead.
  430. https://docs.microsoft.com/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html */
  431. hid_internal_get_ble_info(dev, dev_node);
  432. dev->bus_type = HID_API_BUS_BLUETOOTH;
  433. break;
  434. }
  435. /* I2C devices
  436. https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support-and-power-management */
  437. if (wcsstr(id, L"PNP0C50") != NULL) {
  438. dev->bus_type = HID_API_BUS_I2C;
  439. break;
  440. }
  441. /* SPI devices
  442. https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-for-spi */
  443. if (wcsstr(id, L"PNP0C51") != NULL) {
  444. dev->bus_type = HID_API_BUS_SPI;
  445. break;
  446. }
  447. }
  448. end:
  449. free(device_id);
  450. free(hardware_ids);
  451. free(compatible_ids);
  452. }
  453. static char *hid_internal_UTF16toUTF8(const wchar_t *src)
  454. {
  455. char *dst = NULL;
  456. int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL);
  457. if (len) {
  458. dst = (char*)calloc(len, sizeof(char));
  459. if (dst == NULL) {
  460. return NULL;
  461. }
  462. WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, dst, len, NULL, NULL);
  463. }
  464. return dst;
  465. }
  466. #endif /* 0 */
  467. static wchar_t *hid_internal_UTF8toUTF16(const char *src)
  468. {
  469. wchar_t *dst = NULL;
  470. int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, NULL, 0);
  471. if (len) {
  472. dst = (wchar_t*)calloc(len, sizeof(wchar_t));
  473. if (dst == NULL) {
  474. return NULL;
  475. }
  476. MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, dst, len);
  477. }
  478. return dst;
  479. }
  480. static int hid_get_bluetooth_info(const char *path, struct hid_device_info* dev)
  481. {
  482. wchar_t *interface_path = NULL, *device_id = NULL, *compatible_ids = NULL;
  483. wchar_t *id;
  484. CONFIGRET cr;
  485. DEVINST dev_node;
  486. int is_bluetooth = 0;
  487. /* Get the device id from interface path */
  488. interface_path = hid_internal_UTF8toUTF16(path);
  489. device_id = hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING);
  490. if (!device_id)
  491. goto end;
  492. /* Open devnode from device id */
  493. cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL);
  494. if (cr != CR_SUCCESS)
  495. goto end;
  496. /* Get devnode parent */
  497. cr = CM_Get_Parent(&dev_node, dev_node, 0);
  498. if (cr != CR_SUCCESS)
  499. goto end;
  500. /* Get the compatible ids from parent devnode */
  501. compatible_ids = hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_CompatibleIds, DEVPROP_TYPE_STRING_LIST);
  502. if (!compatible_ids)
  503. goto end;
  504. /* Now we can parse parent's compatible IDs to find out the device bus type */
  505. for (id = compatible_ids; *id; id += wcslen(id) + 1) {
  506. /* Normalize to upper case */
  507. wchar_t* p = id;
  508. for (; *p; ++p) *p = towupper(*p);
  509. /* USB devices
  510. https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support
  511. https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers */
  512. if (wcsstr(id, L"USB") != NULL) {
  513. /*dev->bus_type = HID_API_BUS_USB;*/
  514. break;
  515. }
  516. /* Bluetooth devices
  517. https://docs.microsoft.com/windows-hardware/drivers/bluetooth/installing-a-bluetooth-device */
  518. if (wcsstr(id, L"BTHENUM") != NULL) {
  519. /*dev->bus_type = HID_API_BUS_BLUETOOTH;*/
  520. is_bluetooth = 1;
  521. break;
  522. }
  523. /* Bluetooth LE devices */
  524. if (wcsstr(id, L"BTHLEDEVICE") != NULL) {
  525. /* HidD_GetProductString/HidD_GetManufacturerString/HidD_GetSerialNumberString is not working for BLE HID devices
  526. Request this info via dev node properties instead.
  527. https://docs.microsoft.com/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html */
  528. if (dev)
  529. hid_internal_get_ble_info(dev, dev_node);
  530. /*dev->bus_type = HID_API_BUS_BLUETOOTH;*/
  531. is_bluetooth = 1;
  532. break;
  533. }
  534. /* I2C devices
  535. https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support-and-power-management */
  536. if (wcsstr(id, L"PNP0C50") != NULL) {
  537. /*dev->bus_type = HID_API_BUS_I2C;*/
  538. break;
  539. }
  540. /* SPI devices
  541. https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-for-spi */
  542. if (wcsstr(id, L"PNP0C51") != NULL) {
  543. /*dev->bus_type = HID_API_BUS_SPI;*/
  544. break;
  545. }
  546. }
  547. end:
  548. free(interface_path);
  549. free(device_id);
  550. free(compatible_ids);
  551. return is_bluetooth;
  552. }
  553. static int hid_blacklist(unsigned short vendor_id, unsigned short product_id)
  554. {
  555. size_t i;
  556. static const struct { unsigned short vid; unsigned short pid; } known_bad[] = {
  557. /* Causes deadlock when asking for device details... */
  558. { 0x1B1C, 0x1B3D }, /* Corsair Gaming keyboard */
  559. { 0x1532, 0x0109 }, /* Razer Lycosa Gaming keyboard */
  560. { 0x1532, 0x010B }, /* Razer Arctosa Gaming keyboard */
  561. { 0x045E, 0x0822 }, /* Microsoft Precision Mouse */
  562. { 0x0D8C, 0x0014 }, /* Sharkoon Skiller SGH2 headset */
  563. { 0x1CCF, 0x0000 }, /* All Konami Amusement Devices */
  564. /* Turns into an Android controller when enumerated... */
  565. { 0x0738, 0x2217 } /* SPEEDLINK COMPETITION PRO */
  566. };
  567. for (i = 0; i < (sizeof(known_bad)/sizeof(known_bad[0])); i++) {
  568. if ((vendor_id == known_bad[i].vid) && (product_id == known_bad[i].pid || known_bad[i].pid == 0x0000)) {
  569. return 1;
  570. }
  571. }
  572. return 0;
  573. }
  574. struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
  575. {
  576. BOOL res;
  577. struct hid_device_info *root = NULL; /* return object */
  578. struct hid_device_info *cur_dev = NULL;
  579. /* Windows objects for interacting with the driver. */
  580. GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} };
  581. SP_DEVINFO_DATA devinfo_data;
  582. SP_DEVICE_INTERFACE_DATA device_interface_data;
  583. SP_DEVICE_INTERFACE_DETAIL_DATA_A *device_interface_detail_data = NULL;
  584. HDEVINFO device_info_set = INVALID_HANDLE_VALUE;
  585. int device_index = 0;
  586. const char *hint = SDL_GetHint(SDL_HINT_HIDAPI_IGNORE_DEVICES);
  587. if (hid_init() < 0)
  588. return NULL;
  589. /* Initialize the Windows objects. */
  590. memset(&devinfo_data, 0x0, sizeof(devinfo_data));
  591. devinfo_data.cbSize = sizeof(SP_DEVINFO_DATA);
  592. device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  593. /* Get information for all the devices belonging to the HID class. */
  594. device_info_set = SetupDiGetClassDevsA(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  595. /* Iterate over each device in the HID class, looking for the right one. */
  596. for (;;) {
  597. HANDLE write_handle = INVALID_HANDLE_VALUE;
  598. DWORD required_size = 0;
  599. HIDD_ATTRIBUTES attrib;
  600. res = SetupDiEnumDeviceInterfaces(device_info_set,
  601. NULL,
  602. &InterfaceClassGuid,
  603. device_index,
  604. &device_interface_data);
  605. if (!res) {
  606. /* A return of FALSE from this function means that
  607. there are no more devices. */
  608. break;
  609. }
  610. /* Call with 0-sized detail size, and let the function
  611. tell us how long the detail struct needs to be. The
  612. size is put in &required_size. */
  613. res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
  614. &device_interface_data,
  615. NULL,
  616. 0,
  617. &required_size,
  618. NULL);
  619. /* Allocate a long enough structure for device_interface_detail_data. */
  620. device_interface_detail_data = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) malloc(required_size);
  621. device_interface_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
  622. /* Get the detailed data for this device. The detail data gives us
  623. the device path for this device, which is then passed into
  624. CreateFile() to get a handle to the device. */
  625. res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
  626. &device_interface_data,
  627. device_interface_detail_data,
  628. required_size,
  629. NULL,
  630. NULL);
  631. if (!res) {
  632. /* register_error(dev, "Unable to call SetupDiGetDeviceInterfaceDetail");
  633. Continue to the next device. */
  634. goto cont;
  635. }
  636. /* XInput devices don't get real HID reports and are better handled by the raw input driver */
  637. if (strstr(device_interface_detail_data->DevicePath, "&ig_") != NULL) {
  638. goto cont;
  639. }
  640. /* Make sure this device is of Setup Class "HIDClass" and has a
  641. driver bound to it. */
  642. /* In the main HIDAPI tree this is a loop which will erroneously open
  643. devices that aren't HID class. Please preserve this delta if we ever
  644. update to take new changes */
  645. {
  646. char driver_name[256];
  647. /* Populate devinfo_data. This function will return failure
  648. when there are no more interfaces left. */
  649. res = SetupDiEnumDeviceInfo(device_info_set, device_index, &devinfo_data);
  650. if (!res)
  651. goto cont;
  652. res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
  653. SPDRP_CLASS, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
  654. if (!res)
  655. goto cont;
  656. if (strcmp(driver_name, "HIDClass") == 0) {
  657. /* See if there's a driver bound. */
  658. res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
  659. SPDRP_DRIVER, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
  660. if (!res)
  661. goto cont;
  662. }
  663. else
  664. {
  665. goto cont;
  666. }
  667. }
  668. //wprintf(L"HandleName: %s\n", device_interface_detail_data->DevicePath);
  669. /* Open a handle to the device */
  670. write_handle = open_device(device_interface_detail_data->DevicePath, TRUE, FALSE);
  671. /* Check validity of write_handle. */
  672. if (write_handle == INVALID_HANDLE_VALUE) {
  673. /* Unable to open the device. */
  674. //register_error(dev, "CreateFile");
  675. goto cont;
  676. }
  677. /* Get the Vendor ID and Product ID for this device. */
  678. attrib.Size = sizeof(HIDD_ATTRIBUTES);
  679. HidD_GetAttributes(write_handle, &attrib);
  680. //wprintf(L"Product/Vendor: %x %x\n", attrib.ProductID, attrib.VendorID);
  681. /* See if there are any devices we should skip in enumeration */
  682. if (hint) {
  683. char vendor_match[16], product_match[16];
  684. SDL_snprintf(vendor_match, sizeof(vendor_match), "0x%.4x/0x0000", attrib.VendorID);
  685. SDL_snprintf(product_match, sizeof(product_match), "0x%.4x/0x%.4x", attrib.VendorID, attrib.ProductID);
  686. if (SDL_strcasestr(hint, vendor_match) || SDL_strcasestr(hint, product_match)) {
  687. continue;
  688. }
  689. }
  690. /* Check the VID/PID to see if we should add this
  691. device to the enumeration list. */
  692. if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) &&
  693. (product_id == 0x0 || attrib.ProductID == product_id) &&
  694. !hid_blacklist(attrib.VendorID, attrib.ProductID)) {
  695. #define WSTR_LEN 512
  696. const char *str;
  697. struct hid_device_info *tmp;
  698. PHIDP_PREPARSED_DATA pp_data = NULL;
  699. HIDP_CAPS caps;
  700. BOOLEAN hidp_res;
  701. NTSTATUS nt_res;
  702. wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */
  703. size_t len;
  704. /* Get the Usage Page and Usage for this device. */
  705. hidp_res = HidD_GetPreparsedData(write_handle, &pp_data);
  706. if (hidp_res) {
  707. nt_res = HidP_GetCaps(pp_data, &caps);
  708. HidD_FreePreparsedData(pp_data);
  709. if (nt_res != HIDP_STATUS_SUCCESS) {
  710. goto cont_close;
  711. }
  712. }
  713. else {
  714. goto cont_close;
  715. }
  716. /* SDL Modification: Ignore the device if it's not a gamepad. This limits compatibility
  717. risk from devices that may respond poorly to our string queries below. */
  718. if (attrib.VendorID != USB_VENDOR_VALVE) {
  719. if (caps.UsagePage != USAGE_PAGE_GENERIC_DESKTOP) {
  720. goto cont_close;
  721. }
  722. if (caps.Usage != USAGE_JOYSTICK && caps.Usage != USAGE_GAMEPAD && caps.Usage != USAGE_MULTIAXISCONTROLLER) {
  723. goto cont_close;
  724. }
  725. }
  726. /* VID/PID match. Create the record. */
  727. tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
  728. if (cur_dev) {
  729. cur_dev->next = tmp;
  730. }
  731. else {
  732. root = tmp;
  733. }
  734. cur_dev = tmp;
  735. /* Fill out the record */
  736. cur_dev->usage_page = caps.UsagePage;
  737. cur_dev->usage = caps.Usage;
  738. cur_dev->next = NULL;
  739. str = device_interface_detail_data->DevicePath;
  740. if (str) {
  741. len = strlen(str);
  742. cur_dev->path = (char*) calloc(len+1, sizeof(char));
  743. memcpy(cur_dev->path, str, len+1);
  744. }
  745. else
  746. cur_dev->path = NULL;
  747. /* Serial Number */
  748. hidp_res = HidD_GetSerialNumberString(write_handle, wstr, sizeof(wstr));
  749. wstr[WSTR_LEN-1] = 0x0000;
  750. if (hidp_res) {
  751. cur_dev->serial_number = _wcsdup(wstr);
  752. }
  753. /* Manufacturer String */
  754. hidp_res = HidD_GetManufacturerString(write_handle, wstr, sizeof(wstr));
  755. wstr[WSTR_LEN-1] = 0x0000;
  756. if (hidp_res) {
  757. cur_dev->manufacturer_string = _wcsdup(wstr);
  758. }
  759. /* Product String */
  760. hidp_res = HidD_GetProductString(write_handle, wstr, sizeof(wstr));
  761. wstr[WSTR_LEN-1] = 0x0000;
  762. if (hidp_res) {
  763. cur_dev->product_string = _wcsdup(wstr);
  764. }
  765. /* VID/PID */
  766. cur_dev->vendor_id = attrib.VendorID;
  767. cur_dev->product_id = attrib.ProductID;
  768. /* Release Number */
  769. cur_dev->release_number = attrib.VersionNumber;
  770. /* Interface Number. It can sometimes be parsed out of the path
  771. on Windows if a device has multiple interfaces. See
  772. http://msdn.microsoft.com/en-us/windows/hardware/gg487473 or
  773. search for "Hardware IDs for HID Devices" at MSDN. If it's not
  774. in the path, it's set to -1. */
  775. cur_dev->interface_number = -1;
  776. if (cur_dev->path) {
  777. char *interface_component = strstr(cur_dev->path, "&mi_");
  778. if (interface_component) {
  779. char *hex_str = interface_component + 4;
  780. char *endptr = NULL;
  781. cur_dev->interface_number = strtol(hex_str, &endptr, 16);
  782. if (endptr == hex_str) {
  783. /* The parsing failed. Set interface_number to -1. */
  784. cur_dev->interface_number = -1;
  785. }
  786. }
  787. }
  788. /* Get the Bluetooth device info */
  789. hid_get_bluetooth_info(cur_dev->path, cur_dev);
  790. }
  791. cont_close:
  792. CloseHandle(write_handle);
  793. cont:
  794. /* We no longer need the detail data. It can be freed */
  795. free(device_interface_detail_data);
  796. device_index++;
  797. }
  798. /* Close the device information handle. */
  799. SetupDiDestroyDeviceInfoList(device_info_set);
  800. return root;
  801. }
  802. void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
  803. {
  804. /* TODO: Merge this with the Linux version. This function is platform-independent. */
  805. struct hid_device_info *d = devs;
  806. while (d) {
  807. struct hid_device_info *next = d->next;
  808. free(d->path);
  809. free(d->serial_number);
  810. free(d->manufacturer_string);
  811. free(d->product_string);
  812. free(d);
  813. d = next;
  814. }
  815. }
  816. HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
  817. {
  818. /* TODO: Merge this functions with the Linux version. This function should be platform independent. */
  819. struct hid_device_info *devs, *cur_dev;
  820. const char *path_to_open = NULL;
  821. hid_device *handle = NULL;
  822. devs = hid_enumerate(vendor_id, product_id);
  823. cur_dev = devs;
  824. while (cur_dev) {
  825. if (cur_dev->vendor_id == vendor_id &&
  826. cur_dev->product_id == product_id) {
  827. if (serial_number) {
  828. if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
  829. path_to_open = cur_dev->path;
  830. break;
  831. }
  832. }
  833. else {
  834. path_to_open = cur_dev->path;
  835. break;
  836. }
  837. }
  838. cur_dev = cur_dev->next;
  839. }
  840. if (path_to_open) {
  841. /* Open the device */
  842. handle = hid_open_path(path_to_open, 0);
  843. }
  844. hid_free_enumeration(devs);
  845. return handle;
  846. }
  847. HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path, int bExclusive)
  848. {
  849. hid_device *dev;
  850. HIDP_CAPS caps;
  851. PHIDP_PREPARSED_DATA pp_data = NULL;
  852. BOOLEAN res;
  853. NTSTATUS nt_res;
  854. if (hid_init() < 0) {
  855. return NULL;
  856. }
  857. dev = new_hid_device();
  858. /* Open a handle to the device */
  859. dev->device_handle = open_device(path, FALSE, bExclusive);
  860. /* Check validity of write_handle. */
  861. if (dev->device_handle == INVALID_HANDLE_VALUE) {
  862. /* Unable to open the device. */
  863. register_error(dev, "CreateFile");
  864. goto err;
  865. }
  866. /* Set the Input Report buffer size to 64 reports. */
  867. res = HidD_SetNumInputBuffers(dev->device_handle, 64);
  868. if (!res) {
  869. register_error(dev, "HidD_SetNumInputBuffers");
  870. goto err;
  871. }
  872. /* Get the Input Report length for the device. */
  873. res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
  874. if (!res) {
  875. register_error(dev, "HidD_GetPreparsedData");
  876. goto err;
  877. }
  878. nt_res = HidP_GetCaps(pp_data, &caps);
  879. if (nt_res != HIDP_STATUS_SUCCESS) {
  880. register_error(dev, "HidP_GetCaps");
  881. goto err_pp_data;
  882. }
  883. dev->output_report_length = caps.OutputReportByteLength;
  884. dev->input_report_length = caps.InputReportByteLength;
  885. HidD_FreePreparsedData(pp_data);
  886. /* On Windows 7, we need to use hid_write_output_report() over Bluetooth */
  887. if (dev->output_report_length > 512) {
  888. dev->use_hid_write_output_report = !IsWindowsVersionOrGreater( HIBYTE( _WIN32_WINNT_WIN8 ), LOBYTE( _WIN32_WINNT_WIN8 ), 0 );
  889. }
  890. dev->read_buf = (char*) malloc(dev->input_report_length);
  891. return dev;
  892. err_pp_data:
  893. HidD_FreePreparsedData(pp_data);
  894. err:
  895. free_hid_device(dev);
  896. return NULL;
  897. }
  898. int HID_API_EXPORT HID_API_CALL hid_write_output_report(hid_device *dev, const unsigned char *data, size_t length)
  899. {
  900. BOOL res;
  901. res = HidD_SetOutputReport(dev->device_handle, (void *)data, (ULONG)length);
  902. if (res)
  903. return (int)length;
  904. else
  905. return -1;
  906. }
  907. static int hid_write_timeout(hid_device *dev, const unsigned char *data, size_t length, int milliseconds)
  908. {
  909. DWORD bytes_written;
  910. BOOL res;
  911. unsigned char *buf;
  912. if (dev->use_hid_write_output_report) {
  913. return hid_write_output_report(dev, data, length);
  914. }
  915. /* Make sure the right number of bytes are passed to WriteFile. Windows
  916. expects the number of bytes which are in the _longest_ report (plus
  917. one for the report number) bytes even if the data is a report
  918. which is shorter than that. Windows gives us this value in
  919. caps.OutputReportByteLength. If a user passes in fewer bytes than this,
  920. create a temporary buffer which is the proper size. */
  921. if (length >= dev->output_report_length) {
  922. /* The user passed the right number of bytes. Use the buffer as-is. */
  923. buf = (unsigned char *) data;
  924. } else {
  925. /* Create a temporary buffer and copy the user's data
  926. into it, padding the rest with zeros. */
  927. buf = (unsigned char *) malloc(dev->output_report_length);
  928. memcpy(buf, data, length);
  929. memset(buf + length, 0, dev->output_report_length - length);
  930. length = dev->output_report_length;
  931. }
  932. res = WriteFile( dev->device_handle, buf, ( DWORD ) length, NULL, &dev->write_ol );
  933. if (!res) {
  934. if (GetLastError() != ERROR_IO_PENDING) {
  935. /* WriteFile() failed. Return error. */
  936. register_error(dev, "WriteFile");
  937. bytes_written = (DWORD) -1;
  938. goto end_of_function;
  939. }
  940. }
  941. /* Wait here until the write is done. This makes hid_write() synchronous. */
  942. res = WaitForSingleObject(dev->write_ol.hEvent, milliseconds);
  943. if (res != WAIT_OBJECT_0)
  944. {
  945. // There was a Timeout.
  946. bytes_written = (DWORD) -1;
  947. register_error(dev, "WriteFile/WaitForSingleObject Timeout");
  948. goto end_of_function;
  949. }
  950. res = GetOverlappedResult(dev->device_handle, &dev->write_ol, &bytes_written, FALSE/*F=don't_wait*/);
  951. if (!res) {
  952. /* The Write operation failed. */
  953. register_error(dev, "WriteFile");
  954. bytes_written = (DWORD) -1;
  955. goto end_of_function;
  956. }
  957. end_of_function:
  958. if (buf != data)
  959. free(buf);
  960. return bytes_written;
  961. }
  962. int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length)
  963. {
  964. return hid_write_timeout(dev, data, length, HID_WRITE_TIMEOUT_MILLISECONDS);
  965. }
  966. int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
  967. {
  968. DWORD bytes_read = 0;
  969. size_t copy_len = 0;
  970. BOOL res;
  971. /* Copy the handle for convenience. */
  972. HANDLE ev = dev->ol.hEvent;
  973. if (!dev->read_pending) {
  974. /* Start an Overlapped I/O read. */
  975. dev->read_pending = TRUE;
  976. memset(dev->read_buf, 0, dev->input_report_length);
  977. ResetEvent(ev);
  978. res = ReadFile(dev->device_handle, dev->read_buf, (DWORD)dev->input_report_length, &bytes_read, &dev->ol);
  979. if (!res) {
  980. if (GetLastError() != ERROR_IO_PENDING) {
  981. /* ReadFile() has failed.
  982. Clean up and return error. */
  983. CancelIo(dev->device_handle);
  984. dev->read_pending = FALSE;
  985. goto end_of_function;
  986. }
  987. }
  988. }
  989. /* See if there is any data yet. */
  990. res = WaitForSingleObject(ev, milliseconds >= 0 ? milliseconds : INFINITE);
  991. if (res != WAIT_OBJECT_0) {
  992. /* There was no data this time. Return zero bytes available,
  993. but leave the Overlapped I/O running. */
  994. return 0;
  995. }
  996. /* Get the number of bytes read. The actual data has been copied to the data[]
  997. array which was passed to ReadFile(). We must not wait here because we've
  998. already waited on our event above, and since it's auto-reset, it will have
  999. been reset back to unsignalled by now. */
  1000. res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, FALSE/*don't wait*/);
  1001. /* Set pending back to false, even if GetOverlappedResult() returned error. */
  1002. dev->read_pending = FALSE;
  1003. if (res && bytes_read > 0) {
  1004. if (dev->read_buf[0] == 0x0) {
  1005. /* If report numbers aren't being used, but Windows sticks a report
  1006. number (0x0) on the beginning of the report anyway. To make this
  1007. work like the other platforms, and to make it work more like the
  1008. HID spec, we'll skip over this byte. */
  1009. bytes_read--;
  1010. copy_len = length > bytes_read ? bytes_read : length;
  1011. memcpy(data, dev->read_buf+1, copy_len);
  1012. }
  1013. else {
  1014. /* Copy the whole buffer, report number and all. */
  1015. copy_len = length > bytes_read ? bytes_read : length;
  1016. memcpy(data, dev->read_buf, copy_len);
  1017. }
  1018. }
  1019. end_of_function:
  1020. if (!res) {
  1021. register_error(dev, "GetOverlappedResult");
  1022. return -1;
  1023. }
  1024. return (int)copy_len;
  1025. }
  1026. int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
  1027. {
  1028. return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
  1029. }
  1030. int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock)
  1031. {
  1032. dev->blocking = !nonblock;
  1033. return 0; /* Success */
  1034. }
  1035. int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
  1036. {
  1037. BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, (ULONG)length);
  1038. if (!res) {
  1039. register_error(dev, "HidD_SetFeature");
  1040. return -1;
  1041. }
  1042. return (int)length;
  1043. }
  1044. int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
  1045. {
  1046. BOOL res;
  1047. #if 0
  1048. res = HidD_GetFeature(dev->device_handle, (PVOID)data, (ULONG)length);
  1049. if (!res) {
  1050. register_error(dev, "HidD_GetFeature");
  1051. return -1;
  1052. }
  1053. return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */
  1054. #else
  1055. DWORD bytes_returned;
  1056. OVERLAPPED ol;
  1057. memset(&ol, 0, sizeof(ol));
  1058. res = DeviceIoControl(dev->device_handle,
  1059. IOCTL_HID_GET_FEATURE,
  1060. data, (DWORD)length,
  1061. data, (DWORD)length,
  1062. &bytes_returned, &ol);
  1063. if (!res) {
  1064. if (GetLastError() != ERROR_IO_PENDING) {
  1065. /* DeviceIoControl() failed. Return error. */
  1066. register_error(dev, "Send Feature Report DeviceIoControl");
  1067. return -1;
  1068. }
  1069. }
  1070. /* Wait here until the write is done. This makes
  1071. hid_get_feature_report() synchronous. */
  1072. res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/);
  1073. if (!res) {
  1074. /* The operation failed. */
  1075. register_error(dev, "Send Feature Report GetOverLappedResult");
  1076. return -1;
  1077. }
  1078. return bytes_returned;
  1079. #endif
  1080. }
  1081. void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev)
  1082. {
  1083. typedef BOOL (WINAPI *CancelIoEx_t)(HANDLE hFile, LPOVERLAPPED lpOverlapped);
  1084. CancelIoEx_t CancelIoExFunc = (CancelIoEx_t)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "CancelIoEx");
  1085. if (!dev)
  1086. return;
  1087. if (CancelIoExFunc) {
  1088. CancelIoExFunc(dev->device_handle, NULL);
  1089. } else {
  1090. /* Windows XP, this will only cancel I/O on the current thread */
  1091. CancelIo(dev->device_handle);
  1092. }
  1093. if (dev->read_pending) {
  1094. DWORD bytes_read = 0;
  1095. GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);
  1096. }
  1097. free_hid_device(dev);
  1098. }
  1099. int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
  1100. {
  1101. BOOL res;
  1102. res = HidD_GetManufacturerString(dev->device_handle, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  1103. if (!res) {
  1104. register_error(dev, "HidD_GetManufacturerString");
  1105. return -1;
  1106. }
  1107. return 0;
  1108. }
  1109. int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
  1110. {
  1111. BOOL res;
  1112. res = HidD_GetProductString(dev->device_handle, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  1113. if (!res) {
  1114. register_error(dev, "HidD_GetProductString");
  1115. return -1;
  1116. }
  1117. return 0;
  1118. }
  1119. int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
  1120. {
  1121. BOOL res;
  1122. res = HidD_GetSerialNumberString(dev->device_handle, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  1123. if (!res) {
  1124. register_error(dev, "HidD_GetSerialNumberString");
  1125. return -1;
  1126. }
  1127. return 0;
  1128. }
  1129. int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
  1130. {
  1131. BOOL res;
  1132. res = HidD_GetIndexedString(dev->device_handle, string_index, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
  1133. if (!res) {
  1134. register_error(dev, "HidD_GetIndexedString");
  1135. return -1;
  1136. }
  1137. return 0;
  1138. }
  1139. HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
  1140. {
  1141. return (wchar_t*)dev->last_error_str;
  1142. }
  1143. #if 0
  1144. /*#define PICPGM*/
  1145. /*#define S11*/
  1146. #define P32
  1147. #ifdef S11
  1148. unsigned short VendorID = 0xa0a0;
  1149. unsigned short ProductID = 0x0001;
  1150. #endif
  1151. #ifdef P32
  1152. unsigned short VendorID = 0x04d8;
  1153. unsigned short ProductID = 0x3f;
  1154. #endif
  1155. #ifdef PICPGM
  1156. unsigned short VendorID = 0x04d8;
  1157. unsigned short ProductID = 0x0033;
  1158. #endif
  1159. int __cdecl main(int argc, char* argv[])
  1160. {
  1161. int i, res;
  1162. unsigned char buf[65];
  1163. UNREFERENCED_PARAMETER(argc);
  1164. UNREFERENCED_PARAMETER(argv);
  1165. /* Set up the command buffer. */
  1166. memset(buf,0x00,sizeof(buf));
  1167. buf[0] = 0;
  1168. buf[1] = 0x81;
  1169. /* Open the device. */
  1170. int handle = open(VendorID, ProductID, L"12345");
  1171. if (handle < 0)
  1172. printf("unable to open device\n");
  1173. /* Toggle LED (cmd 0x80) */
  1174. buf[1] = 0x80;
  1175. res = write(handle, buf, 65);
  1176. if (res < 0)
  1177. printf("Unable to write()\n");
  1178. /* Request state (cmd 0x81) */
  1179. buf[1] = 0x81;
  1180. write(handle, buf, 65);
  1181. if (res < 0)
  1182. printf("Unable to write() (2)\n");
  1183. /* Read requested state */
  1184. read(handle, buf, 65);
  1185. if (res < 0)
  1186. printf("Unable to read()\n");
  1187. /* Print out the returned buffer. */
  1188. for (i = 0; i < 4; i++)
  1189. printf("buf[%d]: %d\n", i, buf[i]);
  1190. return 0;
  1191. }
  1192. #endif
  1193. #ifdef __cplusplus
  1194. } /* extern "C" */
  1195. #endif