macos - 为什么 ORSSerialPort 接收委托(delegate)在我的 Swift 项目中不起作用

标签 macos swift xcode6 orsserialport

我有一个简单的 SerialController 类:

class SerialController : NSObject, ORSSerialPortDelegate {
    var port : ORSSerialPort

    init(path: String){
        port=ORSSerialPort(path: path)
        port.close()
    }

    func open(){
        port.baudRate=9600
        port.delegate=self
        port.open()
    }

    func close(){
        port.delegate=nil
        port.close()
    }

    func SendString(data: String){
        port.sendData(data.dataUsingEncoding(NSUTF8StringEncoding))
    }

    func serialPortWasOpened(serialPort: ORSSerialPort!) {
        println("PORT IS OPEN....")
    }

    func serialPortWasClosed(serialPort: ORSSerialPort!) {
        println("PORT IS CLOSE")
    }

    func serialPort(serialPort: ORSSerialPort!, didReceiveData data: NSData!) {
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }

    func serialPortWasRemovedFromSystem(serialPort: ORSSerialPort!) {
        println("PORT REMOVED")
    }

    func serialPort(serialPort: ORSSerialPort!, didEncounterError error: NSError!) {
        println("PORT ERR \(error)")
    }
}

以及将数据发送到 FT232 适配器的简单代码

func readLine()->String{
    return NSString(data:NSFileHandle.fileHandleWithStandardInput().availableData, encoding: NSUTF8StringEncoding)
}

let myPort = SerialController(path: "/dev/cu.usbserial-CN920229")

myPort.open()
println("type your data to send...")
let k = readLine()
myPort.SendString(k)
myPort.close()

FT232 的 RX 和 TX 引脚连接在一起,我想接收数据回显。 我可以连接到我的适配器,SendString 方法可以正确地将数据发送到 FT232,但接收不起作用! 在 cocoaDemo 中,我测试了我的 FT232,我可以得到正确的响应。 我能做什么?

最佳答案

根本问题是您立即关闭端口,程序在端口上发送数据后结束。您需要保持程序运行并打开端口以接收数据。最简单的方法是在发送数据后旋转运行循环:

func readLine()->String?{
    return NSString(data:NSFileHandle.fileHandleWithStandardInput().availableData, encoding: NSUTF8StringEncoding)
}

let myPort = SerialController(path: "/dev/cu.USA19H141P1.1")

myPort.open()
println("type your data to send...")
if let k = readLine() {
    myPort.SendString(k)
}

NSRunLoop.currentRunLoop().run() // <-- This will continue indefinitely.

请注意,虽然这将允许您接收数据,但它当然不是一个结构良好的程序。程序每次运行只能发送一个字符串,因为您只调用一次 readLine() 而不是循环并重复调用它。除了用 ⌘- 杀死它之外,也没有办法退出程序。或类似的。

如果您打算将它变成一个真正的程序,您可以将其用于不仅仅是快速的一次性测试,我建议您查看 CommandLineDemo ORSSerialPort 的示例文件夹中的项目。 Swift 和 Objective-C 都提供了该示例的多个版本。

关于macos - 为什么 ORSSerialPort 接收委托(delegate)在我的 Swift 项目中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27061747/

相关文章:

Xcode 4 加载项目后不显示任何文件

ios - 在 swift 中捕获无效用户输入的异常

ios - 如何子类化 UICollectionViewFlowLayout 以便可以覆盖 layoutAttributesForElementsInRect

ios - ScaleMode 根本不起作用

swift - 具有返回类型的 swift 方法

python - 在 Mac OS X 上静态嵌入 Python 时动态符号查找失败

python - Tkinter Spinbox 和多处理导致 mac SEGFAULT

Python - 超越 RAM 限制?

swift - 将 NSCore 和 NSKeyedArchiver 与 SWIFT 结合使用

ios - 在几个应用程序中用新的 Swift 替换旧的 Objective-c 库