public
Created

HID Device to UDP

  • Download Gist
gistfile1.m
Objective-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
#import <Foundation/Foundation.h>
#import <IOKit/hid/IOHIDManager.h>
#import <IOKit/hid/IOHIDUsageTables.h>
 
#define KEYS 4
 
 
static void Handle_InputCallback(void *inContext, IOReturn inResult, void *inSender, IOHIDValueRef value)
{
IOHIDElementRef elem = IOHIDValueGetElement(value);
 
uint16_t scancode = IOHIDElementGetUsage(elem);
if (scancode < 4 || scancode > 231) {
return;
}
NSLog(@"Key event received");
}
 
 
static void Handle_DeviceMatchingCallback(void * inContext, IOReturn inResult, void * inSender, IOHIDDeviceRef inIOHIDDeviceRef)
{
NSLog(@"Connected");
}
 
static void Handle_RemovalCallback(void * inContext, IOReturn inResult, void * inSender, IOHIDDeviceRef inIOHIDDeviceRef)
{
NSLog(@"Removed");
}
 
 
int main(int argc, const char * argv[])
{
@autoreleasepool {
IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDManagerOptionNone);
if (CFGetTypeID(manager) != IOHIDManagerGetTypeID()) {
exit(1);
}
int vendorId = 0x05ac;
//vendorId = 0x1234;
int productId = 0x0237;
//productId = 0x5678;
int usagePage = kHIDPage_GenericDesktop;
int usage = kHIDUsage_GD_Keyboard;
CFStringRef keys[KEYS] = {
CFSTR(kIOHIDVendorIDKey),
CFSTR(kIOHIDProductIDKey),
CFSTR(kIOHIDDeviceUsagePageKey),
CFSTR(kIOHIDDeviceUsageKey),
};
CFNumberRef values[KEYS] = {
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vendorId),
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &productId),
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usagePage),
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usage),
};
CFDictionaryRef matchingDict = CFDictionaryCreate(kCFAllocatorDefault,
(const void **) keys, (const void **) values, KEYS,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
 
for (int i=0; i<KEYS; i++) {
CFRelease(keys[i]);
CFRelease(values[i]);
}
IOHIDManagerSetDeviceMatching(manager, matchingDict);
CFRelease(matchingDict);
IOHIDManagerRegisterDeviceMatchingCallback(manager, Handle_DeviceMatchingCallback, null);
IOHIDManagerRegisterDeviceRemovalCallback(manager, Handle_RemovalCallback, null);
IOHIDManagerRegisterInputValueCallback(manager, Handle_InputCallback, null);
IOHIDManagerOpen(manager, kIOHIDOptionsTypeSeizeDevice);
 
IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
[[NSRunLoop mainRunLoop] run];
}
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.