[Rxtx] closing a serial port connection (hanging & exception access error)

Ilkka Myller ilkka at myller.com
Mon Feb 23 23:40:40 MST 2009


Hi,

I did not run or compile your code, but here are few things I noticed:

1. You should try to signal your SerialReader thread somehow that you  
are closing the serial port (add running-flag check there also, its  
missing. Interrupt the thread normally etc.).
I havent checked but closing the input stream in other thread while  
other is blocking in its read() does not sound good.
It might just return -1 from read() but I would not do it. I would  
interrupt the blocking thread nicely first - and then close cleanly.

2. In SerialReader read loop: dont assume that read( byte[] ) always  
returns full strings or complete lines from device. You should always  
parse the input for CR/LF delimiters across multiple reads.
For convenience, I would enclose the InputStream in BufferedReader,  
set it to correct text encoding expected from serial device (plain old  
ASCII for example?), and then use readLine() method to read strings.
I am assuming that your device sends full text strings delimited with  
CR or LF or both.

BufferedReader inb = new BufferedReader( new  
InputStreamReader( this.in,  "US-ASCII" ) );
then use inb.readLine() to read full strings.

3. Dont run entire initialization (connects etc.) in AWTs event queue  
thread. It's not nice. Try enclosing only the JFrame.setVisible() in  
event queue invoker.
This makes JVM main-thread the parent thread for all rxtx  
initializations etc, which is much better. Like this:

   public static void main(String args[]) {

                 try {
                     final SC x = new SC();
                     x.connect("COM3");
   		    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
			x.setVisible(true);	
		       }	
		     });
                 } catch (Exception e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }

   }



I hope these help :-)

--
I



More information about the Rxtx mailing list