1 #import "NJHIDManager.h"
3 @implementation NJHIDManager {
5 IOHIDManagerRef _manager;
8 - (id)initWithCriteria:(NSArray *)criteria
9 delegate:(id <NJHIDManagerDelegate>)delegate
11 if ((self = [super init])) {
12 self.criteria = criteria;
13 self.delegate = delegate;
22 static void _input(void *ctx, IOReturn inResult, void *inSender, IOHIDValueRef value) {
23 NJHIDManager *self = (__bridge NJHIDManager *)ctx;
24 IOHIDDeviceRef device = IOHIDQueueGetDevice(inSender);
25 [self.delegate HIDManager:self valueChanged:value fromDevice:device];
28 static void _add(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
29 NJHIDManager *self = (__bridge NJHIDManager *)ctx;
30 [self.delegate HIDManager:self deviceAdded:device];
31 IOHIDDeviceRegisterInputValueCallback(device, _input, ctx);
34 static void _remove(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
35 NJHIDManager *self = (__bridge NJHIDManager *)ctx;
36 [self.delegate HIDManager:self deviceRemoved:device];
42 IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
43 IOHIDManagerSetDeviceMatchingMultiple(manager, (__bridge CFArrayRef)self.criteria);
44 IOReturn ret = IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone);
45 if (ret != kIOReturnSuccess) {
46 NSError *error = [NSError errorWithDomain:NSMachErrorDomain code:ret userInfo:nil];
47 IOHIDManagerClose(manager, kIOHIDOptionsTypeNone);
49 [self.delegate HIDManager:self didError:error];
50 NSLog(@"Error starting HID manager: %@.", error);
53 IOHIDManagerScheduleWithRunLoop(_manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
54 IOHIDManagerRegisterDeviceMatchingCallback(_manager, _add, (__bridge void *)self);
55 IOHIDManagerRegisterDeviceRemovalCallback(_manager, _remove, (__bridge void *)self);
56 [self.delegate HIDManagerDidStart:self];
57 NSLog(@"Started HID manager.");
64 IOHIDManagerUnscheduleFromRunLoop(_manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
65 IOHIDManagerClose(_manager, kIOHIDOptionsTypeNone);
68 [self.delegate HIDManagerDidStop:self];
69 NSLog(@"Stopped HID manager.");
76 - (void)setRunning:(BOOL)running {
83 - (NSArray *)criteria {
87 - (void)setCriteria:(NSArray *)criteria {
90 if (![criteria isEqualToArray:_criteria]) {
91 BOOL running = !!_manager;
93 _criteria = [criteria copy];