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;
}
}
//打开串口
private boolean OpenComm(String PortName)
{
//获取指定的COM端口
try {
portIdentifier = CommPortIdentifier.getPortIdentifier(PortName);
} catch (NoSuchPortException e) {
e.printStackTrace();
return false;
}
//打开端口(3秒打不开则失败)
try {
serialPort = (SerialPort)portIdentifier.open(this.getTitle(),3000);
} catch (PortInUseException e) {
MessageDialog.openInformation(null, "OpenComm ", "Open_Err ");
e.printStackTrace();
return false;
}
//设置端口通讯参数 (波特率 = 9600,数据位 = 8,停止位 = 1 ,校验位 =奇校验)
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;
}
//设置输入流
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
MessageDialog.openInformation(null, "OpenComm ", "Set_InputStream ");
e.printStackTrace();
return false;
}
//设置输出流
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
MessageDialog.openInformation(null, "OpenComm ", "Set_OutputStream ");
e.printStackTrace();
return false;
}
//当串口有数据时通知
serialPort.notifyOnDataAvailable(true);
//当串口通讯中断时通知
serialPort.notifyOnBreakInterrupt(true);
//接收数据超时设置
try {
serialPort.enableReceiveTimeout(30);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
return false;
}
//设置一个串口数据暂存区
strBuffer=new StringBuffer();
//给当前串口添加一个监听器 DisposeSerialportMessage
try {
serialPort.addEventListener(
new SerialPortEventListener()
{
public void serialEvent(SerialPortEvent e)
{
disposeSerialportMessage(e);
}
}
);
} catch (TooManyListenersException e) {
e.printStackTrace();
return false;
}
return true;
}
|