如何在Swift中实现IOServiceMatchingCallBack

时间:2016-01-06 08:17:34

标签: swift macos usb iokit

我想在我的应用程序中检测到插入/删除的特定USB。现在,我可以使用本教程 Working With USB Device Interfaces获取deviceName。但是,如何在Swift中执行(deviceAdded) IOServiceMatchingCallBack 的回调函数。

我尝试如下,但是我收到了一个错误:无法转换类型的值'(UnsafePointer,iterator:io_iterator_t) - > ()'到期望的参数类型'IOServiceMatchingCallback!'

func detectUSBEvent() {
    var portIterator: io_iterator_t = 0
    var kr: kern_return_t = KERN_FAILURE
    let matchingDict = IOServiceMatching(kIOUSBDeviceClassName)

    let vendorIDString = kUSBVendorID as CFStringRef!
    let productIDString = kUSBProductID as CFStringRef!
    CFDictionarySetValue(matchingDict, unsafeAddressOf(vendorIDString), unsafeAddressOf(VendorID))
    CFDictionarySetValue(matchingDict, unsafeAddressOf(productIDString), unsafeAddressOf(ProductID))

    // To set up asynchronous notifications, create a notification port and add its run loop event source to the program’s run loop
    let gNotifyPort: IONotificationPortRef = IONotificationPortCreate(kIOMasterPortDefault)
    let runLoopSource: Unmanaged<CFRunLoopSource>! = IONotificationPortGetRunLoopSource(gNotifyPort)
    let gRunLoop: CFRunLoop! = CFRunLoopGetCurrent()

    CFRunLoopAddSource(gRunLoop, runLoopSource.takeUnretainedValue(), kCFRunLoopDefaultMode)

    // Notification of first match:
    kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, deviceAdded, nil, &portIterator)
    deviceAdded(nil, iterator: portIterator)
 }


func deviceAdded(refCon: UnsafePointer<Void>, iterator: io_iterator_t) {
    if let usbDevice: io_service_t = IOIteratorNext(iterator)
    {
        let name = String()
        let cs = (name as NSString).UTF8String
        let deviceName: UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>(cs)

        let kr: kern_return_t = IORegistryEntryGetName(usbDevice, deviceName)
        if kr == KERN_SUCCESS {
            let deviceNameAsCFString = CFStringCreateWithCString(kCFAllocatorDefault, deviceName,
                kCFStringEncodingASCII)
            print(deviceNameAsCFString)
            // if deviceNameAsCFString == XXX
            // Do Something
        }

    }

}

3 个答案:

答案 0 :(得分:8)

这里是一个Swift 3版本,使用闭包代替全局函数(没有上下文的闭包可以桥接到C函数指针),使用GCD代替Runloops(更好的API),使用回调和调度通知事件和使用真实对象而不是静态对象或单例:

import Darwin
import IOKit
import IOKit.usb
import Foundation


class IOUSBDetector {

    enum Event {
        case Matched
        case Terminated
    }

    let vendorID: Int
    let productID: Int

    var callbackQueue: DispatchQueue?

    var callback: (
        ( _ detector: IOUSBDetector,  _ event: Event,
            _ service: io_service_t
        ) -> Void
    )?


    private
    let internalQueue: DispatchQueue

    private
    let notifyPort: IONotificationPortRef

    private
    var matchedIterator: io_iterator_t = 0

    private
    var terminatedIterator: io_iterator_t = 0


    private
    func dispatchEvent (
        event: Event, iterator: io_iterator_t
    ) {
        repeat {
            let nextService = IOIteratorNext(iterator)
            guard nextService != 0 else { break }
            if let cb = self.callback, let q = self.callbackQueue {
                q.async {
                    cb(self, event, nextService)
                    IOObjectRelease(nextService)
                }
            } else {
                IOObjectRelease(nextService)
            }
        } while (true)
    }


    init? ( vendorID: Int, productID: Int ) {
        self.vendorID = vendorID
        self.productID = productID
        self.internalQueue = DispatchQueue(label: "IODetector")

        let notifyPort = IONotificationPortCreate(kIOMasterPortDefault)
        guard notifyPort != nil else { return nil }

        self.notifyPort = notifyPort!
        IONotificationPortSetDispatchQueue(notifyPort, self.internalQueue)
    }

    deinit {
        self.stopDetection()
    }


    func startDetection ( ) -> Bool {
        guard matchedIterator == 0 else { return true }

        let matchingDict = IOServiceMatching(kIOUSBDeviceClassName)
            as NSMutableDictionary
        matchingDict[kUSBVendorID] = NSNumber(value: vendorID)
        matchingDict[kUSBProductID] = NSNumber(value: productID)

        let matchCallback: IOServiceMatchingCallback = {
            (userData, iterator) in
                let detector = Unmanaged<IOUSBDetector>
                    .fromOpaque(userData!).takeUnretainedValue()
                detector.dispatchEvent(
                    event: .Matched, iterator: iterator
                )
        };
        let termCallback: IOServiceMatchingCallback = {
            (userData, iterator) in
                let detector = Unmanaged<IOUSBDetector>
                    .fromOpaque(userData!).takeUnretainedValue()
                detector.dispatchEvent(
                    event: .Terminated, iterator: iterator
                )
        };

        let selfPtr = Unmanaged.passUnretained(self).toOpaque()

        let addMatchError = IOServiceAddMatchingNotification(
            self.notifyPort, kIOFirstMatchNotification,
            matchingDict, matchCallback, selfPtr, &self.matchedIterator
        )
        let addTermError = IOServiceAddMatchingNotification(
            self.notifyPort, kIOTerminatedNotification,
            matchingDict, termCallback, selfPtr, &self.terminatedIterator
        )

        guard addMatchError == 0 && addTermError == 0 else {
            if self.matchedIterator != 0 {
                IOObjectRelease(self.matchedIterator)
                self.matchedIterator = 0
            }
            if self.terminatedIterator != 0 {
                IOObjectRelease(self.terminatedIterator)
                self.terminatedIterator = 0
            }
            return false
        }

        // This is required even if nothing was found to "arm" the callback
        self.dispatchEvent(event: .Matched, iterator: self.matchedIterator)
        self.dispatchEvent(event: .Terminated, iterator: self.terminatedIterator)

        return true
    }


    func stopDetection ( ) {
        guard self.matchedIterator != 0 else { return }
        IOObjectRelease(self.matchedIterator)
        IOObjectRelease(self.terminatedIterator)
        self.matchedIterator = 0
        self.terminatedIterator = 0
    }
}

以下是测试该类的一些简单测试代码(根据您的USB设备设置产品和供应商ID):

let test = IOUSBDetector(vendorID: 0x4e8, productID: 0x1a23)
test?.callbackQueue = DispatchQueue.global()
test?.callback = {
    (detector, event, service) in
        print("Event \(event)")
};
_ = test?.startDetection()
while true { sleep(1) }

答案 1 :(得分:1)

在我将回调函数放在类之后工作。但是,我不知道为什么。

import farm.Tractor;

答案 2 :(得分:0)

得到了这份工作,谢谢!唯一的问题是我没有在我的回调函数中使用迭代器,因此该函数甚至没有被调用!对我来说似乎有些奇怪的行为,但那是我的问题