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