Search code examples
swiftxcodeserial-portorsserialport

Cannot receive data from ORSSerialPort


I'm trying to use ORSSerialPort to send and receive data to and from serial port.

I'm following the example here but I'm using commandline app: https://github.com/armadsen/ORSSerialPort/tree/master/Examples/ORSSerialPortDemo

I believe I copied/implemented every required method, but the problem is although I can send data to my serial port(I double confirmed from my serial port log and the send succeeded), I cannot receive anything.

My code is very simple as below - it is only intended to be a prototype so the code might not be well designed.

So am I missing anything that I cannot receive data from serial port? Any suggestions are appreciated.

import ORSSerial


class SerialController : NSObject, ORSSerialPortDelegate {
        var port : ORSSerialPort?

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

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

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

        func SendString(data: String){
            let dataa = Data(data.utf8)
            port?.send(dataa)
        }

    func serialPortWasOpened(_ serialPort: ORSSerialPort) {
            print("PORT IS OPEN....")
        }

    func serialPortWasClosed(_ serialPort: ORSSerialPort) {
            print("PORT IS CLOSE")
        }

    func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
        print(NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)!)
        }

    func serialPortWasRemovedFromSystem(_ serialPort: ORSSerialPort) {
            print("PORT REMOVED")
        }

    private func serialPort(serialPort: ORSSerialPort!, didEncounterError error: NSError!) {
        print("PORT ERR \(String(describing: error))")
        }
    }



var mySerial = SerialController(path: "/dev/myserialport")

mySerial.open()

mySerial.SendString(data: "test")

Solution

  • Assuming the code you included is the complete program source code (ie. you're compiling it as a command-line app), the problem is that the program terminates right after sendString() is called, so the port has no chance to receive anything. You need to keep the program alive and running. There are multiple ways to do that, but the simplest is just to call RunLoop.main.run() as the last line of the program. That will cause the run loop to run indefinitely processing input from all sources, and will both keep the program alive and run the system machinery that ORSSerialPort relies on.

    // SerialController class you has looks good, and goes here
    
    let mySerial = SerialController(path: "/dev/myserialport")
    mySerial.open()
    mySerial.SendString(data: "test")
    
    RunLoop.main.run()