00001
00002 package serialInterface;
00003
00004 import java.util.Enumeration;
00005 import java.util.TooManyListenersException;
00006 import java.util.Vector;
00007
00008 import javax.comm.CommPortIdentifier;
00009 import javax.comm.PortInUseException;
00010 import javax.comm.SerialPort;
00011 import javax.comm.SerialPortEventListener;
00012 import javax.comm.UnsupportedCommOperationException;
00013
00014
00033 public class SerialPortUtilities{
00034
00035
00045 public static Vector<String> getSerialPortNames( ){
00046
00047 Vector<String> serialPortNames = new Vector<String>( );
00048 Enumeration availablePorts = CommPortIdentifier.getPortIdentifiers( );
00049
00050
00051 for( ; availablePorts.hasMoreElements( ); ){
00052
00053 CommPortIdentifier currentPort = (CommPortIdentifier)availablePorts.nextElement ( );
00054
00055
00056 if( ( currentPort.getPortType( ) == CommPortIdentifier.PORT_SERIAL ) &&
00057 ( currentPort.isCurrentlyOwned( ) == false ) ){
00058
00059 serialPortNames.add( currentPort.getName( ) );
00060 }
00061 }
00062
00063 return serialPortNames;
00064 }
00065
00076 public static SerialPort connectToSerialPort( String serialPortName ){
00077
00078
00079 Enumeration availablePorts = CommPortIdentifier.getPortIdentifiers( );
00080 SerialPort ret = null;
00081
00082
00083 for( ; availablePorts.hasMoreElements( ); ){
00084
00085 CommPortIdentifier currentPort = ( CommPortIdentifier )availablePorts.nextElement ( );
00086
00087 String currentPortName = ( String )currentPort.getName( );
00088
00089
00090 if( currentPortName.equals( serialPortName ) ){
00091
00092 try{
00093 ret = ( SerialPort )currentPort.open( "AVR SerialPortLibrary" , 200 );
00094 }catch( PortInUseException piue ){
00095
00096 piue.printStackTrace( );
00097 ret = null;
00098 }
00099
00100 break;
00101 }
00102 }
00103
00104 return ret;
00105 }
00106
00117 public static boolean setBaudRate( SerialPort portToConfigure, final int BAUD_RATE ){
00118
00119 try{
00120 portToConfigure.setSerialPortParams( BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
00121 SerialPort.PARITY_NONE );
00122 }catch( UnsupportedCommOperationException ucoe ){
00123
00124 ucoe.printStackTrace( );
00125 return false;
00126 }
00127
00128 return true;
00129 }
00130
00141 public static boolean addSerialEventListener( SerialPort portToAddListener, SerialPortEventListener listener ){
00142
00143 try{
00144 portToAddListener.addEventListener( listener );
00145 }catch( TooManyListenersException tmle ){
00146
00147 tmle.printStackTrace( );
00148 return false;
00149 }
00150
00151
00152 portToAddListener.notifyOnDataAvailable( true );
00153
00154 return true;
00155 }
00156 }