-
Notifications
You must be signed in to change notification settings - Fork 6
/
macosx_hidutilities.c
1728 lines (1507 loc) · 61 KB
/
macosx_hidutilities.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
/*
* Support for Mac OS X via the HID Utilities example code. HID Utilities
* talks to very low-level parts of the HID Manager API, which are deprecated
* in OS X 10.5. Please see macosx_hidmanager.c for the 10.5 implementation.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
#include "manymouse.h"
/*
* These APIs exist on x86_64 in 10.6, but don't actually work (they'll work
* for 32-bit x86 binaries in 10.6, though!). HID Utilities is for legacy
* Macs, going forward you want macosx_hidmanager.c instead.
*/
#if ( (defined(__APPLE__)) && (defined(i386) || defined(__POWERPC__)) )
/*
* This source is almost entirely lifted from Apple's HID Utilities
* example source code, written by George Warner:
*
* http://developer.apple.com/library/mac/#samplecode/HID_Utilities_Source/Introduction/Intro.html
*
* The source license to HID Utilities allows this sort of blatant stealing.
*
* Patches to HID Utilities have comments like "ryan added this", otherwise,
* I just tried to cut down that package to the smallest set of functions
* I needed.
*
* Scroll down for "-- END HID UTILITIES --" to see the ManyMouse glue code.
*/
#include <Carbon/Carbon.h>
#include <IOKit/IOTypes.h>
// 10.0.x
//#include <IOKit/IOUSBHIDParser.h>
// 10.1.x
#include <IOKit/hid/IOHIDUsageTables.h>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOMessage.h>
#define USE_NOTIFICATIONS 1
#define HIDREPORTERRORNUM(s,n) do {} while (false)
#define HIDREPORTERROR(s) do {} while (false)
typedef enum HIDElementTypeMask
{
kHIDElementTypeInput = 1 << 1,
kHIDElementTypeOutput = 1 << 2,
kHIDElementTypeFeature = 1 << 3,
kHIDElementTypeCollection = 1 << 4,
kHIDElementTypeIO = kHIDElementTypeInput | kHIDElementTypeOutput | kHIDElementTypeFeature,
kHIDElementTypeAll = kHIDElementTypeIO | kHIDElementTypeCollection
}HIDElementTypeMask;
enum
{
kDefaultUserMin = 0, // default user min and max used for scaling
kDefaultUserMax = 255
};
enum
{
kDeviceQueueSize = 50 // this is wired kernel memory so should be set to as small as possible
// but should account for the maximum possible events in the queue
// USB updates will likely occur at 100 Hz so one must account for this rate of
// if states change quickly (updates are only posted on state changes)
};
struct recElement
{
unsigned long type; // the type defined by IOHIDElementType in IOHIDKeys.h
long usagePage; // usage page from IOUSBHIDParser.h which defines general usage
long usage; // usage within above page from IOUSBHIDParser.h which defines specific usage
void * cookie; // unique value (within device of specific vendorID and productID) which identifies element, will NOT change
long min; // reported min value possible
long max; // reported max value possible
long scaledMin; // reported scaled min value possible
long scaledMax; // reported scaled max value possible
long size; // size in bits of data return from element
unsigned char relative; // are reports relative to last report (deltas)
unsigned char wrapping; // does element wrap around (one value higher than max is min)
unsigned char nonLinear; // are the values reported non-linear relative to element movement
unsigned char preferredState; // does element have a preferred state (such as a button)
unsigned char nullState; // does element have null state
long units; // units value is reported in (not used very often)
long unitExp; // exponent for units (also not used very often)
char name[256]; // name of element (c string)
// runtime variables
long calMin; // min returned value
long calMax; // max returned value (calibrate call)
long userMin; // user set value to scale to (scale call)
long userMax;
struct recElement * pPrevious; // previous element (NULL at list head)
struct recElement * pChild; // next child (only of collections)
struct recElement * pSibling; // next sibling (for elements and collections)
long depth;
};
typedef struct recElement recElement;
typedef recElement* pRecElement;
// ryan added this.
typedef enum
{
DISCONNECT_CONNECTED,
DISCONNECT_TELLUSER,
DISCONNECT_COMPLETE
} DisconnectState;
struct recDevice
{
void * interface; // interface to device, NULL = no interface
void * queue; // device queue, NULL = no queue
void * queueRunLoopSource; // device queue run loop source, NULL == no source
void * transaction; // output transaction interface, NULL == no interface
void * notification; // notifications
char transport[256]; // device transport (c string)
long vendorID; // id for device vendor, unique across all devices
long productID; // id for particular product, unique across all of a vendors devices
long version; // version of product
char manufacturer[256]; // name of manufacturer
char product[256]; // name of product
char serial[256]; // serial number of specific product, can be assumed unique across specific product or specific vendor (not used often)
long locID; // long representing location in USB (or other I/O) chain which device is pluged into, can identify specific device on machine
long usage; // usage page from IOUSBHID Parser.h which defines general usage
long usagePage; // usage within above page from IOUSBHID Parser.h which defines specific usage
long totalElements; // number of total elements (should be total of all elements on device including collections) (calculated, not reported by device)
long features; // number of elements of type kIOHIDElementTypeFeature
long inputs; // number of elements of type kIOHIDElementTypeInput_Misc or kIOHIDElementTypeInput_Button or kIOHIDElementTypeInput_Axis or kIOHIDElementTypeInput_ScanCodes
long outputs; // number of elements of type kIOHIDElementTypeOutput
long collections; // number of elements of type kIOHIDElementTypeCollection
long axis; // number of axis (calculated, not reported by device)
long buttons; // number of buttons (calculated, not reported by device)
long hats; // number of hat switches (calculated, not reported by device)
long sliders; // number of sliders (calculated, not reported by device)
long dials; // number of dials (calculated, not reported by device)
long wheels; // number of wheels (calculated, not reported by device)
recElement* pListElements; // head of linked list of elements
DisconnectState disconnect; // (ryan added this.)
AbsoluteTime lastScrollTime; // (ryan added this.)
int logical; // (ryan added this.)
struct recDevice* pNext; // next device
};
typedef struct recDevice recDevice;
typedef recDevice* pRecDevice;
#if USE_NOTIFICATIONS
static IONotificationPortRef gNotifyPort;
static io_iterator_t gAddedIter;
static CFRunLoopRef gRunLoop;
#endif // USE_NOTIFICATIONS
// for element retrieval
static pRecDevice gCurrentGetDevice = NULL;
static Boolean gAddAsChild = false;
static int gDepth = false;
static pRecDevice gpDeviceList = NULL;
static UInt32 gNumDevices = 0;
static Boolean HIDIsValidDevice(const pRecDevice pSearchDevice);
static pRecElement HIDGetFirstDeviceElement (pRecDevice pDevice, HIDElementTypeMask typeMask);
static pRecElement HIDGetNextDeviceElement (pRecElement pElement, HIDElementTypeMask typeMask);
static pRecDevice HIDGetFirstDevice (void);
static pRecDevice HIDGetNextDevice (pRecDevice pDevice);
static void HIDReleaseDeviceList (void);
static unsigned long HIDDequeueDevice (pRecDevice pDevice);
static void hid_GetElements (CFTypeRef refElementCurrent, pRecElement *ppCurrentElement);
static void HIDReportError(const char *err) {}
static void HIDReportErrorNum(const char *err, int num) {}
static void hid_GetCollectionElements (CFMutableDictionaryRef deviceProperties, pRecElement *ppCurrentCollection)
{
CFTypeRef refElementTop = CFDictionaryGetValue (deviceProperties, CFSTR(kIOHIDElementKey));
if (refElementTop)
hid_GetElements (refElementTop, ppCurrentCollection);
else
HIDReportError ("hid_GetCollectionElements: CFDictionaryGetValue error when creating CFTypeRef for kIOHIDElementKey.");
}
// extracts actual specific element information from each element CF dictionary entry
static void hid_GetElementInfo (CFTypeRef refElement, pRecElement pElement)
{
long number;
CFTypeRef refType;
// type, usagePage, usage already stored
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementCookieKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->cookie = (IOHIDElementCookie) number;
else
pElement->cookie = (IOHIDElementCookie) 0;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMinKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->min = number;
else
pElement->min = 0;
pElement->calMax = pElement->min;
pElement->userMin = kDefaultUserMin;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementMaxKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->max = number;
else
pElement->max = 0;
pElement->calMin = pElement->max;
pElement->userMax = kDefaultUserMax;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMin = number;
else
pElement->scaledMin = 0;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMax = number;
else
pElement->scaledMax = 0;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->size = number;
else
pElement->size = 0;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
if (refType)
pElement->relative = CFBooleanGetValue (refType);
else
pElement->relative = 0;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
if (refType)
pElement->wrapping = CFBooleanGetValue (refType);
else
pElement->wrapping = false;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
if (refType)
pElement->nonLinear = CFBooleanGetValue (refType);
else
pElement->wrapping = false;
#ifdef kIOHIDElementHasPreferredStateKey
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferredStateKey));
#else // Mac OS X 10.0 has spelling error
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
#endif
if (refType)
pElement->preferredState = CFBooleanGetValue (refType);
else
pElement->preferredState = false;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
if (refType)
pElement->nullState = CFBooleanGetValue (refType);
else
pElement->nullState = false;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUnitKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->units = number;
else
pElement->units = 0;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUnitExponentKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->unitExp = number;
else
pElement->unitExp = 0;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementNameKey));
if (refType)
if (!CFStringGetCString (refType, pElement->name, 256, CFStringGetSystemEncoding ()))
HIDReportError ("CFStringGetCString error retrieving pElement->name.");
#if 0
if (!*pElement->name)
{
// set name from vendor id, product id & usage info look up
if (!HIDGetElementNameFromVendorProductUsage (gCurrentGetDevice->vendorID, gCurrentGetDevice->productID, pElement->usagePage, pElement->usage, pElement->name))
{
// set name from vendor id/product id look up
HIDGetElementNameFromVendorProductCookie (gCurrentGetDevice->vendorID, gCurrentGetDevice->productID, (long) pElement->cookie, pElement->name);
if (!*pElement->name) { // if no name
HIDGetUsageName (pElement->usagePage, pElement->usage, pElement->name);
if (!*pElement->name) // if not usage
sprintf (pElement->name, "Element");
}
}
}
#endif
}
static void hid_AddElement (CFTypeRef refElement, pRecElement * ppElementCurrent)
{
pRecDevice pDevice = gCurrentGetDevice;
pRecElement pElement = NULL;
long elementType, usagePage, usage;
CFTypeRef refElementType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementTypeKey));
CFTypeRef refUsagePage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsagePageKey));
CFTypeRef refUsage = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementUsageKey));
if (refElementType)
CFNumberGetValue (refElementType, kCFNumberLongType, &elementType);
if (refUsagePage)
CFNumberGetValue (refUsagePage, kCFNumberLongType, &usagePage);
if (refUsage)
CFNumberGetValue (refUsage, kCFNumberLongType, &usage);
if (NULL == pDevice)
return;
if (elementType)
{
// look at types of interest
if (elementType != kIOHIDElementTypeCollection)
{
if (usagePage && usage) // if valid usage and page
{
switch (usagePage) // only interested in kHIDPage_GenericDesktop and kHIDPage_Button
{
case kHIDPage_GenericDesktop:
{
switch (usage) // look at usage to determine function
{
case kHIDUsage_GD_X:
case kHIDUsage_GD_Y:
case kHIDUsage_GD_Z:
case kHIDUsage_GD_Rx:
case kHIDUsage_GD_Ry:
case kHIDUsage_GD_Rz:
pElement = (pRecElement) malloc (sizeof (recElement));
if (pElement) pDevice->axis++;
break;
case kHIDUsage_GD_Slider:
pElement = (pRecElement) malloc (sizeof (recElement));
if (pElement) pDevice->sliders++;
break;
case kHIDUsage_GD_Dial:
pElement = (pRecElement) malloc (sizeof (recElement));
if (pElement) pDevice->dials++;
break;
case kHIDUsage_GD_Wheel:
pElement = (pRecElement) malloc (sizeof (recElement));
if (pElement) pDevice->wheels++;
break;
case kHIDUsage_GD_Hatswitch:
pElement = (pRecElement) malloc (sizeof (recElement));
if (pElement) pDevice->hats++;
break;
default:
pElement = (pRecElement) malloc (sizeof (recElement));
break;
}
}
break;
case kHIDPage_Button:
pElement = (pRecElement) malloc (sizeof (recElement));
if (pElement) pDevice->buttons++;
break;
default:
// just add a generic element
pElement = (pRecElement) malloc (sizeof (recElement));
break;
}
}
#if 0
else
HIDReportError ("CFNumberGetValue error when getting value for refUsage or refUsagePage.");
#endif // 0
}
else // collection
pElement = (pRecElement) malloc (sizeof (recElement));
}
else
HIDReportError ("CFNumberGetValue error when getting value for refElementType.");
if (pElement) // add to list
{
// this code builds a binary tree based on the collection hierarchy of inherent in the device element layout
// it preserves the structure of the lements as collections have children and elements are siblings to each other
// clear record
bzero(pElement,sizeof(recElement));
// get element info
pElement->type = elementType;
pElement->usagePage = usagePage;
pElement->usage = usage;
pElement->depth = 0; // assume root object
hid_GetElementInfo (refElement, pElement);
// count elements
pDevice->totalElements++;
switch (pElement->type)
{
case kIOHIDElementTypeInput_Misc:
case kIOHIDElementTypeInput_Button:
case kIOHIDElementTypeInput_Axis:
case kIOHIDElementTypeInput_ScanCodes:
pDevice->inputs++;
break;
case kIOHIDElementTypeOutput:
pDevice->outputs++;
break;
case kIOHIDElementTypeFeature:
pDevice->features++;
break;
case kIOHIDElementTypeCollection:
pDevice->collections++;
break;
default:
HIDReportErrorNum ("Unknown element type : ", pElement->type);
}
if (NULL == *ppElementCurrent) // if at list head
{
pDevice->pListElements = pElement; // add current element
*ppElementCurrent = pElement; // set current element to element we just added
}
else // have exsiting structure
{
if (gAddAsChild) // if the previous element was a collection, let's add this as a child of the previous
{
// this iteration should not be needed but there maybe some untested degenerate case which this code will ensure works
while ((*ppElementCurrent)->pChild) // step down tree until free child node found
*ppElementCurrent = (*ppElementCurrent)->pChild;
(*ppElementCurrent)->pChild = pElement; // insert there
pElement->depth = (*ppElementCurrent)->depth + 1;
}
else // add as sibling
{
// this iteration should not be needed but there maybe some untested degenerate case which this code will ensure works
while ((*ppElementCurrent)->pSibling) // step down tree until free sibling node found
*ppElementCurrent = (*ppElementCurrent)->pSibling;
(*ppElementCurrent)->pSibling = pElement; // insert there
pElement->depth = (*ppElementCurrent)->depth;
}
pElement->pPrevious = *ppElementCurrent; // point to previous
*ppElementCurrent = pElement; // set current to our collection
}
if (elementType == kIOHIDElementTypeCollection) // if this element is a collection of other elements
{
gAddAsChild = true; // add next set as children to this element
gDepth++;
hid_GetCollectionElements ((CFMutableDictionaryRef) refElement, &pElement); // recursively process the collection
gDepth--;
}
gAddAsChild = false; // add next as this elements sibling (when return from a collection or with non-collections)
}
#if 0
else
HIDReportError ("hid_AddElement - no element added.");
#endif
}
static void hid_GetElementsCFArrayHandler (const void * value, void * parameter)
{
if (CFGetTypeID (value) == CFDictionaryGetTypeID ())
hid_AddElement ((CFTypeRef) value, (pRecElement *) parameter);
}
// ---------------------------------
// handles retrieval of element information from arrays of elements in device IO registry information
static void hid_GetElements (CFTypeRef refElementCurrent, pRecElement *ppCurrentElement)
{
CFTypeID type = CFGetTypeID (refElementCurrent);
if (type == CFArrayGetTypeID()) // if element is an array
{
CFRange range = {0, CFArrayGetCount (refElementCurrent)};
// CountElementsCFArrayHandler called for each array member
CFArrayApplyFunction (refElementCurrent, range, hid_GetElementsCFArrayHandler, ppCurrentElement);
}
}
static void hid_TopLevelElementHandler (const void * value, void * parameter)
{
CFTypeRef refCF = 0;
if ((NULL == value) || (NULL == parameter))
return; // (kIOReturnBadArgument)
if (CFGetTypeID (value) != CFDictionaryGetTypeID ())
return; // (kIOReturnBadArgument)
refCF = CFDictionaryGetValue (value, CFSTR(kIOHIDElementUsagePageKey));
if (!CFNumberGetValue (refCF, kCFNumberLongType, &((pRecDevice) parameter)->usagePage))
HIDReportError ("CFNumberGetValue error retrieving pDevice->usagePage.");
refCF = CFDictionaryGetValue (value, CFSTR(kIOHIDElementUsageKey));
if (!CFNumberGetValue (refCF, kCFNumberLongType, &((pRecDevice) parameter)->usage))
HIDReportError ("CFNumberGetValue error retrieving pDevice->usage.");
}
static void hid_GetDeviceInfo (io_object_t hidDevice, CFMutableDictionaryRef hidProperties, pRecDevice pDevice)
{
CFMutableDictionaryRef usbProperties = 0;
io_registry_entry_t parent1, parent2;
// Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
// get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
if ((KERN_SUCCESS == IORegistryEntryGetParentEntry (hidDevice, kIOServicePlane, &parent1)) &&
(KERN_SUCCESS == IORegistryEntryGetParentEntry (parent1, kIOServicePlane, &parent2)) &&
(KERN_SUCCESS == IORegistryEntryCreateCFProperties (parent2, &usbProperties, kCFAllocatorDefault, kNilOptions)))
{
if (usbProperties)
{
CFTypeRef refCF = 0;
// get device info
// try hid dictionary first, if fail then go to usb dictionary
// get transport
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDTransportKey));
if (refCF)
{
if (!CFStringGetCString (refCF, pDevice->transport, 256, CFStringGetSystemEncoding ()))
HIDReportError ("CFStringGetCString error retrieving pDevice->transport.");
}
// get vendorID
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDVendorIDKey));
if (!refCF)
refCF = CFDictionaryGetValue (usbProperties, CFSTR("idVendor"));
if (refCF)
{
if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->vendorID))
HIDReportError ("CFNumberGetValue error retrieving pDevice->vendorID.");
}
// get product ID
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDProductIDKey));
if (!refCF)
refCF = CFDictionaryGetValue (usbProperties, CFSTR("idProduct"));
if (refCF)
{
if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->productID))
HIDReportError ("CFNumberGetValue error retrieving pDevice->productID.");
}
// get product version
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDVersionNumberKey));
if (refCF)
{
if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->version))
HIDReportError ("CFNumberGetValue error retrieving pDevice->version.");
}
// get manufacturer name
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDManufacturerKey));
if (!refCF)
refCF = CFDictionaryGetValue (usbProperties, CFSTR("USB Vendor Name"));
if (refCF)
{
if (!CFStringGetCString (refCF, pDevice->manufacturer, 256, CFStringGetSystemEncoding ()))
HIDReportError ("CFStringGetCString error retrieving pDevice->manufacturer.");
}
// get product name
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDProductKey));
if (!refCF)
refCF = CFDictionaryGetValue (usbProperties, CFSTR("USB Product Name"));
if (refCF)
{
// ryan forced this to UTF-8.
//if (!CFStringGetCString (refCF, pDevice->product, 256, CFStringGetSystemEncoding ()))
if (!CFStringGetCString (refCF, pDevice->product, 256, kCFStringEncodingUTF8))
HIDReportError ("CFStringGetCString error retrieving pDevice->product.");
}
// get serial
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDSerialNumberKey));
if (refCF)
{
if (!CFStringGetCString (refCF, pDevice->serial, 256, CFStringGetSystemEncoding ()))
HIDReportError ("CFStringGetCString error retrieving pDevice->serial.");
}
// get location ID
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDLocationIDKey));
if (!refCF)
refCF = CFDictionaryGetValue (usbProperties, CFSTR("locationID"));
if (refCF)
{
if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->locID))
HIDReportError ("CFNumberGetValue error retrieving pDevice->locID.");
}
// get usage page and usage
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey));
if (refCF)
{
if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usagePage))
HIDReportError ("CFNumberGetValue error retrieving pDevice->usagePage.");
refCF = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDPrimaryUsageKey));
if (refCF)
if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usage))
HIDReportError ("CFNumberGetValue error retrieving pDevice->usage.");
}
if (NULL == refCF) // get top level element HID usage page or usage
{
// use top level element instead
CFTypeRef refCFTopElement = 0;
refCFTopElement = CFDictionaryGetValue (hidProperties, CFSTR(kIOHIDElementKey));
{
// refCFTopElement points to an array of element dictionaries
CFRange range = {0, CFArrayGetCount (refCFTopElement)};
CFArrayApplyFunction (refCFTopElement, range, hid_TopLevelElementHandler, NULL);
}
}
}
else
HIDReportError ("IORegistryEntryCreateCFProperties failed to create usbProperties.");
CFRelease (usbProperties);
if (kIOReturnSuccess != IOObjectRelease (parent2))
HIDReportError ("IOObjectRelease error with parent2.");
if (kIOReturnSuccess != IOObjectRelease (parent1))
HIDReportError ("IOObjectRelease error with parent1.");
}
}
static Boolean hid_MatchElementTypeMask (IOHIDElementType type, HIDElementTypeMask typeMask)
{
if (typeMask & kHIDElementTypeInput)
if ((type == kIOHIDElementTypeInput_Misc) || (type == kIOHIDElementTypeInput_Button) || (type == kIOHIDElementTypeInput_Axis) || (type == kIOHIDElementTypeInput_ScanCodes))
return true;
if (typeMask & kHIDElementTypeOutput)
if (type == kIOHIDElementTypeOutput)
return true;
if (typeMask & kHIDElementTypeFeature)
if (type == kIOHIDElementTypeFeature)
return true;
if (typeMask & kHIDElementTypeCollection)
if (type == kIOHIDElementTypeCollection)
return true;
return false;
}
static pRecElement hid_GetDeviceElement (pRecElement pElement, HIDElementTypeMask typeMask)
{
// we are asking for this element
if (NULL != pElement)
{
if (hid_MatchElementTypeMask (pElement->type, typeMask)) // if the type match what we are looking for
return pElement; // return the element
else
return HIDGetNextDeviceElement (pElement, typeMask); // else get the next one
}
return NULL;
}
static unsigned long HIDCloseReleaseInterface (pRecDevice pDevice)
{
IOReturn result = kIOReturnSuccess;
if (HIDIsValidDevice(pDevice) && (NULL != pDevice->interface))
{
// close the interface
result = (*(IOHIDDeviceInterface**) pDevice->interface)->close (pDevice->interface);
if (kIOReturnNotOpen == result)
{
// do nothing as device was not opened, thus can't be closed
}
else if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("HIDCloseReleaseInterface - Failed to close IOHIDDeviceInterface.", result);
//release the interface
result = (*(IOHIDDeviceInterface**) pDevice->interface)->Release (pDevice->interface);
if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("HIDCloseReleaseInterface - Failed to release interface.", result);
pDevice->interface = NULL;
}
return result;
}
// ---------------------------------
// count number of devices in global device list (gpDeviceList)
static UInt32 hid_CountCurrentDevices (void)
{
pRecDevice pDevice = gpDeviceList;
UInt32 devices = 0;
while (pDevice)
{
devices++;
pDevice = pDevice->pNext;
}
return devices;
}
static UInt32 HIDCountDevices (void)
{
gNumDevices = hid_CountCurrentDevices ();
return gNumDevices;
}
static void hid_DisposeDeviceElements (pRecElement pElement)
{
if (pElement)
{
if (pElement->pChild)
hid_DisposeDeviceElements (pElement->pChild);
if (pElement->pSibling)
hid_DisposeDeviceElements (pElement->pSibling);
free (pElement);
}
}
static pRecDevice hid_DisposeDevice (pRecDevice pDevice)
{
kern_return_t result = KERN_SUCCESS;
pRecDevice pDeviceNext = NULL;
if (HIDIsValidDevice(pDevice))
{
// save next device prior to disposing of this device
pDeviceNext = pDevice->pNext;
result = HIDDequeueDevice (pDevice);
#if 0
if (kIOReturnSuccess != result)
HIDReportErrorNum ("hid_DisposeDevice: HIDDequeueDevice error: 0x%8.8X.", result);
#endif // 1
hid_DisposeDeviceElements (pDevice->pListElements);
pDevice->pListElements = NULL;
result = HIDCloseReleaseInterface (pDevice); // function sanity checks interface value (now application does not own device)
if (kIOReturnSuccess != result)
HIDReportErrorNum ("hid_DisposeDevice: HIDCloseReleaseInterface error: 0x%8.8X.", result);
#if USE_NOTIFICATIONS
if (pDevice->interface)
{
// replace (*pDevice->interface)->Release(pDevice->interface);
result = IODestroyPlugInInterface (pDevice->interface);
if (kIOReturnSuccess != result)
HIDReportErrorNum ("hid_DisposeDevice: IODestroyPlugInInterface error: 0x%8.8X.", result);
}
if (pDevice->notification)
{
result = IOObjectRelease((io_object_t) pDevice->notification);
if (kIOReturnSuccess != result)
HIDReportErrorNum ("hid_DisposeDevice: IOObjectRelease error: 0x%8.8X.", result);
}
#endif // USE_NOTIFICATIONS
// remove this device from the device list
if (gpDeviceList == pDevice) // head of list?
gpDeviceList = pDeviceNext;
else
{
pRecDevice pDeviceTemp = pDeviceNext = gpDeviceList; // we're going to return this if we don't find ourselfs in the list
while (pDeviceTemp)
{
if (pDeviceTemp->pNext == pDevice) // found us!
{
// take us out of linked list
pDeviceTemp->pNext = pDeviceNext = pDevice->pNext;
break;
}
pDeviceTemp = pDeviceTemp->pNext;
}
}
free (pDevice);
}
// update device count
gNumDevices = hid_CountCurrentDevices ();
return pDeviceNext;
}
// ---------------------------------
// disposes and releases queue, sets queue to NULL,.
// Note: will have no effect if device or queue do not exist
static IOReturn hid_DisposeReleaseQueue (pRecDevice pDevice)
{
IOReturn result = kIOReturnError; // assume failure (pessimist!)
if (HIDIsValidDevice(pDevice)) // need valid device
{
if (pDevice->queue) // and queue
{
// stop queue
result = (*(IOHIDQueueInterface**) pDevice->queue)->stop (pDevice->queue);
if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("hid_DisposeReleaseQueue - Failed to stop queue.", result);
// dispose of queue
result = (*(IOHIDQueueInterface**) pDevice->queue)->dispose (pDevice->queue);
if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("hid_DisposeReleaseQueue - Failed to dipose queue.", result);
// release the queue
result = (*(IOHIDQueueInterface**) pDevice->queue)->Release (pDevice->queue);
if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("hid_DisposeReleaseQueue - Failed to release queue.", result);
pDevice->queue = NULL;
}
else
HIDREPORTERROR ("hid_DisposeReleaseQueue - no queue.");
}
else
HIDREPORTERROR ("hid_DisposeReleaseQueue - Invalid device.");
return result;
}
// ---------------------------------
// completely removes all elements from queue and releases queue and closes device interface
// does not release device interfaces, application must call HIDReleaseDeviceList on exit
static unsigned long HIDDequeueDevice (pRecDevice pDevice)
{
IOReturn result = kIOReturnSuccess;
if (HIDIsValidDevice(pDevice))
{
if ((pDevice->interface) && (pDevice->queue))
{
// iterate through elements and if queued, remove
pRecElement pElement = HIDGetFirstDeviceElement (pDevice, kHIDElementTypeIO);
while (pElement)
{
if ((*(IOHIDQueueInterface**) pDevice->queue)->hasElement (pDevice->queue, pElement->cookie))
{
result = (*(IOHIDQueueInterface**) pDevice->queue)->removeElement (pDevice->queue, pElement->cookie);
if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("HIDDequeueDevice - Failed to remove element from queue.", result);
}
pElement = HIDGetNextDeviceElement (pElement, kHIDElementTypeIO);
}
}
// ensure queue is disposed and released
// interface will be closed and released on call to HIDReleaseDeviceList
result = hid_DisposeReleaseQueue (pDevice);
if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("removeElement - Failed to dispose and release queue.", result);
#if USE_ASYNC_EVENTS
else if (NULL != pDevice->queueRunLoopSource)
{
if (CFRunLoopContainsSource(CFRunLoopGetCurrent(), pDevice->queueRunLoopSource, kCFRunLoopDefaultMode))
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), pDevice->queueRunLoopSource, kCFRunLoopDefaultMode);
CFRelease(pDevice->queueRunLoopSource);
pDevice->queueRunLoopSource = NULL;
}
#endif // USE_ASYNC_EVENTS
}
else
{
HIDREPORTERROR ("HIDDequeueDevice - Invalid device.");
result = kIOReturnBadArgument;
}
return result;
}
// ---------------------------------
// releases all device queues for quit or rebuild (must be called)
// does not release device interfaces, application must call HIDReleaseDeviceList on exit
static unsigned long HIDReleaseAllDeviceQueues (void)
{
IOReturn result = kIOReturnBadArgument;
pRecDevice pDevice = HIDGetFirstDevice ();
while (pDevice)
{
result = HIDDequeueDevice (pDevice);
if (kIOReturnSuccess != result)
HIDREPORTERRORNUM ("HIDReleaseAllDeviceQueues - Could not dequeue device.", result);
pDevice = HIDGetNextDevice (pDevice);
}
return result;
}
// ---------------------------------
// Get the next event in the queue for a device
// elements or entire device should be queued prior to calling this with HIDQueueElement or HIDQueueDevice
// returns true if an event is avialable for the element and fills out *pHIDEvent structure, returns false otherwise
// Note: kIOReturnUnderrun returned from getNextEvent indicates an empty queue not an error condition
// Note: application should pass in a pointer to a IOHIDEventStruct cast to a void (for CFM compatibility)
static unsigned char HIDGetEvent (pRecDevice pDevice, void * pHIDEvent)
{
IOReturn result = kIOReturnBadArgument;
AbsoluteTime zeroTime = {0,0};
if (HIDIsValidDevice(pDevice))
{
if (pDevice->queue)
{
result = (*(IOHIDQueueInterface**) pDevice->queue)->getNextEvent (pDevice->queue, (IOHIDEventStruct *)pHIDEvent, zeroTime, 0);
if (kIOReturnUnderrun == result)
return false; // no events in queue not an error per say
else if (kIOReturnSuccess != result) // actual error versus just an empty queue
HIDREPORTERRORNUM ("HIDGetEvent - Could not get HID event via getNextEvent.", result);
else
return true;
}
else
HIDREPORTERROR ("HIDGetEvent - queue does not exist.");
}
else
HIDREPORTERROR ("HIDGetEvent - invalid device.");
return false; // did not get event
}
static unsigned long HIDCreateOpenDeviceInterface (UInt32 hidDevice, pRecDevice pDevice)
{
IOReturn result = kIOReturnSuccess;
HRESULT plugInResult = S_OK;
SInt32 score = 0;
IOCFPlugInInterface ** ppPlugInInterface = NULL;
if (NULL == pDevice->interface)
{
result = IOCreatePlugInInterfaceForService (hidDevice, kIOHIDDeviceUserClientTypeID,
kIOCFPlugInInterfaceID, &ppPlugInInterface, &score);
if (kIOReturnSuccess == result)
{
// Call a method of the intermediate plug-in to create the device interface
plugInResult = (*ppPlugInInterface)->QueryInterface (ppPlugInInterface,
CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID), (void *) &(pDevice->interface));
if (S_OK != plugInResult)
HIDReportErrorNum ("Couldn't query HID class device interface from plugInInterface", plugInResult);
IODestroyPlugInInterface (ppPlugInInterface); // replace (*ppPlugInInterface)->Release (ppPlugInInterface)
}
else
HIDReportErrorNum ("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.", result);
}
if (NULL != pDevice->interface)
{
result = (*(IOHIDDeviceInterface**)pDevice->interface)->open (pDevice->interface, 0);
if (kIOReturnSuccess != result)
HIDReportErrorNum ("Failed to open pDevice->interface via open.", result);
}
return result;
}
// ---------------------------------
// adds device to linked list of devices passed in (handles NULL lists properly)
// (returns where you just stored it)
static pRecDevice* hid_AddDevice (pRecDevice *ppListDeviceHead, pRecDevice pNewDevice)
{
pRecDevice* result = NULL;
if (NULL == *ppListDeviceHead)
result = ppListDeviceHead;
else
{
pRecDevice pDevicePrevious = NULL, pDevice = *ppListDeviceHead;
while (pDevice)
{
pDevicePrevious = pDevice;
pDevice = pDevicePrevious->pNext;
}
result = &pDevicePrevious->pNext;
}
pNewDevice->pNext = NULL;
*result = pNewDevice;
return result;
}
static pRecDevice hid_BuildDevice (io_object_t hidDevice)
{
pRecDevice pDevice = (pRecDevice) malloc (sizeof (recDevice));
if (NULL != pDevice)
{
// get dictionary for HID properties