hid.c 25 KB

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