forked from libusb/hidapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hid.c
2559 lines (2229 loc) · 97.5 KB
/
hid.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************
HIDAPI - Multi-Platform library for
communication with HID devices.
Alan Ott
Signal 11 Software
8/22/2009
Copyright 2009, All Rights Reserved.
At the discretion of the user of this library,
this software may be licensed under the terms of the
GNU General Public License v3, a BSD-Style license, or the
original HIDAPI license as outlined in the LICENSE.txt,
LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
files located at the root of the source distribution.
These files may also be found in the public source
code repository located at:
https://github.com/libusb/hidapi .
********************************************************/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
// Do not warn about mbsrtowcs and wcsncpy usage.
// https://docs.microsoft.com/cpp/c-runtime-library/security-features-in-the-crt
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <windows.h>
#ifndef _NTDEF_
typedef LONG NTSTATUS;
#endif
#ifdef __MINGW32__
#include <ntdef.h>
#include <winbase.h>
#endif
#ifdef __CYGWIN__
#include <ntdef.h>
#define _wcsdup wcsdup
#endif
/* The maximum number of characters that can be passed into the
HidD_Get*String() functions without it failing.*/
#define MAX_STRING_WCHARS 0xFFF
/*#define HIDAPI_USE_DDK*/
#ifdef __cplusplus
extern "C" {
#endif
#include <setupapi.h>
#include <winioctl.h>
#ifdef HIDAPI_USE_DDK
#include <hidsdi.h>
#endif
/* Copied from inc/ddk/hidclass.h, part of the Windows DDK. */
#define HID_OUT_CTL_CODE(id) \
CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
#define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100)
#define IOCTL_HID_GET_INPUT_REPORT HID_OUT_CTL_CODE(104)
#ifdef __cplusplus
} /* extern "C" */
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wctype.h>
#include "hidapi.h"
#undef MIN
#define MIN(x,y) ((x) < (y)? (x): (y))
#ifdef __cplusplus
extern "C" {
#endif
static struct hid_api_version api_version = {
.major = HID_API_VERSION_MAJOR,
.minor = HID_API_VERSION_MINOR,
.patch = HID_API_VERSION_PATCH
};
#ifndef HIDAPI_USE_DDK
/* Since we're not building with the DDK, and the HID header
files aren't part of the SDK, we have to define all this
stuff here. In lookup_functions(), the function pointers
defined below are set. */
typedef struct _HIDD_ATTRIBUTES{
ULONG Size;
USHORT VendorID;
USHORT ProductID;
USHORT VersionNumber;
} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
typedef USHORT USAGE, *PUSAGE;
typedef struct _HIDP_CAPS {
USAGE Usage;
USAGE UsagePage;
USHORT InputReportByteLength;
USHORT OutputReportByteLength;
USHORT FeatureReportByteLength;
USHORT Reserved[17];
USHORT NumberLinkCollectionNodes;
USHORT NumberInputButtonCaps;
USHORT NumberInputValueCaps;
USHORT NumberInputDataIndices;
USHORT NumberOutputButtonCaps;
USHORT NumberOutputValueCaps;
USHORT NumberOutputDataIndices;
USHORT NumberFeatureButtonCaps;
USHORT NumberFeatureValueCaps;
USHORT NumberFeatureDataIndices;
} HIDP_CAPS, *PHIDP_CAPS;
typedef struct _HIDP_DATA {
USHORT DataIndex;
USHORT Reserved;
union {
ULONG RawValue;
BOOLEAN On;
};
} HIDP_DATA, * PHIDP_DATA;
//typedef void* PHIDP_PREPARSED_DATA;
typedef struct _HIDP_LINK_COLLECTION_NODE {
USAGE LinkUsage;
USAGE LinkUsagePage;
USHORT Parent;
USHORT NumberOfChildren;
USHORT NextSibling;
USHORT FirstChild;
ULONG CollectionType : 8;
ULONG IsAlias : 1;
ULONG Reserved : 23;
PVOID UserContext;
} HIDP_LINK_COLLECTION_NODE, * PHIDP_LINK_COLLECTION_NODE;
typedef enum _HIDP_REPORT_TYPE {
HidP_Input,
HidP_Output,
HidP_Feature,
NUM_OF_HIDP_REPORT_TYPES
} HIDP_REPORT_TYPE;
/// <summary>
/// Contains information about one global item that the HID parser did not recognize.
/// </summary>
typedef struct _HIDP_UNKNOWN_TOKEN {
UCHAR Token; ///< Specifies the one-byte prefix of a global item.
UCHAR Reserved[3];
ULONG BitField; ///< Specifies the data part of the global item.
} HIDP_UNKNOWN_TOKEN, * PHIDP_UNKNOWN_TOKEN;
#define HIDP_STATUS_SUCCESS 0x110000
#define HIDP_STATUS_NULL 0x80110001
#define HIDP_STATUS_INVALID_PREPARSED_DATA 0xc0110001
#define HIDP_STATUS_INVALID_REPORT_TYPE 0xc0110002
#define HIDP_STATUS_INVALID_REPORT_LENGTH 0xc0110003
#define HIDP_STATUS_USAGE_NOT_FOUND 0xc0110004
#define HIDP_STATUS_VALUE_OUT_OF_RANGE 0xc0110005
#define HIDP_STATUS_BAD_LOG_PHY_VALUES 0xc0110006
#define HIDP_STATUS_BUFFER_TOO_SMALL 0xc0110007
#define HIDP_STATUS_INTERNAL_ERROR 0xc0110008
#define HIDP_STATUS_I8042_TRANS_UNKNOWN 0xc0110009
#define HIDP_STATUS_INCOMPATIBLE_REPORT_ID 0xc011000a
#define HIDP_STATUS_NOT_VALUE_ARRAY 0xc011000b
#define HIDP_STATUS_IS_VALUE_ARRAY 0xc011000c
#define HIDP_STATUS_DATA_INDEX_NOT_FOUND 0xc011000d
#define HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE 0xc011000e
#define HIDP_STATUS_BUTTON_NOT_PRESSED 0xc011000f
#define HIDP_STATUS_REPORT_DOES_NOT_EXIST 0xc0110010
#define HIDP_STATUS_NOT_IMPLEMENTED 0xc0110020
#define HIDP_STATUS_I8242_TRANS_UNKNOWN 0xc0110009
typedef struct _hid_pp_caps_info {
USHORT FirstCap;
USHORT NumberOfCaps; // Includes empty caps after LastCap
USHORT LastCap;
USHORT ReportByteLength;
} hid_pp_caps_info, * phid_pp_caps_info;
typedef struct _hid_pp_link_collection_node {
USAGE LinkUsage;
USAGE LinkUsagePage;
USHORT Parent;
USHORT NumberOfChildren;
USHORT NextSibling;
USHORT FirstChild;
ULONG CollectionType : 8;
ULONG IsAlias : 1;
ULONG Reserved : 23;
// Same as the public API structure HIDP_LINK_COLLECTION_NODE, but without PVOID UserContext at the end
} hid_pp_link_collection_node, * phid_pp_link_collection_node;
typedef struct _hid_pp_cap {
USAGE UsagePage;
UCHAR ReportID;
UCHAR BitPosition;
USHORT BitSize; // WIN32 term for Report Size
USHORT ReportCount;
USHORT BytePosition;
USHORT BitCount;
ULONG BitField;
USHORT NextBytePosition;
USHORT LinkCollection;
USAGE LinkUsagePage;
USAGE LinkUsage;
// 8 Flags in one byte
BOOLEAN IsMultipleItemsForArray:1;
BOOLEAN IsPadding:1;
BOOLEAN IsButtonCap:1;
BOOLEAN IsAbsolute:1;
BOOLEAN IsRange:1;
BOOLEAN IsAlias:1; // IsAlias is set to TRUE in the first n-1 capability structures added to the capability array. IsAlias set to FALSE in the nth capability structure.
BOOLEAN IsStringRange:1;
BOOLEAN IsDesignatorRange:1;
// 8 Flags in one byte
BOOLEAN Reserved1[3];
struct _HIDP_UNKNOWN_TOKEN UnknownTokens[4]; // 4 x 8 Byte
union {
struct {
USAGE UsageMin;
USAGE UsageMax;
USHORT StringMin;
USHORT StringMax;
USHORT DesignatorMin;
USHORT DesignatorMax;
USHORT DataIndexMin;
USHORT DataIndexMax;
} Range;
struct {
USAGE Usage;
USAGE Reserved1;
USHORT StringIndex;
USHORT Reserved2;
USHORT DesignatorIndex;
USHORT Reserved3;
USHORT DataIndex;
USHORT Reserved4;
} NotRange;
};
union {
struct {
LONG LogicalMin;
LONG LogicalMax;
} Button;
struct {
BOOLEAN HasNull;
UCHAR Reserved4[3];
LONG LogicalMin;
LONG LogicalMax;
LONG PhysicalMin;
LONG PhysicalMax;
} NotButton;
};
ULONG Units;
ULONG UnitsExp;
} hid_pp_cap, * phid_pp_cap;
typedef struct _hid_preparsed_data {
UCHAR MagicKey[8];
USAGE Usage;
USAGE UsagePage;
USHORT Reserved[2];
// CAPS structure for Input, Output and Feature
hid_pp_caps_info caps_info[3];
USHORT FirstByteOfLinkCollectionArray;
USHORT NumberLinkCollectionNodes;
// MINGW: flexible array member in union not supported - but works with MSVC
//union {
hid_pp_cap caps[];
//hid_pp_link_collection_node LinkCollectionArray[];
//};
} HIDP_PREPARSED_DATA, * PHIDP_PREPARSED_DATA;
typedef void(__stdcall* HidD_GetHidGuid_)(LPGUID hid_guid);
typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib);
typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len);
typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length);
typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length);
typedef BOOLEAN (__stdcall *HidD_GetInputReport_)(HANDLE handle, PVOID data, ULONG length);
typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len);
typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, PHIDP_PREPARSED_DATA *preparsed_data);
typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(PHIDP_PREPARSED_DATA preparsed_data);
typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS *caps);
typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers);
typedef NTSTATUS (__stdcall *HidP_GetLinkCollectionNodes_)(PHIDP_LINK_COLLECTION_NODE link_collection_nodes, PULONG link_collection_nodes_length, PHIDP_PREPARSED_DATA preparsed_data);
static HidD_GetHidGuid_ HidD_GetHidGuid;
static HidD_GetAttributes_ HidD_GetAttributes;
static HidD_GetSerialNumberString_ HidD_GetSerialNumberString;
static HidD_GetManufacturerString_ HidD_GetManufacturerString;
static HidD_GetProductString_ HidD_GetProductString;
static HidD_SetFeature_ HidD_SetFeature;
static HidD_GetFeature_ HidD_GetFeature;
static HidD_GetInputReport_ HidD_GetInputReport;
static HidD_GetIndexedString_ HidD_GetIndexedString;
static HidD_GetPreparsedData_ HidD_GetPreparsedData;
static HidD_FreePreparsedData_ HidD_FreePreparsedData;
static HidP_GetCaps_ HidP_GetCaps;
static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers;
static HidP_GetLinkCollectionNodes_ HidP_GetLinkCollectionNodes;
static HMODULE lib_handle = NULL;
static BOOLEAN initialized = FALSE;
typedef DWORD RETURN_TYPE;
typedef RETURN_TYPE CONFIGRET;
typedef DWORD DEVNODE, DEVINST;
typedef DEVNODE* PDEVNODE, * PDEVINST;
typedef WCHAR* DEVNODEID_W, * DEVINSTID_W;
#define CR_SUCCESS (0x00000000)
#define CR_BUFFER_SMALL (0x0000001A)
#define CM_LOCATE_DEVNODE_NORMAL 0x00000000
#define DEVPROP_TYPEMOD_LIST 0x00002000
#define DEVPROP_TYPE_STRING 0x00000012
#define DEVPROP_TYPE_STRING_LIST (DEVPROP_TYPE_STRING|DEVPROP_TYPEMOD_LIST)
typedef CONFIGRET(__stdcall* CM_Locate_DevNodeW_)(PDEVINST pdnDevInst, DEVINSTID_W pDeviceID, ULONG ulFlags);
typedef CONFIGRET(__stdcall* CM_Get_Parent_)(PDEVINST pdnDevInst, DEVINST dnDevInst, ULONG ulFlags);
typedef CONFIGRET(__stdcall* CM_Get_DevNode_PropertyW_)(DEVINST dnDevInst, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags);
typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_PropertyW_)(LPCWSTR pszDeviceInterface, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags);
static CM_Locate_DevNodeW_ CM_Locate_DevNodeW = NULL;
static CM_Get_Parent_ CM_Get_Parent = NULL;
static CM_Get_DevNode_PropertyW_ CM_Get_DevNode_PropertyW = NULL;
static CM_Get_Device_Interface_PropertyW_ CM_Get_Device_Interface_PropertyW = NULL;
static HMODULE cfgmgr32_lib_handle = NULL;
#endif /* HIDAPI_USE_DDK */
struct hid_device_ {
HANDLE device_handle;
BOOL blocking;
USHORT output_report_length;
unsigned char *write_buf;
size_t input_report_length;
USHORT feature_report_length;
unsigned char *feature_buf;
void *last_error_str;
DWORD last_error_num;
BOOL read_pending;
char *read_buf;
OVERLAPPED ol;
OVERLAPPED write_ol;
struct hid_device_info* device_info;
};
static hid_device *new_hid_device()
{
hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
dev->device_handle = INVALID_HANDLE_VALUE;
dev->blocking = TRUE;
dev->output_report_length = 0;
dev->write_buf = NULL;
dev->input_report_length = 0;
dev->feature_report_length = 0;
dev->feature_buf = NULL;
dev->last_error_str = NULL;
dev->last_error_num = 0;
dev->read_pending = FALSE;
dev->read_buf = NULL;
memset(&dev->ol, 0, sizeof(dev->ol));
dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL);
memset(&dev->write_ol, 0, sizeof(dev->write_ol));
dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*inital state f=nonsignaled*/, NULL);
dev->device_info = NULL;
return dev;
}
static void free_hid_device(hid_device *dev)
{
CloseHandle(dev->ol.hEvent);
CloseHandle(dev->write_ol.hEvent);
CloseHandle(dev->device_handle);
LocalFree(dev->last_error_str);
free(dev->write_buf);
free(dev->feature_buf);
free(dev->read_buf);
free(dev->device_info);
free(dev);
}
static void register_error(hid_device *dev, const char *op)
{
WCHAR *ptr, *msg;
(void)op; // unreferenced param
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&msg, 0/*sz*/,
NULL);
/* Get rid of the CR and LF that FormatMessage() sticks at the
end of the message. Thanks Microsoft! */
ptr = msg;
while (*ptr) {
if (*ptr == L'\r') {
*ptr = L'\0';
break;
}
ptr++;
}
/* Store the message off in the Device entry so that
the hid_error() function can pick it up. */
LocalFree(dev->last_error_str);
dev->last_error_str = msg;
}
#ifndef HIDAPI_USE_DDK
static int lookup_functions()
{
lib_handle = LoadLibraryA("hid.dll");
if (lib_handle) {
#if defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-function-type"
#endif
#define RESOLVE(x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) return -1;
RESOLVE(HidD_GetHidGuid);
RESOLVE(HidD_GetAttributes);
RESOLVE(HidD_GetSerialNumberString);
RESOLVE(HidD_GetManufacturerString);
RESOLVE(HidD_GetProductString);
RESOLVE(HidD_SetFeature);
RESOLVE(HidD_GetFeature);
RESOLVE(HidD_GetInputReport);
RESOLVE(HidD_GetIndexedString);
RESOLVE(HidD_GetPreparsedData);
RESOLVE(HidD_FreePreparsedData);
RESOLVE(HidP_GetCaps);
RESOLVE(HidD_SetNumInputBuffers);
RESOLVE(HidP_GetLinkCollectionNodes);
#undef RESOLVE
#if defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
}
else
return -1;
cfgmgr32_lib_handle = LoadLibraryA("cfgmgr32.dll");
if (cfgmgr32_lib_handle) {
#if defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-function-type"
#endif
#define RESOLVE(x) x = (x##_)GetProcAddress(cfgmgr32_lib_handle, #x);
RESOLVE(CM_Locate_DevNodeW);
RESOLVE(CM_Get_Parent);
RESOLVE(CM_Get_DevNode_PropertyW);
RESOLVE(CM_Get_Device_Interface_PropertyW);
#undef RESOLVE
#if defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
}
else {
CM_Locate_DevNodeW = NULL;
CM_Get_Parent = NULL;
CM_Get_DevNode_PropertyW = NULL;
CM_Get_Device_Interface_PropertyW = NULL;
}
return 0;
}
#endif
/// <summary>
/// Enumeration of all report descriptor item One-Byte prefixes from the USB HID spec 1.11
/// The two least significiant bits nn represent the size of the item and must be added to this values
/// </summary>
typedef enum rd_items_ {
rd_main_input = 0x80, ///< 1000 00 nn
rd_main_output = 0x90, ///< 1001 00 nn
rd_main_feature = 0xB0, ///< 1011 00 nn
rd_main_collection = 0xA0, ///< 1010 00 nn
rd_main_collection_end = 0xC0, ///< 1100 00 nn
rd_global_usage_page = 0x04, ///< 0000 01 nn
rd_global_logical_minimum = 0x14, ///< 0001 01 nn
rd_global_logical_maximum = 0x24, ///< 0010 01 nn
rd_global_physical_minimum = 0x34, ///< 0011 01 nn
rd_global_physical_maximum = 0x44, ///< 0100 01 nn
rd_global_unit_exponent = 0x54, ///< 0101 01 nn
rd_global_unit = 0x64, ///< 0110 01 nn
rd_global_report_size = 0x74, ///< 0111 01 nn
rd_global_report_id = 0x84, ///< 1000 01 nn
rd_global_report_count = 0x94, ///< 1001 01 nn
rd_global_push = 0xA4, ///< 1010 01 nn
rd_global_pop = 0xB4, ///< 1011 01 nn
rd_local_usage = 0x08, ///< 0000 10 nn
rd_local_usage_minimum = 0x18, ///< 0001 10 nn
rd_local_usage_maximum = 0x28, ///< 0010 10 nn
rd_local_designator_index = 0x38, ///< 0011 10 nn
rd_local_designator_minimum = 0x48, ///< 0100 10 nn
rd_local_designator_maximum = 0x58, ///< 0101 10 nn
rd_local_string = 0x78, ///< 0111 10 nn
rd_local_string_minimum = 0x88, ///< 1000 10 nn
rd_local_string_maximum = 0x98, ///< 1001 10 nn
rd_local_delimiter = 0xA8 ///< 1010 10 nn
} RD_ITEMS;
/// <summary>
/// List element of the encoded report descriptor
/// </summary>
struct rd_item_byte
{
unsigned char byte;
struct rd_item_byte* next;
};
/// <summary>
/// Function that appends a byte to encoded report descriptor list
/// </summary>
/// <param name="byte">Single byte to append</param>
/// <param name="list">Pointer to the list</param>
static void rd_append_byte(unsigned char byte, struct rd_item_byte** list) {
struct rd_item_byte* new_list_element;
/* Determine last list position */
while (*list != NULL)
{
list = &(*list)->next;
}
new_list_element = malloc(sizeof(*new_list_element)); // Create new list entry
new_list_element->byte = byte;
new_list_element->next = NULL; // Marks last element of list
*list = new_list_element;
}
/// <summary>
/// Writes a short report descriptor item according USB HID spec 1.11 chapter 6.2.2.2
/// </summary>
/// <param name="rd_item">Enumeration identifying type (Main, Global, Local) and function (e.g Usage or Report Count) of the item.</param>
/// <param name="data">Data (Size depends on rd_item 0,1,2 or 4bytes)</param>
/// <param name="list">Chained list of report descriptor bytes</param>
/// <returns>Returns 0 if successful, -1 for error</returns>
static int rd_write_short_item(RD_ITEMS rd_item, LONG64 data, struct rd_item_byte** list) {
if (rd_item & 0x03) {
return -1; // Invaid input data
}
if (rd_item == rd_main_collection_end) {
// Item without data
unsigned char oneBytePrefix = rd_item + 0x00;
rd_append_byte(oneBytePrefix, list);
printf("%02X ", oneBytePrefix);
} else if ((rd_item == rd_global_logical_minimum) ||
(rd_item == rd_global_logical_maximum) ||
(rd_item == rd_global_physical_minimum) ||
(rd_item == rd_global_physical_maximum)) {
// Item with signed integer data
if ((data >= -128) && (data <= 127)) {
unsigned char oneBytePrefix = rd_item + 0x01;
char localData = (char)data;
rd_append_byte(oneBytePrefix, list);
rd_append_byte(localData & 0xFF, list);
printf("%02X %02X ", oneBytePrefix, localData & 0xFF);
}
else if ((data >= -32768) && (data <= 32767)) {
unsigned char oneBytePrefix = rd_item + 0x02;
INT16 localData = (INT16)data;
rd_append_byte(oneBytePrefix, list);
rd_append_byte(localData & 0xFF, list);
rd_append_byte(localData >> 8 & 0xFF, list);
printf("%02X %02X %02X ", oneBytePrefix, localData & 0xFF, localData >> 8 & 0xFF);
}
else if ((data >= -2147483648LL) && (data <= 2147483647)) {
unsigned char oneBytePrefix = rd_item + 0x03;
INT32 localData = (INT32)data;
rd_append_byte(oneBytePrefix, list);
rd_append_byte(localData & 0xFF, list);
rd_append_byte(localData >> 8 & 0xFF, list);
rd_append_byte(localData >> 16 & 0xFF, list);
rd_append_byte(localData >> 24 & 0xFF, list);
printf("%02X %02X %02X %02X %02X ", oneBytePrefix, localData & 0xFF, localData >> 8 & 0xFF, localData >> 16 & 0xFF, localData >> 24 & 0xFF);
} else {
// Error data out of range
return -1;
}
} else {
// Item with unsigned integer data
if ((data >= 0) && (data <= 0xFF)) {
unsigned char oneBytePrefix = rd_item + 0x01;
unsigned char localData = (unsigned char)data;
rd_append_byte(oneBytePrefix, list);
rd_append_byte(localData & 0xFF, list);
printf("%02X %02X ", oneBytePrefix, localData & 0xFF);
}
else if ((data >= 0) && (data <= 0xFFFF)) {
unsigned char oneBytePrefix = rd_item + 0x02;
UINT16 localData = (UINT16)data;
rd_append_byte(oneBytePrefix, list);
rd_append_byte(localData & 0xFF, list);
rd_append_byte(localData >> 8 & 0xFF, list);
printf("%02X %02X %02X ", oneBytePrefix, localData & 0xFF, localData >> 8 & 0xFF);
}
else if ((data >= 0) && (data <= 0xFFFFFFFF)) {
unsigned char oneBytePrefix = rd_item + 0x03;
UINT32 localData = (UINT32)data;
rd_append_byte(oneBytePrefix, list);
rd_append_byte(localData & 0xFF, list);
rd_append_byte(localData >> 8 & 0xFF, list);
rd_append_byte(localData >> 16 & 0xFF, list);
rd_append_byte(localData >> 24 & 0xFF, list);
printf("%02X %02X %02X %02X %02X ", oneBytePrefix, localData & 0xFF, localData >> 8 & 0xFF, localData >> 16 & 0xFF, localData >> 24 & 0xFF);
} else {
// Error data out of range
return -1;
}
}
return 0;
}
/// <summary>
/// Writes a long report descriptor item according USB HID spec 1.11 chapter 6.2.2.3
/// </summary>
/// <param name="data">Optional data items (NULL if bDataSize is 0)</param>
/// <param name="bLongItemTag">Long item tag (8 bits)</param>
/// <param name="bDataSize">Size of long item data (range 0-255 in Bytes)</param>
/// <returns></returns>
static int rd_write_long_item(unsigned char* data, unsigned char bLongItemTag, unsigned char bDataSize) {
// Not implemented
}
typedef enum _RD_MAIN_ITEMS {
rd_input = HidP_Input,
rd_output = HidP_Output,
rd_feature = HidP_Feature,
rd_collection,
rd_collection_end,
rd_delimiter_open,
rd_delimiter_usage,
rd_delimiter_close,
RD_NUM_OF_MAIN_ITEMS
} RD_MAIN_ITEMS;
typedef struct _RD_BIT_RANGE {
int FirstBit;
int LastBit;
} RD_BIT_RANGE;
typedef enum _RD_ITEM_NODE_TYPE {
rd_item_node_cap,
rd_item_node_padding,
rd_item_node_collection,
RD_NUM_OF_ITEM_NODE_TYPES
} RD_NODE_TYPE;
struct rd_main_item_node
{
int FirstBit; ///< Position of first bit in report (counting from 0)
int LastBit; ///< Position of last bit in report (counting from 0)
RD_NODE_TYPE TypeOfNode; ///< Information if caps index refers to the array of button caps, value caps,
///< or if the node is just a padding element to fill unused bit positions.
///< The node can also be a collection node without any bits in the report.
int CapsIndex; ///< Index in the array of caps
int CollectionIndex; ///< Index in the array of link collections
RD_MAIN_ITEMS MainItemType; ///< Input, Output, Feature, Collection or Collection End
unsigned char ReportID;
struct rd_main_item_node* next;
};
static struct rd_main_item_node* rd_append_main_item_node(int first_bit, int last_bit, RD_NODE_TYPE type_of_node, int caps_index, int collection_index, RD_MAIN_ITEMS main_item_type, unsigned char report_id, struct rd_main_item_node** list) {
struct rd_main_item_node* new_list_node;
// Determine last node in the list
while (*list != NULL)
{
list = &(*list)->next;
}
new_list_node = malloc(sizeof(*new_list_node)); // Create new list entry
new_list_node->FirstBit = first_bit;
new_list_node->LastBit = last_bit;
new_list_node->TypeOfNode = type_of_node;
new_list_node->CapsIndex = caps_index;
new_list_node->CollectionIndex = collection_index;
new_list_node->MainItemType = main_item_type;
new_list_node->ReportID = report_id;
new_list_node->next = NULL; // NULL marks last node in the list
*list = new_list_node;
return new_list_node;
}
static struct rd_main_item_node* rd_insert_main_item_node(int first_bit, int last_bit, RD_NODE_TYPE type_of_node, int caps_index, int collection_index, RD_MAIN_ITEMS main_item_type, unsigned char report_id, struct rd_main_item_node** list) {
// Insert item after the main item node referenced by list
struct rd_main_item_node* next_item = (*list)->next;
(*list)->next = NULL;
rd_append_main_item_node(first_bit, last_bit, type_of_node, caps_index, collection_index, main_item_type, report_id, list);
(*list)->next->next = next_item;
return (*list)->next;
}
static struct rd_main_item_node* rd_search_main_item_list_for_bit_position(int search_bit, RD_MAIN_ITEMS main_item_type, unsigned char report_id, struct rd_main_item_node** list) {
// Determine first INPUT/OUTPUT/FEATURE main item, where the last bit position is equal or greater than the search bit position
while (((*list)->next->MainItemType != rd_collection) &&
((*list)->next->MainItemType != rd_collection_end) &&
!(((*list)->next->LastBit >= search_bit) &&
((*list)->next->ReportID == report_id) &&
((*list)->next->MainItemType == main_item_type))
)
{
list = &(*list)->next;
}
return *list;
}
static HANDLE open_device(const char *path, BOOL open_rw)
{
HANDLE handle;
DWORD desired_access = (open_rw)? (GENERIC_WRITE | GENERIC_READ): 0;
DWORD share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
handle = CreateFileA(path,
desired_access,
share_mode,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/
0);
return handle;
}
HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version()
{
return &api_version;
}
HID_API_EXPORT const char* HID_API_CALL hid_version_str()
{
return HID_API_VERSION_STR;
}
int HID_API_EXPORT hid_init(void)
{
#ifndef HIDAPI_USE_DDK
if (!initialized) {
if (lookup_functions() < 0) {
hid_exit();
return -1;
}
initialized = TRUE;
}
#endif
return 0;
}
int HID_API_EXPORT hid_exit(void)
{
#ifndef HIDAPI_USE_DDK
if (lib_handle)
FreeLibrary(lib_handle);
lib_handle = NULL;
if (cfgmgr32_lib_handle)
FreeLibrary(cfgmgr32_lib_handle);
cfgmgr32_lib_handle = NULL;
initialized = FALSE;
#endif
return 0;
}
static void hid_internal_get_ble_info(struct hid_device_info* dev, DEVINST dev_node)
{
ULONG len;
CONFIGRET cr;
DEVPROPTYPE property_type;
static DEVPROPKEY DEVPKEY_NAME = { { 0xb725f130, 0x47ef, 0x101a, 0xa5, 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac }, 10 }; // DEVPROP_TYPE_STRING
static DEVPROPKEY PKEY_DeviceInterface_Bluetooth_DeviceAddress = { { 0x2BD67D8B, 0x8BEB, 0x48D5, 0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A }, 1 }; // DEVPROP_TYPE_STRING
static DEVPROPKEY PKEY_DeviceInterface_Bluetooth_Manufacturer = { { 0x2BD67D8B, 0x8BEB, 0x48D5, 0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A }, 4 }; // DEVPROP_TYPE_STRING
/* Manufacturer String */
len = 0;
cr = CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_Manufacturer, &property_type, NULL, &len, 0);
if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) {
free(dev->manufacturer_string);
dev->manufacturer_string = (wchar_t*)calloc(len, sizeof(BYTE));
CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_Manufacturer, &property_type, (PBYTE)dev->manufacturer_string, &len, 0);
}
/* Serial Number String (MAC Address) */
len = 0;
cr = CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_DeviceAddress, &property_type, NULL, &len, 0);
if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) {
free(dev->serial_number);
dev->serial_number = (wchar_t*)calloc(len, sizeof(BYTE));
CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_DeviceAddress, &property_type, (PBYTE)dev->serial_number, &len, 0);
}
/* Get devnode grandparent to reach out Bluetooth LE device node */
cr = CM_Get_Parent(&dev_node, dev_node, 0);
if (cr != CR_SUCCESS)
return;
/* Product String */
len = 0;
cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_NAME, &property_type, NULL, &len, 0);
if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) {
free(dev->product_string);
dev->product_string = (wchar_t*)calloc(len, sizeof(BYTE));
CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_NAME, &property_type, (PBYTE)dev->product_string, &len, 0);
}
}
static void hid_internal_get_info(struct hid_device_info* dev)
{
const char *tmp = NULL;
wchar_t *interface_path = NULL, *device_id = NULL, *compatible_ids = NULL;
mbstate_t state;
ULONG len;
CONFIGRET cr;
DEVPROPTYPE property_type;
DEVINST dev_node;
static DEVPROPKEY DEVPKEY_Device_InstanceId = { { 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57 }, 256 }; // DEVPROP_TYPE_STRING
static DEVPROPKEY DEVPKEY_Device_CompatibleIds = { { 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}, 4 }; // DEVPROP_TYPE_STRING_LIST
if (!CM_Get_Device_Interface_PropertyW ||
!CM_Locate_DevNodeW ||
!CM_Get_Parent ||
!CM_Get_DevNode_PropertyW)
goto end;
tmp = dev->path;
len = (ULONG)strlen(tmp);
interface_path = (wchar_t*)calloc(len + 1, sizeof(wchar_t));
memset(&state, 0, sizeof(state));
if (mbsrtowcs(interface_path, &tmp, len, &state) == (size_t)-1)
goto end;
/* Get the device id from interface path */
len = 0;
cr = CM_Get_Device_Interface_PropertyW(interface_path, &DEVPKEY_Device_InstanceId, &property_type, NULL, &len, 0);
if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) {
device_id = (wchar_t*)calloc(len, sizeof(BYTE));
cr = CM_Get_Device_Interface_PropertyW(interface_path, &DEVPKEY_Device_InstanceId, &property_type, (PBYTE)device_id, &len, 0);
}
if (cr != CR_SUCCESS)
goto end;
/* Open devnode from device id */
cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL);
if (cr != CR_SUCCESS)
goto end;
/* Get devnode parent */
cr = CM_Get_Parent(&dev_node, dev_node, 0);
if (cr != CR_SUCCESS)
goto end;
/* Get the compatible ids from parent devnode */
len = 0;
cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_CompatibleIds, &property_type, NULL, &len, 0);
if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING_LIST) {
compatible_ids = (wchar_t*)calloc(len, sizeof(BYTE));
cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_CompatibleIds, &property_type, (PBYTE)compatible_ids, &len, 0);
}
if (cr != CR_SUCCESS)
goto end;
/* Now we can parse parent's compatible IDs to find out the device bus type */
for (wchar_t* compatible_id = compatible_ids; *compatible_id; compatible_id += wcslen(compatible_id) + 1) {
/* Normalize to upper case */
for (wchar_t* p = compatible_id; *p; ++p) *p = towupper(*p);
/* Bluetooth LE devices */
if (wcsstr(compatible_id, L"BTHLEDEVICE") != NULL) {
/* HidD_GetProductString/HidD_GetManufacturerString/HidD_GetSerialNumberString is not working for BLE HID devices
Request this info via dev node properties instead.
https://docs.microsoft.com/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html */
hid_internal_get_ble_info(dev, dev_node);
break;
}
}
end:
free(interface_path);
free(device_id);
free(compatible_ids);
}
static struct hid_device_info *hid_get_device_info(const char *path, HANDLE handle)
{
struct hid_device_info *dev = NULL; /* return object */
BOOL res;
HIDD_ATTRIBUTES attrib;
PHIDP_PREPARSED_DATA pp_data = NULL;
HIDP_CAPS caps;
#define WSTR_LEN 512
wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */
/* Create the record. */
dev = (struct hid_device_info*)calloc(1, sizeof(struct hid_device_info));
/* Fill out the record */
dev->next = NULL;
if (path) {
size_t len = strlen(path);
dev->path = (char*)calloc(len + 1, sizeof(char));
memcpy(dev->path, path, len + 1);
}
else
dev->path = NULL;
attrib.Size = sizeof(HIDD_ATTRIBUTES);
res = HidD_GetAttributes(handle, &attrib);
if (res) {
/* VID/PID */
dev->vendor_id = attrib.VendorID;
dev->product_id = attrib.ProductID;
/* Release Number */
dev->release_number = attrib.VersionNumber;
}
/* Get the Usage Page and Usage for this device. */
res = HidD_GetPreparsedData(handle, &pp_data);
if (res) {
NTSTATUS nt_res = HidP_GetCaps(pp_data, &caps);
if (nt_res == HIDP_STATUS_SUCCESS) {
dev->usage_page = caps.UsagePage;
dev->usage = caps.Usage;
}
HidD_FreePreparsedData(pp_data);
}
/* Serial Number */
wstr[0] = L'\0';
res = HidD_GetSerialNumberString(handle, wstr, sizeof(wstr));
wstr[WSTR_LEN - 1] = L'\0';
dev->serial_number = _wcsdup(wstr);
/* Manufacturer String */
wstr[0] = L'\0';
res = HidD_GetManufacturerString(handle, wstr, sizeof(wstr));
wstr[WSTR_LEN - 1] = L'\0';
dev->manufacturer_string = _wcsdup(wstr);
/* Product String */
wstr[0] = L'\0';
res = HidD_GetProductString(handle, wstr, sizeof(wstr));
wstr[WSTR_LEN - 1] = L'\0';
dev->product_string = _wcsdup(wstr);
/* Interface Number. It can sometimes be parsed out of the path
on Windows if a device has multiple interfaces. See
https://docs.microsoft.com/windows-hardware/drivers/hid/hidclass-hardware-ids-for-top-level-collections
or search for "HIDClass Hardware IDs for Top-Level Collections" at Microsoft Docs. If it's not
in the path, it's set to -1. */
dev->interface_number = -1;
if (dev->path) {
char* interface_component = strstr(dev->path, "&mi_");
if (interface_component) {
char* hex_str = interface_component + 4;
char* endptr = NULL;
dev->interface_number = strtol(hex_str, &endptr, 16);
if (endptr == hex_str) {
/* The parsing failed. Set interface_number to -1. */
dev->interface_number = -1;
}
}