JAvaシリアル通信コード

14585 ワード

以下は私自身が実現したシリアル受信のクラスで、シリアル送信は比較的簡単で、直接送信すればいいです.次のクラスは直接使用できます.
 
package com.boomdts.weather_monitor.util;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;
import com.boomdts.weather_monitor.biz.RecvCommand;
import com.boomdts.weather_monitor.util.SysLog;
/*
     
*/
public class SerialComm {
    private int ibaudRate;
    private String scomPort;
    private CommPortIdentifier portId = null;
    //       
    private InputStream inStream ;
    //       
    private OutputStream outStream ;
    private SerialPort serialPort;
    public SerialComm(int ibaudRate, String scomPort) {
        this.ibaudRate = ibaudRate;
        this.scomPort = scomPort;
        try {
            Enumeration portList = CommPortIdentifier.getPortIdentifiers();
            while (portList.hasMoreElements())
            {
                portId = (CommPortIdentifier) portList.nextElement();
                //              
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    //   COM1       
                    System.out.println("portId = " + portId.getName());
                    if(portId.getName().equals(scomPort)){
                        break;
                    }else{
                        portId=null;
                    }
                }
            }
            //          1000ms
            SerialPort serialPort = (SerialPort)portId.open("Serial_Communication", 1000);
            //       38400,   8 ,   1 ,     
            serialPort.setSerialPortParams(ibaudRate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
            //          port   。
            //  port          ,commListener         
            serialPort.addEventListener(new CommListener(serialPort));
            //
            serialPort.notifyOnDataAvailable(true);
             // Set notifyOnBreakInterrup to allow event driven break handling.
            serialPort.notifyOnBreakInterrupt(true);
             // Set receive timeout to allow breaking out of polling loop during  input handling.
            serialPort.enableReceiveTimeout(30);
            //       
            OutputStream outStream = new BufferedOutputStream(serialPort.getOutputStream());
            //new ReceiveThread(inStream).start();
            //new SendThread(outStream).start();
        }  catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
        } catch (PortInUseException e) {
            e.printStackTrace();
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
        SysLog.logger.info("      !");
    }
}
//     ,   javax.comm.SerialPortEventListener;
class CommListener implements SerialPortEventListener {
    private StringBuffer linkWgt ;//       
    private String sCommand ;//     
    private SerialPort serialPort ;
    private InputStream inStream ;
    private RecvCommand recvCommand;
    public CommListener(SerialPort serialPort){
        recvCommand = new RecvCommand();
        linkWgt = new StringBuffer();
        sCommand = new String();
        this.serialPort = serialPort;
        try {
        //       
        this.inStream = new BufferedInputStream(serialPort.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //      
    public void serialEvent(SerialPortEvent e){
        int newData = 0;
        byte bRead[] = {0};
        String sSubStr = "";
        // Determine type of event.
        switch (e.getEventType()) {
        // Read data until -1 is returned. If \r is received substitute
            // 
for correct newline handling.
case SerialPortEvent.DATA_AVAILABLE: while (newData != -1) { try { //inStream = serialPort.getInputStream(); newData = inStream.read(); if (newData == -1) { break; } if ('\r' == (char)newData) { } else { // 0~255 int 16 sSubStr = Integer.toHexString((newData & 0x000000FF) | 0xFFFFFF00).substring(6); //System.out.println(sSubStr); linkWgt.append(sSubStr); } } catch (IOException ex) { System.err.println(ex); return; } } try{ System.out.println("linkWgt ----start-----" + linkWgt.toString() + "----end-----"); while(linkWgt.indexOf("a55a") != -1) { linkWgt.delete(0,linkWgt.indexOf("a55a")); if(linkWgt.indexOf("9191910000") == -1) { System.out.println(" !" + linkWgt); } else { sCommand =linkWgt.substring(0, linkWgt.indexOf("9191910000")); linkWgt.delete(0,linkWgt.indexOf("9191910000")); System.out.println("sCommand ----start-----" + sCommand + "----end-----"); recvCommand.analyze(sCommand); } } }catch(Exception ew){ ew.printStackTrace(); }finally{ } break; // If break event append BREAK RECEIVED message. case SerialPortEvent.BI: System.out.println("
--- BREAK RECEIVED ---
"); } } }