Java SWT 设计RS232/RS485串口接受的界面,用线程读取和发送

时间:2022-05-14 01:15:29

本文主要介绍基于eclipse SWT 设计RS232/RS485串口接受的界面,并且用线程读取和发送。

部分代码如下:

主界面:

当选择好下拉框的内容后,点击打开按钮,调用函数将参数传递给串口,并以全双工的方式传输数据;关闭按钮即为断开串口的连接。

Java SWT 设计RS232/RS485串口接受的界面,用线程读取和发送

界面UIjava调用SerialRead.java和Serialwrite.java

serialRead.java

public class SerialRead extends Observable implements Runnable, SerialPortEventListener {


/**
* @param args
*/

/*public static void main(String[] args) {
System.out.println(1);

}*/


public SerialRead() {
isOpen = false; // 初始时刻关闭串口,防止非法占用
}

public boolean isOpen() {
return isOpen;

}

@SuppressWarnings("rawtypes")
public void open(HashMap params) throws SerialPortException {


//SerialWrite serialwrite=new SerialWrite();
//this.outputStream=SerialWrite.outputStreamwrite;
/*serialwrite.isWrite=a;
serialwrite.meg=b;*/

serialParams = params;
if(isOpen){ //重新打开前先关闭
close();
}

try {

delay_read=Integer.parseInt(serialParams.get(PARAMS_DELAY).toString());
timeout = Integer.parseInt(serialParams.get(PARAMS_TIMEOUT).toString());
rate = Integer.parseInt(serialParams.get(PARAMS_RATE).toString());
parity = Integer.parseInt(serialParams.get(PARAMS_PARITY).toString());
databit = Integer.parseInt(serialParams.get(PARAMS_DATABITS).toString());
stopbit = Integer.parseInt(serialParams.get(PARAMS_STOPBITS).toString());
portname = serialParams.get(PARAMS_PORT).toString();
portId = CommPortIdentifier.getPortIdentifier(portname);// NoSuchPortException异常
serialPort = (SerialPort) portId.open("SerialRead", timeout);// PortInUseException
inputStream = serialPort.getInputStream();// IOException
serialPort.addEventListener(this);// TooManyListenersException
serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(rate, databit, stopbit, parity);// UnsupportedCommOperationException
isOpen = true;
//if(!isSend){

//serialPort.notifyOnDataAvailable(false);// 数据监听
//}
//else{
outputStream=serialPort.getOutputStream();
//}


} catch (NoSuchPortException e) {
throw new SerialPortException("端口"
+ serialParams.get(PARAMS_PORT).toString() + "不存在");
} catch (PortInUseException e) {
throw new SerialPortException("端口"
+ serialParams.get(PARAMS_PORT).toString() + "已经被占用");
} catch (TooManyListenersException e) {
throw new SerialPortException("端口"
+ serialParams.get(PARAMS_PORT).toString() + "监听者过多");
} catch (UnsupportedCommOperationException e) {
throw new SerialPortException("端口操作命令不支持");
} catch (IOException e) {
throw new SerialPortException("打开端口"+ serialParams.get(PARAMS_PORT).toString() + "失败");
}
readThread = new Thread(this);
readThread.start();

}

public void close() throws SerialPortException {// 关闭串口serial,释放资源inputstream
if (isOpen) {

try {
serialPort.notifyOnDataAvailable(false);// 数据监听
serialPort.removeEventListener();// 关闭监听
inputStream.close();
serialPort.close();
isOpen = false;
} catch (IOException e) {
throw new SerialPortException("关闭串口失败");
}

}
}

@Override
public void run() {// 读取线程执行间隔
try {

Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

@Override
public void serialEvent(SerialPortEvent event) {
try {
Thread.sleep(delay_read);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (event.getEventType()) {
case SerialPortEvent.BI: // 10
case SerialPortEvent.OE: // 7
case SerialPortEvent.FE: // 9
case SerialPortEvent.PE: // 8
case SerialPortEvent.CD: // 6
case SerialPortEvent.CTS: // 3
case SerialPortEvent.DSR: // 4
case SerialPortEvent.RI: // 5
case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2
break;
case SerialPortEvent.DATA_AVAILABLE: // 1
//读取数据
try {
// 多次读取,将所有数据读入
// listPorts();
// System.out.println(inputStream.available());
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);//一次接受有多少数据
}

// 打印接收到的字节数据的ASCII码
for (int i = 0; i < numBytes; i++) {//逐个输出
// System.out.println("msg[" + numBytes + "]: ["
// +readBuffer[i] + "]:"+(char)readBuffer[i]);
}
// numBytes = inputStream.read( readBuffer );
changeMessage( readBuffer, numBytes );
} catch (IOException e) {
e.printStackTrace();
}
break;

}
}

//*************************************//
//******************二次改进:对信息提取!!!!!!!!!!!!!!!!!!!
//*************************************//

// 通过observer pattern将收到的数据发送给observer
// 将buffer中的空字节删除后再发送更新消息,通知观察者
public void changeMessage( byte[] message, int length )
{
setChanged();
byte[] temp = new byte[length];//临时数组
System.arraycopy( message, 0, temp, 0, length );
notifyObservers(temp);//更新后通知observer,传递数据
}
static void listPorts()
{
portList= CommPortIdentifier.getPortIdentifiers();//得到系统中的端口列表
while ( portList.hasMoreElements() )
{
CommPortIdentifier portIdentifier = ( CommPortIdentifier ) portList.nextElement();
System.out.println( portIdentifier.getName() + " - "+getPortTypeName( portIdentifier.getPortType() ) );
}
}


public void writeComm(String cmd) {
// isSend=send;

//System.out.println(cmd);

try {
outputStream.write(cmd.getBytes());


}
catch (IOException e) {
e.printStackTrace(); }

}
public static HashSet<CommPortIdentifier> getAvailableSerialPorts()
{
HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
thePorts = CommPortIdentifier.getPortIdentifiers();
while ( thePorts.hasMoreElements() )
{
com = ( CommPortIdentifier ) thePorts.nextElement();
switch ( com.getPortType() )
{
case CommPortIdentifier.PORT_SERIAL:
try
{
CommPort thePort = com.open( "CommUtil", 50 );
thePort.close();
h.add( com );<pre name="code" class="java">

 

SerialWrite.java

public class SerialWrite extends Thread{

static boolean isWrite=true;
public volatile static boolean exit = false;

public void run() {
while(!exit)
{
try {
Thread.sleep(100);
writeComm("12345");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void writeComm(String cmd) {
// isSend=send;

System.out.println(cmd);
}

public static void main(String[] args) {

new SerialWrite().start();

while (isWrite) {
try {

Thread.sleep(4000);
exit=true;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}