hid.c 26 KB

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