Mac开发之USB HID 通讯

框架:IOKit.framework

简介:用于Mac OS 上位机软件根据USB线连接下位机硬件,与之进行数据交互,通讯。

开发步骤:

1、导入依赖头文件

#include <IOKit/hid/IOHIDLib.h>

2、初始化IOHIDManager

IOHIDManagerRef managerRef = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);

3、进行配对设置,可以过滤其他USB设备。

1).无配对设备

IOHIDManagerSetDeviceMatching(HIDManager, NULL);

2).单类设备配对

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).多种设备配对设置

NSMutableArray *arr = [NSMutableArray array];
[arr addObject:dict];
IOHIDManagerSetDeviceMatchingMultiple(managerRef, (__bridge CFMutableArrayRef)arr);

4、注册插拔设备的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、实现插拔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设备",(void *)inIOHIDDeviceRef);
}

8、插入设备获取到IOHIDDeviceRef inIOHIDDeviceRef后,打开IOHIDDeviceRef

IOOptionBits options = 0;
    IOReturn ret = IOHIDDeviceOpen(inIOHIDDeviceRef,options);
    if (ret == kIOReturnSuccess) {
        NSLog(@"打开成功");
    }

9、注册的接收数据callback

IOHIDDeviceRegisterInputReportCallback(inIOHIDDeviceRef, (uint8_t*)inputbuffer, 64, MyInputCallback, NULL);

10、实现接收数据callback方法,即可接收数据

static void MyInputCallback(void* context, IOReturn result, void* sender, IOHIDReportType type, uint32_t reportID, uint8_t *report,CFIndex reportLength) {
     RobotPenUSBLog(@"%s",report);
}

11、向USB设备发送指令

IOReturn ret = IOHIDDeviceSetReport(inIOHIDDeviceRef, kIOHIDReportTypeOutput, 0, (uint8_t*)buffer, length);
    if (ret != kIOReturnSuccess) {
         NSLog(@"指令发送失败");
    }

12、断开设备

IOReturn ret = IOHIDDeviceClose(inIOHIDDeviceRef,0L);
  if (ret == kIOReturnSuccess) {
     NSLog(@"断开成功");
    }

更多内容请参考:苹果官方开发者文档

    原文作者:隐身人
    原文地址: https://www.jianshu.com/p/fb281319b185
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞