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

来源:互联网 发布:中国移动办公软件 编辑:程序博客网 时间:2024/06/06 08:54

本文主要介绍基于eclipse 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);// PortInUseExceptioninputStream = serialPort.getInputStream();// IOExceptionserialPort.addEventListener(this);// TooManyListenersExceptionserialPort.notifyOnDataAvailable(true);serialPort.setSerialPortParams(rate, databit, stopbit, parity);// UnsupportedCommOperationExceptionisOpen = 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,释放资源inputstreamif (isOpen) {try {serialPort.notifyOnDataAvailable(false);// 数据监听serialPort.removeEventListener();// 关闭监听inputStream.close();serialPort.close();isOpen = false;} catch (IOException e) {throw new SerialPortException("关闭串口失败");}}}@Overridepublic void run() {// 读取线程执行间隔try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}@Overridepublic void serialEvent(SerialPortEvent event) {try {Thread.sleep(delay_read);} catch (InterruptedException e) {e.printStackTrace();}switch (event.getEventType()) {case SerialPortEvent.BI: // 10case SerialPortEvent.OE: // 7case SerialPortEvent.FE: // 9case SerialPortEvent.PE: // 8case SerialPortEvent.CD: // 6case SerialPortEvent.CTS: // 3case SerialPortEvent.DSR: // 4case SerialPortEvent.RI: // 5case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2break;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 blocke.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 blocke.printStackTrace();}}    } }


0 0
原创粉丝点击