RXTXシリアル通信javaコード実装

7659 ワード

package com.runtrial.lms.rxtx;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

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

/**
 * @     :illegalsms
 * @     :SerialPort.java
 * @    :org.serial
 * @     :    
 * @     :
 */
public class DSerialPort implements Runnable, SerialPortEventListener {

    private String appName = "      [    2012]";
    private int timeout = 2000;// open         
    private int threadTime = 0;

    private CommPortIdentifier commPort;
    private SerialPort serialPort;
    private InputStream inputStream;
    private OutputStream outputStream;

    /**
     * @     :listPort
     * @     :         
     * @      :void
     */
    @SuppressWarnings("rawtypes")
    public void listPort() {
        CommPortIdentifier cpid;
        Enumeration en = CommPortIdentifier.getPortIdentifiers();

        System.out.println("now to list all Port of this PC:" + en);

        while (en.hasMoreElements()) {
            cpid = (CommPortIdentifier) en.nextElement();
            if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println(cpid.getName() + ", " + cpid.getCurrentOwner());
            }
        }
    }

    /**
     * @     :selectPort
     * @     :      ,  :COM1
     * @      :void
     * @param portName
     */
    @SuppressWarnings("rawtypes")
    public void selectPort(String portName) {

        this.commPort = null;
        CommPortIdentifier cpid;
        Enumeration en = CommPortIdentifier.getPortIdentifiers();

        while (en.hasMoreElements()) {
            cpid = (CommPortIdentifier) en.nextElement();
            if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL && cpid.getName().equals(portName)) {
                this.commPort = cpid;
                break;
            }
        }

        openPort();
    }

    /**
     * @     :openPort
     * @     :  SerialPort
     * @      :void
     */
    private void openPort() {
        if (commPort == null)
            log(String.format("       '%1$s'   !", commPort.getName()));
        else {
            log("      ,    :" + commPort.getName() + ",      SerialPort:");

            try {
                serialPort = (SerialPort) commPort.open(appName, timeout);
                log("   SerialPort   !");
            } catch (PortInUseException e) {
                throw new RuntimeException(String.format("  '%1$s'     !", commPort.getName()));
            }
        }
    }

    /**
     * @     :checkPort
     * @     :          
     * @      :void
     */
    private void checkPort() {
        if (commPort == null)
            throw new RuntimeException("      ,    " + "selectPort(String portName)       ");

        if (serialPort == null) {
            throw new RuntimeException("SerialPort     !");
        }
    }

    /**
     * @     :write
     * @     :       ,              ,   SerialPort    !
     * @      :void
     * @param message
     */
    public void write(String message) {
        checkPort();

        try {
            outputStream = new BufferedOutputStream(serialPort.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("     OutputStream  :" + e.getMessage());
        }

        try {
            outputStream.write(message.getBytes("GBK"), 0, message.getBytes("GBK").length);
            //outputStream.write(message.getBytes());
            log("      !"+new String(message.getBytes()));
        } catch (IOException e) {
            throw new RuntimeException("          :" + e.getMessage());
        } finally {
            try {
                outputStream.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * @     :startRead
     * @     :             
     * @      :void
     * @param time
     *                     ,    ,0       
     */
    public void startRead(int time) {
        checkPort();

        try {
            inputStream = new BufferedInputStream(serialPort.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException("     InputStream  :" + e.getMessage());
        }

        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) {
            throw new RuntimeException(e.getMessage());
        }

        serialPort.notifyOnDataAvailable(true);

        log(String.format("      '%1$s'   --------------", commPort.getName()));
        if (time > 0) {
            this.threadTime = time * 1000;
            Thread t = new Thread(this);
            t.start();
            log(String.format("      %1$d    。。。。", threadTime));
        }
    }

    /**
     * @     :close
     * @     :   SerialPort
     * @      :void
     */
    public void close() {
        serialPort.close();
        serialPort = null;
        commPort = null;
    }

    public void log(String msg) {
        System.out.println(appName + " --> " + msg);
    }

    /**
     *            
     */
    @Override
    public void serialEvent(SerialPortEvent arg0) {
        switch (arg0.getEventType()) {
        case SerialPortEvent.BI:/* Break interrupt,     */
        case SerialPortEvent.OE:/* Overrun error,     */
        case SerialPortEvent.FE:/* Framing error,     */
        case SerialPortEvent.PE:/* Parity error,     */
        case SerialPortEvent.CD:/* Carrier detect,     */
        case SerialPortEvent.CTS:/* Clear to send,     */
        case SerialPortEvent.DSR:/* Data set ready,       */
        case SerialPortEvent.RI:/* Ring indicator,     */
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*
                                                     * Output buffer is
                                                     * empty,       
                                                     */
            break;
        case SerialPortEvent.DATA_AVAILABLE:/*
                                             * Data available at the serial
                                             * port,       。      ,     
                                             */
            byte[] readBuffer = new byte[1024];
            String readStr = "";
            String s2 = "";

            try {

                while (inputStream.available() > 0) {
                    inputStream.read(readBuffer);
                    readStr += new String(readBuffer).trim();
                }

                s2 = new String(readBuffer).trim();

                log("         (   " + readStr.length() + "):" + readStr);
                log(s2);
            } catch (IOException e) {
            }
        }
    }

    @Override
    public void run() {
        try {
            Thread.sleep(threadTime);
            serialPort.close();
            log(String.format("  ''     !", commPort.getName()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  public static void main(String[] args) { 
      DSerialPort dp = new DSerialPort();
     dp.listPort();
     dp.selectPort("COM2");
     dp.write("     ");
     dp.startRead(30);

    
     }

}