使用IOKit与USB设备通信

时间:2015-02-03 13:43:29

标签: macos cocoa swift serial-port iokit

我正在尝试创建一个与USB设备通信的应用程序,就像我在终端上使用screen命令一样。

为了让我的问题更容易理解,这就是我通常在终端中所做的事情:

命令:

ls /dev/tty.usb*

返回:

/dev/tty.usbmodem1411   /dev/tty.usbmodem1451

接下来,我打电话给:

screen /dev/tty.usbmodem1411

在此之后,我可以向设备发送命令(例如输入“U”,获得响应)

我正试图从Xcode做到这一点。

使用IOKit,我设法执行的东西等同于返回usb端口列表的第一个命令:

/dev/tty.usbmodem1411   /dev/tty.usbmodem1451

这是代码:

@IBAction func testPressed(sender: AnyObject) {

        var portIterator: io_iterator_t = 0
        let kernResult = findSerialDevices(kIOSerialBSDModemType, serialPortIterator: &portIterator)
        if kernResult == KERN_SUCCESS {
            printSerialPaths(portIterator)
        }

    }

    func findSerialDevices(deviceType: String, inout serialPortIterator: io_iterator_t ) -> kern_return_t {
        var result: kern_return_t = KERN_FAILURE
        var classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue).takeUnretainedValue()
        var classesToMatchDict = (classesToMatch as NSDictionary) as Dictionary<String, AnyObject>
        classesToMatchDict[kIOSerialBSDTypeKey] = deviceType
        let classesToMatchCFDictRef = (classesToMatchDict as NSDictionary) as CFDictionaryRef
        result = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatchCFDictRef, &serialPortIterator);
        return result
    }

    func printSerialPaths(portIterator: io_iterator_t) {
        var serialService: io_object_t
        do {
            serialService = IOIteratorNext(portIterator)
            if (serialService != 0) {
                let key: CFString! = "IOCalloutDevice"
                let bsdPathAsCFtring: AnyObject? = IORegistryEntryCreateCFProperty(serialService, key, kCFAllocatorDefault, 0).takeUnretainedValue()
                var bsdPath = bsdPathAsCFtring as String?
                if let path = bsdPath {
                    println(path)
                }
            }
        } while serialService != 0;
    }
}

现在,即使在阅读了Apple的IOKit手册之后,我也无法继续前进。 如何使用IOKit开始发送命令?

1 个答案:

答案 0 :(得分:0)

请参阅Apple Performing Serial I/O示例项目。