/
HID_Utilities.c
executable file
·2199 lines (1970 loc) · 97.4 KB
/
HID_Utilities.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
/*
File: HID_Utilities.c
Contains: Implementation of HID Utilities
DRI: George Warner
Copyright: Copyright © 2002 Apple Computer, Inc., All Rights Reserved
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HID_Utilities_Internal.h"
#include "HID_Utilities_External.h"
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOMessage.h>
#include <IOKit/hid/IOHIDUsageTables.h>
//================================================================================================
#define USE_NOTIFICATIONS 1
//================================================================================================
// local (static) functions
//================================================================================================
static void hid_GetCollectionElements (CFMutableDictionaryRef deviceProperties, pRecElement *ppCurrentCollection);
static pRecDevice hid_DisposeDevice (pRecDevice ppDevice);
//================================================================================================
// globals
//================================================================================================
#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;
#pragma mark private functions
// ==================================
// private functions
static UInt32 hid_CountCurrentDevices (void);
// 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 (!*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");
}
}
}
}
// ---------------------------------
// examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements
// if element of interest allocate storage, add to list and retrieve element specific info
// if collection then pass on to deconstruction collection into additional individual elements
static void hid_AddElement (CFTypeRef refElement, pRecElement * ppElementCurrent)
{
pRecDevice pDevice = gCurrentGetDevice;
pRecElement pElement = NULL;
long elementType=0, usagePage=0, usage=0;
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
}
// ---------------------------------
// collects information from each array member in device element list (each array memeber = element)
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);
}
}
// ---------------------------------
// handles extracting element information from element collection CF types
// used from top level element decoding and hierarchy deconstruction to flatten device element list
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.");
}
// ---------------------------------
// use top level element usage page and usage to discern device usage page and usage setting appropriate values in device record
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.");
}
// ---------------------------------
// extracts device info from CF dictionary records in IO registry
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)
{
if (!CFStringGetCString (refCF, pDevice->product, 256, CFStringGetSystemEncoding ()))
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);
}
}
CFRelease (usbProperties);
}
else
HIDReportError ("IORegistryEntryCreateCFProperties failed to create usbProperties.");
if (kIOReturnSuccess != IOObjectRelease (parent2))
HIDReportError ("IOObjectRelease error with parent2.");
if (kIOReturnSuccess != IOObjectRelease (parent1))
HIDReportError ("IOObjectRelease error with parent1.");
}
}
// ---------------------------------
// 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;
}
// ---------------------------------
// given a IO device object build a flat device record including device info and elements
static pRecDevice hid_BuildDevice (io_object_t hidDevice)
{
pRecDevice pDevice = (pRecDevice) malloc (sizeof (recDevice));
if (NULL != pDevice)
{
// get dictionary for HID properties
CFMutableDictionaryRef hidProperties = 0;
kern_return_t result = IORegistryEntryCreateCFProperties (hidDevice, &hidProperties, kCFAllocatorDefault, kNilOptions);
// clear record
bzero(pDevice, sizeof(recDevice));
if ((result == KERN_SUCCESS) && (NULL != hidProperties))
{
pRecElement pCurrentElement = NULL;
// create device interface
result = HIDCreateOpenDeviceInterface (hidDevice, pDevice);
if (kIOReturnSuccess != result)
HIDReportErrorNum ("HIDCreateOpenDeviceInterface failed.", result);
hid_GetDeviceInfo (hidDevice, hidProperties, pDevice); // hidDevice used to find parents in registry tree
// set current device for use in getting elements
gCurrentGetDevice = pDevice;
// Add all elements
hid_GetCollectionElements (hidProperties, &pCurrentElement);
gCurrentGetDevice = NULL;
CFRelease (hidProperties);
}
else
HIDReportErrorNum ("IORegistryEntryCreateCFProperties error when creating deviceProperties.", result);
}
else
HIDReportError ("malloc error when allocating pRecDevice.");
return pDevice;
}
#if USE_NOTIFICATIONS
//================================================================================================
//
// hid_DeviceNotification
//
// This routine will get called whenever any kIOGeneralInterest notification happens. We are
// interested in the kIOMessageServiceIsTerminated message so that's what we look for. Other
// messages are defined in IOMessage.h.
//
//================================================================================================
//
static void hid_DeviceNotification( void *refCon,
io_service_t service,
natural_t messageType,
void *messageArgument )
{
#pragma unused(messageArgument)
pRecDevice pDevice = (pRecDevice) refCon;
if (messageType == kIOMessageServiceIsTerminated)
{
printf("Device 0x%08x \"%s\"removed.\n", service, pDevice->product);
// Free the data we're no longer using now that the device is going away
hid_DisposeDevice (pDevice);
}
}
#else
static void hid_RemovalCallbackFunction(void * target, IOReturn result, void * refcon, void * sender)
{
hid_DisposeDevice ((pRecDevice) target);
}
#endif //USE_NOTIFICATIONS
//================================================================================================
//
// hid_AddDevices
//
// This routine is the callback for our IOServiceAddMatchingNotification. When we get called
// we will look at all the devices that were added and we will:
//
// 1. Create some private data to relate to each device.
// 2. Submit an IOServiceAddInterestNotification of type kIOGeneralInterest for this device,
// using the refCon field to store a pointer to our data. When we get called with
// this interest notification, we can grab the refCon and access our private data.
//
//================================================================================================
//
// ---------------------------------
// given a IO device iterator, iterate it and add all its devices
static void hid_AddDevices (void *refCon, io_iterator_t iterator)
{
// NOTE: refcon passed in is used to point to the device list head
pRecDevice* pListDeviceHead = (pRecDevice*) refCon;
IOReturn result = kIOReturnSuccess;
io_object_t ioHIDDeviceObject = 0;
while ((ioHIDDeviceObject = IOIteratorNext (iterator)))
{
pRecDevice* pNewDeviceAt = NULL;
pRecDevice pNewDevice = hid_BuildDevice (ioHIDDeviceObject);
if (pNewDevice)
{
#if 0 // set true for verbose output
printf("\nhid_AddDevices: pNewDevice = {t: \"%s\", v: %ld, p: %ld, v: %ld, m: \"%s\", " \
"p: \"%s\", l: %ld, u: %4.4lX:%4.4lX, #e: %ld, #f: %ld, #i: %ld, #o: %ld, " \
"#c: %ld, #a: %ld, #b: %ld, #h: %ld, #s: %ld, #d: %ld, #w: %ld}.",
pNewDevice->transport,
pNewDevice->vendorID,
pNewDevice->productID,
pNewDevice->version,
pNewDevice->manufacturer,
pNewDevice->product,
pNewDevice->locID,
pNewDevice->usagePage,
pNewDevice->usage,
pNewDevice->totalElements,
pNewDevice->features,
pNewDevice->inputs,
pNewDevice->outputs,
pNewDevice->collections,
pNewDevice->axis,
pNewDevice->buttons,
pNewDevice->hats,
pNewDevice->sliders,
pNewDevice->dials,
pNewDevice->wheels
);
fflush(stdout);
#elif 0 // otherwise output brief description
printf("\nhid_AddDevices: pNewDevice = {m: \"%s\" p: \"%s\", vid: %ld, pid: %ld, loc: %8.8lX, usage: %4.4lX:%4.4lX}.",
pNewDevice->manufacturer,
pNewDevice->product,
pNewDevice->vendorID,
pNewDevice->productID,
pNewDevice->locID,
pNewDevice->usagePage,
pNewDevice->usage
);
fflush(stdout);
#endif
pNewDeviceAt = hid_AddDevice (pListDeviceHead, pNewDevice);
}
#if USE_NOTIFICATIONS
// Register for an interest notification of this device being removed. Use a reference to our
// private data as the refCon which will be passed to the notification callback.
result = IOServiceAddInterestNotification( gNotifyPort, // notifyPort
ioHIDDeviceObject, // service
kIOGeneralInterest, // interestType
hid_DeviceNotification, // callback
pNewDevice, // refCon
(io_object_t*) &pNewDevice->notification); // notification
if (KERN_SUCCESS != result)
HIDReportErrorNum ("hid_AddDevices: IOServiceAddInterestNotification error: x0%8.8lX.", result);
#else
result = (*(IOHIDDeviceInterface**)pNewDevice->interface)->setRemovalCallback (pNewDevice->interface, hid_RemovalCallbackFunction,pNewDeviceAt,0);
#endif //USE_NOTIFICATIONS
// release the device object, it is no longer needed
result = IOObjectRelease (ioHIDDeviceObject);
if (KERN_SUCCESS != result)
HIDReportErrorNum ("hid_AddDevices: IOObjectRelease error with ioHIDDeviceObject.", result);
}
}
// ---------------------------------
// disposes of the element list associated with a device and the memory associated with the list
// uses depthwise recursion to dispose both collections and elements.
static void hid_DisposeDeviceElements (pRecElement pElement)
{
if (pElement)
{
if (pElement->pChild)
hid_DisposeDeviceElements (pElement->pChild);
if (pElement->pSibling)
hid_DisposeDeviceElements (pElement->pSibling);
free (pElement);
}
}
// ---------------------------------
// disposes of a single device, closing and releaseing interface, freeing memory fro device and elements, setting device pointer to NULL
// all your device no longer belong to us... (i.e., you do not 'own' the device anymore)
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;
}
// ---------------------------------
// 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;
}
// ---------------------------------
// matches type masks passed in to actual element types (which are not set up to be used as a mask
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;
}
#define FAKE_IT 0 // set true for debugging; returns the usage & usage page as numbers
// ---------------------------------
// Load the usage strings from the <HID_usage_strings.plist> resource (XML) file into a CFPropertyListRef
static CFPropertyListRef xml_load_usage_strings(void)
{
CFPropertyListRef tCFPropertyListRef = NULL;
CFURLRef resFileCFURLRef = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("HID_usage_strings"), CFSTR("plist"), NULL);
if (NULL != resFileCFURLRef)
{
CFDataRef resCFDataRef;
if (CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, resFileCFURLRef, &resCFDataRef, nil, nil, nil))
{
if (NULL != resCFDataRef)
{
CFStringRef errorString;
tCFPropertyListRef = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, resCFDataRef, kCFPropertyListImmutable, &errorString);
if (NULL == tCFPropertyListRef)
CFShow(errorString);
CFRelease(resCFDataRef);
}
}
CFRelease(resFileCFURLRef);
}
return tCFPropertyListRef;
}
// ---------------------------------
// Find a usage string in the <HID_usage_strings.plist> resource (XML) file
static Boolean xml_GetUsageName(const long valueUsagePage, const long valueUsage, char* pCstr)
{
static CFPropertyListRef tCFPropertyListRef = NULL;
Boolean results = false;
if (NULL == tCFPropertyListRef)
tCFPropertyListRef = xml_load_usage_strings();
if (NULL != tCFPropertyListRef)
{
if (CFDictionaryGetTypeID() == CFGetTypeID(tCFPropertyListRef))
{
CFDictionaryRef pageCFDictionaryRef;
CFStringRef pageKeyCFStringRef;
pageKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("0x%4.4lX"), valueUsagePage);
if (CFDictionaryGetValueIfPresent(tCFPropertyListRef, pageKeyCFStringRef, (const void**) &pageCFDictionaryRef))
{
CFStringRef pageCFStringRef;
if (CFDictionaryGetValueIfPresent(pageCFDictionaryRef, CFSTR("Name"), (const void**) &pageCFStringRef))
{
//CFShow(pageCFStringRef);
}
{
CFStringRef fullCFStringRef = NULL;
CFStringRef usageKeyCFStringRef;
CFStringRef usageCFStringRef;
usageKeyCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("0x%4.4lX"), valueUsage);
if (CFDictionaryGetValueIfPresent(pageCFDictionaryRef, usageKeyCFStringRef, (const void**) &usageCFStringRef))
{
fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ %@"),
pageCFStringRef, usageCFStringRef);
// CFShow(usageCFStringRef);
}
#if FAKE_IT
else
{
fullCFStringRef = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ #%@"),
pageCFStringRef, usageKeyCFStringRef);
}
#endif
if (fullCFStringRef)
{
// CFShow(fullCFStringRef);
results = CFStringGetCString(
fullCFStringRef, pCstr, CFStringGetLength(fullCFStringRef) * sizeof(UniChar) + 1, kCFStringEncodingMacRoman);
CFRelease(fullCFStringRef);
}
CFRelease(usageKeyCFStringRef);
}
}
CFRelease(pageKeyCFStringRef);
}
//++CFRelease(tCFPropertyListRef); // Leak this!
}
return results;
}
#pragma mark public functions
// =================================
// public functions
// ---------------------------------
// Create and open an interface to device, required prior to extracting values or building queues
// Note: appliction now owns the device and must close and release it prior to exiting
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