首页 文章

从插入设备的IOKit(CoreFoundation)接收通知时出现问题

提问于
浏览
3

我正在开发一个10.6.7上的应用程序,它应该在插入新的USB设备时收到通知 . 我发现有一个IOKit函数可以处理这些东西'IOServiceAddMatchingNotification' . 因为这个特定函数的返回值是0,我认为这个问题可能出现在我的匹配字典中,该字典被赋予了这个函数 . 我这样宣布字典:

CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);

因为我不想收到每个设备的通知,所以我不知道这是否是创建这个特定字典的正确方法 .

我的完整代码如下所示:

ioKitNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);
notificationRunLoopSource = IONotificationPortGetRunLoopSource(ioKitNotificationPort);

CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);

CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);


addMatchingNotificationResult = IOServiceAddMatchingNotification(ioKitNotificationPort,
                                                                 kIOPublishNotification,
                                                                 matchingDict,
                                                                 deviceAdded,
                                                                 NULL,

有谁知道为什么这不起作用? (注意:Callback函数是一个静态void c函数,其余部分包含在一个Obj-C类中) .

谢谢

Xcode 4,10.6.7

4 回答

  • 0

    您是否将要查找的设备的VID和PID添加到匹配的字典中?对于你拥有的字典,VID = yourVid,PID = yourPid,它将是:

    CFDictionaryAddValue(matchingDict, usbVendorId, yourVid);  
    CFDictionaryAddValue(matchingDict, usbProductId, yourPid);
    

    另一件事 - 在调用IOServiceAddMatchingNotification成功之后,您需要使用在调用中设置的迭代器调用设备添加的处理程序 . 这将触发通知并检查现有设备 .

  • 1

    做我认为你所描述的最简单的方法是挂钩DiskArbitration Framework . DA对OSX来说相对较新,允许用户态应用程序在连接时检查设备 . 它是用于在连接iPod时打开iTunes,在连接相机时启动iPhoto等等...如果您要查找的USB设备是存储设备,那么这将适合您 . 否则你需要去匹配的字典路线......

  • 1

    奇怪的是,在通知将被布防之前,您必须清空IOServiceAddMatchingNotification返回的迭代器 . 我在提供的代码中没有看到,因此可能存在问题 . 该迭代器实际上是您需要保持通知以保持通知运行 .

    io_iterator_t ioNotification;
    
    addMatchingNotificationResult = IOServiceAddMatchingNotification(ioKitNotificationPort,
                                                                     kIOPublishNotification,
                                                                     matchingDict,
                                                                     deviceAdded,
                                                                     NULL,
                                                                     &ioNotification);
    
    while ((service = IOIteratorNext(ioNotification)))
    {
        NSLog(@"Hey, I found a service!");
    
        IOObjectRelease(service); // yes, you have to release this
    }
    
  • 3

    在我看来,你应该在opensource.apple.com上下载源代码表格IOUSBFamily,然后找到 USB Prober 的代码,这个应用程序与你描述的完全一样,听USB设备附件 . (此外, USB Prober 也得到一般设备和配置描述符,也许它也是你需要的东西 . )

相关问题