JAVA通信编程(一)——串口通讯

来源:互联网 发布:linux文件写入权限 编辑:程序博客网 时间:2024/06/16 03:38

  博主结合实际经验,决定总结下JAVA通讯编程的一些小知识,希望能给给位读者有些帮助。这里的JAVA通讯编程主要是指如何应用JAVA编写串口、TCP以及UDP的通讯程序。本片主要讲述的是串口通讯。
    本人所知的java串口通讯可以采用两种方式实现:
    1. 采用comm.jar这个包,这个是sun提供的串口包javacomm20-win32.zip,可以搜索去下载。
    2. 采用RXTXComm.jar包。
    这两个的串口编程方式类似,有许多类名也相似,这里采用的是RXTXComm.jar,具体原因可以去问度娘,我是先用了comm.jar后来换成了rxtxcomm.jar。
    我采用的版本是:rxtx-2.1-7-bins-r2.zip.

通过目录可以看到RXTXcomm可以几种各种主流的操作系统,(不支持64位的windows系统)

不同的操作系统需要导入不同的库,可以参考里面的INSTALL文件,虽然是英文的,但是不难看懂,比如Windows操作系统下,将RXTXcomm.jar放入jre/lib/ext/下,将window的dll文件rxtxSerial.dll放入jre/bin下(linux的会有差异,可以参考INSTALL文件)。

虽然本文讲的是串口通讯,但是为了能够使我们的程序屏蔽底层差异,即上层应用只负责业务处理,底层的通讯不必管,通过一定的配置可以切换串口、tcp、udp进行通讯,这里我们的串口程序实现以公用接口:

package com.zzh.comm;public interface CommBuff{public byte[] readBuff();public void writeBuff(byte[] message);public void open();public void close();public Object getInfo();}

readBuff负责读数据,writeBuff负责写数据,open()做一些打开串口之类的事,close()做些资源关闭的工作,Object getInfo()预留接口,可以将一些状态通过这个接口传输出来,这个可以在TCP那篇博文中可以用到,具体是将TCP的Socket对象返送给上层应用。上层应用读取这个对象以便做相应的处理。

下面就是我们的串口通讯程序了:

package com.zzh.comm;import gnu.io.CommPortIdentifier;import gnu.io.NoSuchPortException;import gnu.io.PortInUseException;import gnu.io.SerialPort;import gnu.io.SerialPortEvent;import gnu.io.SerialPortEventListener;import gnu.io.UnsupportedCommOperationException;import java.io.BufferedOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.Map;import java.util.TooManyListenersException;import org.apache.log4j.Logger;public class SerialImpl implements CommBuff, SerialPortEventListener{private CommPortIdentifier portId;      private SerialPort serialPort;      private InputStream inputStream;      private OutputStream outputStream;      private boolean isOpen = false;        private static byte[] recvBuff = new byte[4096];    private static int recvLen = 0;        private String appName;    private String portName;    private int rate;    private int dataBit;    private int stopBit;    private int parityInt;    private int timeout;    private int delay;        private Logger logger = Logger.getLogger(Object.class.getName());        private String fileName = "/serial.properties";    public SerialImpl()    {    Map<String,String> map = new ReadProperties().getPropertiesMap(fileName);        try{    this.appName = map.get("appName");    this.portName = map.get("portName");String rates = map.get("rate");this.rate = Integer.parseInt(rates);String dataBits = map.get("dataBit");this.dataBit = Integer.parseInt(dataBits);String stopBits = map.get("stopBit");this.stopBit = Integer.parseInt(stopBits);String parityInts = map.get("parityInt");this.parityInt = Integer.parseInt(parityInts);String timeouts = map.get("timeout");this.timeout = Integer.parseInt(timeouts);String delays = map.get("delay");this.delay = Integer.parseInt(delays);}catch (Exception e){logger.error(e.getMessage());}    }        public void listPort()    {    CommPortIdentifier  cpid;    Enumeration<?> en = CommPortIdentifier.getPortIdentifiers();    while(en.hasMoreElements())    {    cpid = (CommPortIdentifier)en.nextElement();    if(cpid.getPortType() == CommPortIdentifier.PORT_SERIAL)    {    logger.info(cpid.getName());    }    }    }        public boolean isOpen(){return isOpen;}public void open()    {    if(isOpen)    {    close();    }try{portId = CommPortIdentifier.getPortIdentifier(portName);serialPort = (SerialPort) portId.open(appName,timeout);inputStream = serialPort.getInputStream();  serialPort.addEventListener(this);serialPort.notifyOnDataAvailable(true);serialPort.setSerialPortParams(rate, dataBit, stopBit, parityInt);isOpen = true;}catch (NoSuchPortException e){logger.error(e.getMessage());}catch (PortInUseException e){logger.error(e.getMessage());}catch (IOException e){logger.error(e.getMessage());}catch (TooManyListenersException e){logger.error(e.getMessage());}catch (UnsupportedCommOperationException e){logger.error(e.getMessage());}    }        public void close()    {    if(isOpen)    {    try    {    serialPort.notifyOnDataAvailable(false);    serialPort.removeEventListener();    inputStream.close();    serialPort.close();    isOpen = false;    }    catch(IOException ex)    {    logger.error(ex.getMessage());    }    }    }        private void checkPort()    {    if(portId==null)    {    throw new RuntimeException("no found serial port!");    }    if(serialPort == null)    {    throw new RuntimeException("serialPort object is failed!");    }    }    @Overridepublic synchronized void writeBuff(byte[] message){checkPort();try{outputStream = new BufferedOutputStream(serialPort.getOutputStream());}catch (IOException e){logger.error(e.getMessage());}try{outputStream.write(message);logger.info("发送成功: "+CommUtil.bytesToHex(message));}catch (IOException e){throw new RuntimeException("向端口发送信息出错: "+e.getMessage());}finally{try{outputStream.close();}catch(Exception e){logger.error(e.getMessage());}}}@Overridepublic synchronized  byte[] readBuff(){checkPort();byte[] ans = new byte[0];if(recvLen > 0){ans = new byte[recvLen];System.arraycopy(recvBuff,0,ans,0,recvLen);recvLen = 0;}return ans;}@Overridepublic synchronized void serialEvent(SerialPortEvent event){try{Thread.sleep(delay);}catch (InterruptedException e){logger.error(e.getMessage());}switch(event.getEventType()){case SerialPortEvent.BI:case SerialPortEvent.OE:case SerialPortEvent.FE:case SerialPortEvent.PE:case SerialPortEvent.CD:case SerialPortEvent.CTS:case SerialPortEvent.DSR:case SerialPortEvent.RI:case SerialPortEvent.OUTPUT_BUFFER_EMPTY:break;case SerialPortEvent.DATA_AVAILABLE:byte[] readBuffer = new byte[1024];try{while(inputStream.available()>0){int numBytes = inputStream.read(readBuffer);if(recvLen + numBytes>4096){throw new RuntimeException("接收缓存数组内容溢出");}else{logger.info("串口接收:"+CommUtil.bytesToHexWithLen(readBuffer,numBytes));for(int i=0;i<numBytes;i++){recvBuff[recvLen+i] = readBuffer[i];}recvLen = recvLen + numBytes;}}}catch(IOException e){logger.error(e.getMessage());}break;}}@Overridepublic Object getInfo(){// TODO Auto-generated method stubreturn null;}}

构造函数里面是初始化一些串口参数,这些参数都在serial.properties中存放,至于如何读取java的properties文件,封装成
Map<String,String> map = new ReadProperties().getPropertiesMap(fileName);

这样方便的读取将在下一篇文章中简要说明。

可以看到这个串口程序实现了接口中的功能,并且实现了SerialPortEventListener这个接口的serialEvent方法。

serial.properties文件内容如下:

#serial para#(随便配)appName=DIAOZHATIAN#串口名portName=COM3#波特率rate=9600#数据位dataBit=8#停止位stopBit=1#校验方式  (0:无校验 1:奇校验 2:偶校验)parityInt=0#(某些参数,不建议修改)timeout=2000#(某些参数,不建议修改)delay=1000

上层应用需要开辟一个线程专门读取readBuff中的数据,否则上面串口程序中开辟的4k的recvBuff很快会被塞满。

举例:上层应用采用多线程双向队列进行存储接收到的数据private ConcurrentLinkedDeque<Byte> deque = new ConcurrentLinkedDeque<Byte>();

private class readThread implements Runnable{@Overridepublic void run(){while(true){byte[] recvBuff = comm.readBuff();if(recvBuff.length>0){for(int i=0;i<recvBuff.length;i++){deque.add(recvBuff[i]);}}try{TimeUnit.MILLISECONDS.sleep(1000);}catch (InterruptedException e){e.printStackTrace();}}}}
然后在初始化的时候开启这个线程并设置成后台线程。

            ExecutorService pool = Executors.newFixedThreadPool(1);            Thread thread1 = new Thread(new readThread());            thread1.setDaemon(true);            pool.execute(thread1);
关于串口通讯,先写到这里。再下一篇先插播一下如何读取java的配置文件properties,然后继续讲述如何使用java进行tcp通讯。


3 1
原创粉丝点击