返回列表 回复 发帖

JAVA操作串口有感

在做过一年多的RXTX操作串口项目有现在把一些平时遇到的问题在这里写写:
RXTX是一个开源包,主要是在COMM开源包中做扩张,以前的COMM包只能在WINDOWS下面对串口或并口做操作,扩充后的RXTX可以在LINUX和MAC下对串口和并口做操作。  现在跨平台:

在RXTX网站下载JAR包和动态库
http://users.frii.com/jarvi/rxtx/download.html

下载后配置环境

Windows

拷贝RXTXcomm.jar 文件到 \jre\lib\ext 目录下
拷贝rxtxSerial.dll文件到 \jre\bin目录下

Mac OS X (x86 and ppc) (there is an Installer with the source)

MAC下面我自己没有配置环境成功,后来找一个MAC下RXTX的安装把环境配置好的。
http://www.jdivelog.org/how-to/mac-os-x/下载安装环境配置文件RXTX_Tiger.pkg

Linux (only x86, x86_64, ia64 here but more in the ToyBox)

拷贝RXTXcomm.jar 文件到 /jre/lib/ext 目录下
拷贝librxtxSerial.so 文件到 /jre/lib/[machine type] (i386 for instance)目录下
并将拷贝文件释放权限给所有用户

Solaris (sparc only so far)

拷贝RXTXcomm.jar 文件到 /jre/lib/ext 目录下
拷贝librxtxSerial.so 文件到 /jre/lib/[machine type]目录下
并将拷贝文件释放权限给所有用户

环境搭建好后开始写代码实现

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TooManyListenersException;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class SerialComm implements SerialPortEventListener, Runnable
{
        public final static String PORT_OWER = "MonitorApp";

        private boolean isOpen;

        private boolean isStart;

        private boolean isSave;

        private boolean isPrint;

        private Thread readThread;

        private String portName;

        private String portAddress;

        private CommPortIdentifier portId;

        private SerialPort serialPort;

        private DataInputStream inputStream;

        private OutputStream outputStream;

        private SimpleDateFormat formatter;

        // prase data with process
        private String dataProtocol;

        private Object readWriteLock = new Object();


        public SerialComm() {
                isOpen = false;
                isStart = false;
                isSave = true;
                isPrint = false;
                formatter = new SimpleDateFormat("[yyyy-MM-dd hh:mm:ss,SSS]");

                portName = "COM1";
                portAddress = "LOCAL";
                dataProtocol = "Gooseli";
        }

        public void init(String port, String protocol) throws Exception
        {
                portName = port;
                portAddress = portName;
                dataProtocol = protocol;

                init();
        }

        public void init(String port, String address, String protocol) throws Exception
        {
                portName = port;
                portAddress = address;
                dataProtocol = protocol;

                init();
        }

        public void init() throws IOException, Exception, Exception
        {
                if (isOpen)
                {
                        close();
                }

                try
                {
                        //传送串口名创建CommPortIdentifier对象服务。
                        portId = CommPortIdentifier.getPortIdentifier(portName);

                        //使用portId对象服务打开串口,并获得串口对象
                        serialPort = (SerialPort) portId.open(PORT_OWER, 2000);

                        //通过串口对象获得读串口流对象
                        inputStream = new DataInputStream(serialPort.getInputStream());

                        //通过串口对象获得写串口流对象
                        outputStream = serialPort.getOutputStream();

                        isOpen = true;
                } catch (NoSuchPortException ex)
                {
                        throw new Exception(ex.toString());
                } catch (PortInUseException ex)
                {
                        throw new Exception(ex.toString());
                }
        }

        public void start() throws Exception
        {
                if (!isOpen)
                {
                        throw new Exception(portName + " has not been opened.");
                }

                try
                {
                        //创建对象线程
                        readThread = new Thread(this);
                        readThread.start();

                        //设置串口数据时间有效
                        serialPort.notifyOnDataAvailable(true);

                        //增加监听
                        serialPort.addEventListener(this);

                        isStart = true;

                } catch (TooManyListenersException ex)
                {
                        throw new Exception(ex.toString());
                }
        }

        public void run()
        {
                String at = "at^hcmgr=1\r";

                String strTemp = at + (char) Integer.parseInt("1a", 16) + "z";

                writeComm(strTemp);
                isPrint = true;
        }

        public void stop()
        {
                if (isStart)
                {
                        serialPort.notifyOnDataAvailable(false);
                        serialPort.removeEventListener();

                        isStart = false;
                }
        }

        public void close()
        {
                stop();

                if (isOpen)
                {
                        try
                        {
                                inputStream.close();
                                outputStream.close();
                                serialPort.close();

                                isOpen = false;
                        } catch (IOException ex)
                        {
                        }
                }
        }

        //如果串口有数据上报则主动调用此方法
        public void serialEvent(SerialPortEvent event)
        {
                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:
                        readComm();
                        break;
                default:
                        break;
                }
        }

        public void readComm()
        {
                StringBuffer readBuffer = new StringBuffer();
                String scannedInput = "";
                Date currentTime = null;
                String TimeStamp = "";
                int c;
                char a;
                try
                {
                        InputStreamReader fis = new InputStreamReader(inputStream, "utf-8");
                        while ((c = fis.read()) != -1)
                        {
                                readBuffer.append((char) c);
                        }
                        scannedInput = readBuffer.toString().trim();
                        currentTime = new Date();

                        TimeStamp = formatter.format(currentTime);

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

                } catch (Exception ex)
                {

                        ex.printStackTrace();
                }

        }

        public void writeComm(String outString)
        {
                synchronized (readWriteLock)
                {
                        try
                        {
                                outputStream.write(outString.getBytes());
                        } catch (IOException ex)
                        {

                        }
                }
        }

        public static void main(String[] args)
        {
                SerialComm serialcomm = new SerialComm();

                try
                {
                        serialcomm.init("COM3", "Air");// windows下测试端口
                       
                        // serialcomm.init("/dev/ttyUSB0", "Air");//linux下测试端口
                        serialcomm.start();
                } catch (Exception ex)
                {
                }
        }

}
并口呢,三方程序,你不出钱那有这么容易,看别人的开源,支持多系统
if (this.osName.toLowerCase().indexOf("windows") != -1)
      {
        localObject2 = new String[259];
        for (i = 1; i <= 256; ++i)
        {
          localObject2[(i - 1)] = new String("COM" + i);
        }
        for (i = 1; i <= 3; ++i)
        {
          localObject2[(i + 255)] = new String("LPT" + i);
        }
        localObject1 = localObject2;
      }
      else if ((this.osName.equals("Solaris")) || (this.osName.equals("SunOS")))
      {
        localObject2 = new String[2];
        i = 0;
        File localFile = null;

        localFile = new File("/dev/term");
        if (localFile.list().length > 0);
        localObject2[(i++)] = new String("term/");

        String[] arrayOfString2 = new String;
        for (--i; i >= 0; --i)
          arrayOfString2 = localObject2;
        localObject1 = arrayOfString2;
      }
      else
      {
        localObject2 = new File(this.deviceDirectory);
        arrayOfString1 = ((File)localObject2).list();
        localObject1 = arrayOfString1; }
    }
    if (localObject1 == null)
    {
      return;
    }

    Object localObject2 = new String[0];
    switch (paramInt)
    {
    case 1:
      if (this.osName.equals("Linux"))
      {
        arrayOfString1 = { "ttyS", "ttySA", "ttyUSB" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("Linux-all-ports"))
      {
        arrayOfString1 = { "comx", "holter", "modem", "rfcomm", "ttyircomm", "ttycosa0c", "ttycosa1c", "ttyC", "ttyCH", "ttyD", "ttyE", "ttyF", "ttyH", "ttyI", "ttyL", "ttyM", "ttyMX", "ttyP", "ttyR", "ttyS", "ttySI", "ttySR", "ttyT", "ttyUSB", "ttyV", "ttyW", "ttyX" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.toLowerCase().indexOf("qnx") != -1)
      {
        arrayOfString1 = { "ser" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("Irix"))
      {
        arrayOfString1 = { "ttyc", "ttyd", "ttyf", "ttym", "ttyq", "tty4d", "tty4f", "midi", "us" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("FreeBSD"))
      {
        arrayOfString1 = { "ttyd", "cuaa", "ttyA", "cuaA", "ttyD", "cuaD", "ttyE", "cuaE", "ttyF", "cuaF", "ttyR", "cuaR", "stl" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("NetBSD"))
      {
        arrayOfString1 = { "tty0" };

        localObject2 = arrayOfString1;
      }
      else if ((this.osName.equals("Solaris")) || (this.osName.equals("SunOS")))
      {
        arrayOfString1 = { "term/", "cua/" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("HP-UX"))
      {
        arrayOfString1 = { "tty0p", "tty1p" };

        localObject2 = arrayOfString1;
      }
      else if ((this.osName.equals("UnixWare")) || (this.osName.equals("OpenUNIX")))
      {
        arrayOfString1 = { "tty00s", "tty01s", "tty02s", "tty03s" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("OpenServer"))
      {
        arrayOfString1 = { "tty1A", "tty2A", "tty3A", "tty4A", "tty5A", "tty6A", "tty7A", "tty8A", "tty9A", "tty10A", "tty11A", "tty12A", "tty13A", "tty14A", "tty15A", "tty16A", "ttyu1A", "ttyu2A", "ttyu3A", "ttyu4A", "ttyu5A", "ttyu6A", "ttyu7A", "ttyu8A", "ttyu9A", "ttyu10A", "ttyu11A", "ttyu12A", "ttyu13A", "ttyu14A", "ttyu15A", "ttyu16A" };

        localObject2 = arrayOfString1;
      }
      else if ((this.osName.equals("Compaq's Digital UNIX")) || (this.osName.equals("OSF1")))
      {
        arrayOfString1 = { "tty0" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("BeOS"))
      {
        arrayOfString1 = { "serial" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("Mac OS X"))
      {
        arrayOfString1 = { "cu.KeyUSA28X191.", "tty.KeyUSA28X191.", "cu.KeyUSA28X181.", "tty.KeyUSA28X181.", "cu.KeyUSA19181.", "tty.KeyUSA19181." };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.toLowerCase().indexOf("windows") != -1)
      {
        arrayOfString1 = { "COM" };

        localObject2 = arrayOfString1; }
      break;
    case 2:
      if (this.osName.equals("Linux"))
      {
        arrayOfString1 = { "lp" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.equals("FreeBSD"))
      {
        arrayOfString1 = { "lpt" };

        localObject2 = arrayOfString1;
      }
      else if (this.osName.toLowerCase().indexOf("windows") != -1)
      {
        arrayOfString1 = { "LPT" };

        localObject2 = arrayOfString1;
      }
这是咋了,lz要转技术型民工
有好东西当然要拿出来共享一下了
不怕你笑话,学了3年java,对底层的操作还是基础水平。
接触到的全是应用层的东西。

终于,我不用再寄希望于学校微薄的助学金了!

提示: 作者被禁止或删除 内容自动屏蔽
返回列表