5 // Created by Sam McCall on 4/05/09.
11 #import "NJInputAnalog.h"
12 #import "NJInputHat.h"
13 #import "NJInputButton.h"
15 static NSArray *InputsForElement(IOHIDDeviceRef device, id base) {
16 CFArrayRef elements = IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone);
17 NSMutableArray *children = [NSMutableArray arrayWithCapacity:CFArrayGetCount(elements)];
23 for (int i = 0; i < CFArrayGetCount(elements); i++) {
24 IOHIDElementRef element = (IOHIDElementRef)CFArrayGetValueAtIndex(elements, i);
25 int type = IOHIDElementGetType(element);
26 unsigned usage = IOHIDElementGetUsage(element);
27 unsigned usagePage = IOHIDElementGetUsagePage(element);
28 long max = IOHIDElementGetPhysicalMax(element);
29 long min = IOHIDElementGetPhysicalMin(element);
30 CFStringRef elName = IOHIDElementGetName(element);
34 if (!(type == kIOHIDElementTypeInput_Misc
35 || type == kIOHIDElementTypeInput_Axis
36 || type == kIOHIDElementTypeInput_Button))
39 if (max - min == 1 || usagePage == kHIDPage_Button || type == kIOHIDElementTypeInput_Button) {
40 input = [[NJInputButton alloc] initWithName:(__bridge NSString *)elName
43 } else if (usage == kHIDUsage_GD_Hatswitch) {
44 input = [[NJInputHat alloc] initWithIndex:++hats];
45 } else if (usage >= kHIDUsage_GD_X && usage <= kHIDUsage_GD_Rz) {
46 input = [[NJInputAnalog alloc] initWithIndex:++axes
53 // TODO(jfw): Should be moved into better constructors.
55 input.cookie = IOHIDElementGetCookie(element);
56 [children addObject:input];
63 @implementation NJDevice {
68 - (id)initWithDevice:(IOHIDDeviceRef)dev {
69 if ((self = [super initWithName:nil did:nil base:nil])) {
71 self.productName = (__bridge NSString *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDProductKey));
72 _vendorId = [(__bridge NSNumber *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDVendorIDKey)) intValue];
73 _productId = [(__bridge NSNumber *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDProductIDKey)) intValue];
74 self.children = InputsForElement(dev, self);
80 return [NSString stringWithFormat:@"%@ #%d", _productName, _index];
84 return [NSString stringWithFormat: @"%d:%d:%d", _vendorId, _productId, _index];
87 - (NJInput *)findInputByCookie:(IOHIDElementCookie)cookie {
88 for (NJInput *child in self.children)
89 if (child.cookie == cookie)
94 - (NJInput *)handlerForEvent:(IOHIDValueRef)value {
95 NJInput *mainInput = [self inputForEvent:value];
96 return [mainInput findSubInputForValue:value];
99 - (NJInput *)inputForEvent:(IOHIDValueRef)value {
100 IOHIDElementRef elt = IOHIDValueGetElement(value);
101 IOHIDElementCookie cookie = IOHIDElementGetCookie(elt);
102 return [self findInputByCookie:cookie];