框架:IOKit.framework
簡介:用于Mac OS 上位機(jī)軟件根據(jù)USB線連接下位機(jī)硬件喧半,與之進(jìn)行數(shù)據(jù)交互秧骑,通訊霎奢。
開發(fā)步驟:
1、導(dǎo)入依賴頭文件
#include <IOKit/hid/IOHIDLib.h>
2份乒、初始化IOHIDManager
IOHIDManagerRef managerRef = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
3恕汇、進(jìn)行配對(duì)設(shè)置,可以過濾其他USB設(shè)備或辖。
1).無配對(duì)設(shè)備
IOHIDManagerSetDeviceMatching(HIDManager, NULL);
2).單類設(shè)備配對(duì)
NSMutableDictionary* dict= [NSMutableDictionary dictionary];
[dict setValue:pid forKey:[NSString stringWithCString:kIOHIDProductIDKey encoding:NSUTF8StringEncoding]];
[dict setValue:vid forKey:[NSString stringWithCString:kIOHIDVendorIDKey encoding:NSUTF8StringEncoding]];
IOHIDManagerSetDeviceMatching(managerRef, (__bridge CFMutableDictionaryRef)dict);
3).多種設(shè)備配對(duì)設(shè)置
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:dict];
IOHIDManagerSetDeviceMatchingMultiple(managerRef, (__bridge CFMutableArrayRef)arr);
4瘾英、注冊插拔設(shè)備的callback
//注冊插入callback
IOHIDManagerRegisterDeviceMatchingCallback(managerRef, &Handle_DeviceMatchingCallback, NULL);
//注冊拔出callback
IOHIDManagerRegisterDeviceRemovalCallback(managerRef, &Handle_DeviceRemovalCallback, NULL);
5、加入RunLoop
IOHIDManagerScheduleWithRunLoop(managerRef, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
6颂暇、打開IOHIDManager
IOReturn ret = IOHIDManagerOpen(managerRef, kIOHIDOptionsTypeNone);
if (ret == kIOReturnSuccess) {
NSLog(@"IOHIDManager打開成功");
}
7缺谴、實(shí)現(xiàn)插拔callback
static void Handle_DeviceMatchingCallback(void *inContext,IOReturn inResult,void *inSender,IOHIDDeviceRef inIOHIDDeviceRef) {
NSLog(@"插入:%p",(void *)inIOHIDDeviceRef);
}
static void Handle_DeviceRemovalCallback(void *inContext,IOReturn inResult,void *inSender,IOHIDDeviceRef inIOHIDDeviceRef) {
NSLog(@"拔出:%p設(shè)備",(void *)inIOHIDDeviceRef);
}
8、插入設(shè)備獲取到IOHIDDeviceRef inIOHIDDeviceRef后耳鸯,打開IOHIDDeviceRef
IOOptionBits options = 0;
IOReturn ret = IOHIDDeviceOpen(inIOHIDDeviceRef,options);
if (ret == kIOReturnSuccess) {
NSLog(@"打開成功");
}
9湿蛔、注冊的接收數(shù)據(jù)callback
IOHIDDeviceRegisterInputReportCallback(inIOHIDDeviceRef, (uint8_t*)inputbuffer, 64, MyInputCallback, NULL);
10、實(shí)現(xiàn)接收數(shù)據(jù)callback方法县爬,即可接收數(shù)據(jù)
static void MyInputCallback(void* context, IOReturn result, void* sender, IOHIDReportType type, uint32_t reportID, uint8_t *report,CFIndex reportLength) {
RobotPenUSBLog(@"%s",report);
}
11阳啥、向USB設(shè)備發(fā)送指令
IOReturn ret = IOHIDDeviceSetReport(inIOHIDDeviceRef, kIOHIDReportTypeOutput, 0, (uint8_t*)buffer, length);
if (ret != kIOReturnSuccess) {
NSLog(@"指令發(fā)送失敗");
}
12、斷開設(shè)備
IOReturn ret = IOHIDDeviceClose(inIOHIDDeviceRef,0L);
if (ret == kIOReturnSuccess) {
NSLog(@"斷開成功");
}
更多內(nèi)容請參考:蘋果官方開發(fā)者文檔
因?yàn)橛泻芏嗯笥阉叫盼襀ID 開發(fā)過程中遇到的一些問題财喳,有的涉及到公司的具體業(yè)務(wù)察迟,不便透露斩狱,這篇文章寫的有點(diǎn)雜亂籠統(tǒng),所以我整理了一篇新的帶實(shí)例的文章扎瓶,封裝好的工程修改對(duì)應(yīng)ID之后應(yīng)該可以直接連接下位機(jī)設(shè)備進(jìn)行測試的 ??
time:20190926
我新整理的 帶實(shí)例demo的 USB HID 通訊文章