// Initialize the serial driver
Private Boolean initcommdriver_win32 (){
Try {
System. loadlibrary ("win32com ");
String drivername = "com. Sun. Comm. win32driver ";
Commdriver driver = (commdriver) class. forname (drivername). newinstance ();
Driver. initialize ();
Return true;
} Catch (throwable e ){
Messagedialog. openinformation (null, "initdriver", "initdriver_err_win32com ");
E. printstacktrace ();
Return false;
}
}
// Open the serial port
Private Boolean opencomm (string portname)
{
// Obtain the specified COM port
Try {
Portidentifier = comatrix ortidentifier. getportidentifier (portname );
} Catch (nosuchportexception e ){
E. printstacktrace ();
Return false;
}
// Open the port (failure if the port cannot be opened in 3 seconds)
Try {
SerialPort = (SerialPort) portidentifier. Open (this. gettitle (), 3000 );
} Catch (portinuseexception e ){
Messagedialog. openinformation (null, "opencomm", "open_err ");
E. printstacktrace ();
Return false;
}
// Set the port communication parameters (baud rate = 9600, data bit = 8, stop bit = 1, check bit = odd check)
Try {
SerialPort. setserialportparams (9600,
SerialPort. databits_8,
SerialPort. stopbits_1,
SerialPort. parity_odd );
} Catch (unsupportedcommoperationexception E)
{
Messagedialog. openinformation (null, "opencomm", "set_port ");
E. printstacktrace ();
Return false;
}
// Set the input stream
Try {
Inputstream = SerialPort. getinputstream ();
} Catch (ioexception e ){
Messagedialog. openinformation (null, "opencomm", "set_inputstream ");
E. printstacktrace ();
Return false;
}
// Set the output stream
Try {
Outputstream = SerialPort. getoutputstream ();
} Catch (ioexception e ){
Messagedialog. openinformation (null, "opencomm", "set_outputstream ");
E. printstacktrace ();
Return false;
}
// Notification when data exists in the serial port
SerialPort. yonyondataavailable (true );
// Notification when serial communication is interrupted
SerialPort. yonyonbreakinterrupt (true );
// Timeout settings for receiving data
Try {
SerialPort. enablereceivetimeout (30 );
} Catch (unsupportedcommoperationexception e ){
E. printstacktrace ();
Return false;
}
// Set a serial data staging area
Strbuffer = new stringbuffer ();
// Add a listener disposeserialportmessage to the current serial port
Try {
SerialPort. addeventlistener (
New serialporteventlistener ()
{
Public void serialevent (serialportevent E)
{
Disposeserialportmessage (E );
}
}
);
} Catch (toomanylistenersexception e ){
E. printstacktrace ();
Return false;
}
Return true;
}