RXTX serial connection - issue with blocking read()

后端 未结 4 1009
别那么骄傲
别那么骄傲 2021-01-03 11:58

I am trying to use the RXTX library for blocking serial communication on Windows (XP and 7). I have tested the connection with Hyperterminal in both ends, and it works flawl

相关标签:
4条回答
  • 2021-01-03 12:12

    I think the code you wrote in your own readLine implementation is buggy. nextByte[0] is never restored to -1 after the first character is read. You should try to use the value returned by inStream.read(nextByte) to state the number of bytes read from the stream instead of the value of your byte array.

    Anyway I think you should go for an event based method of reading the inputs with a SerialPortEventListener:

    serialPort.addEventListener(new SerialPortEventListener() {
    
          public void serialEvent(SerialPortEvent evt) {
               switch (evt.getEventType()) {
               case SerialPortEvent.DATA_AVAILABLE:
                   dataReceived();
                   break;
               default:
                   break;
               }
          }
    });
    serialPort.notifyOnDataAvailable(true);
    
    0 讨论(0)
  • 2021-01-03 12:12

    I have solved this way

    try 
            {
                if(input.ready()==true)
                {
                String inputLine=input.readLine();
                System.out.println(inputLine);
                }
    
            } catch (Exception e) 
    
    0 讨论(0)
  • 2021-01-03 12:18

    Use RXTX-2.2pre2, previous versions have had a bug which prevented blocking I/O from working correctly.

    And do not forget to set port to blocking mode:

    serialPort.disableReceiveTimeout();
    serialPort.enableReceiveThreshold(1);
    
    0 讨论(0)
  • 2021-01-03 12:25

    it may not be blocking but when the stream is empty, just catch the IOE and keep reading from it. This is what I do with RXTX-2.1-7 and it works fine, I use it to read and write to an arduino:

    public static class SerialReader implements Runnable {
        InputStream in;
        public SerialReader(InputStream in) {
            this.in = in;
        }
        public void run() {
            Boolean keepRunning = true;
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while (keepRunning) {
                try {
                    while ((line = br.readLine()) != null) {
                      //DO YOUR STUFF HERE
                    }
                } catch (IOException e) {
                    try {
                        //ignore it, the stream is temporarily empty,RXTX's just whining
                        Thread.sleep(200);
                    } catch (InterruptedException ex) {
                        // something interrupted our sleep, exit ...
                        keepRunning = false;
                    }
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题