JAvaシリアル通信

6965 ワード

依存:rxtxcomm.jar
プラットフォーム以来のドライバをjavahome libの下に関連する位置に事前に置く必要があります.ダウンロードアドレス 配置位置パッケージの解凍後にinstall.txt内に紹介があります.
 
JAva実装コード
package comm;

import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import gnu.io.*;

public class ContinueRead extends Thread implements SerialPortEventListener { // SerialPortEventListener
    //    ,                   
    static CommPortIdentifier portId; //        
    static Enumeration> portList; //            
    InputStream inputStream; //         
    static OutputStream outputStream;//        
    static SerialPort serialPort; //      
    //              
    private BlockingQueue msgQueue = new LinkedBlockingQueue();

    @Override
    /**
     * SerialPort EventListene    ,             
     */
    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://            
            byte[] readBuffer = new byte[20];
            try {
                int numBytes = -1;
                while (inputStream.available() > 0) {
                    numBytes = inputStream.read(readBuffer);

                    if (numBytes > 0) {
                        msgQueue.add(new Date() + "        :-----"
                                + new String(readBuffer));
                        readBuffer = new byte[20];//         ,                
                    } else {
                        msgQueue.add(" ------      ");
                    }
                }
            } catch (IOException e) {
            }
            break;
        }
    }

    /**
     * 
     *       COM4  ,            
     * 
     * @return   1         ,   0        
     */
    public int startComPort() {
        //                      
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {

            //         
            portId = (CommPortIdentifier) portList.nextElement();

            System.out.println("    :--->" + portId.getPortType());
            System.out.println("    :---->" + portId.getName());
            //            
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                //     COM4    ,      
                if (portId.getName().equals("COM4")) {
                    try {
                        //        COM_4(    ),   2  
                        serialPort = (SerialPort) portId.open("COM_4", 2000);

                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    //             
                    try {
                        inputStream = serialPort.getInputStream();
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    //             
                    try {
                        serialPort.addEventListener(this);
                    } catch (TooManyListenersException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    //        , :       
                    serialPort.notifyOnDataAvailable(true);

                    //            
                    try {
                        //    、   、   、     
                        serialPort.setSerialPortParams(9600,
                                SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {
                        e.printStackTrace();
                        return 0;
                    }

                    return 1;
                }
            }
        }
        return 0;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            System.out.println("--------------         --------------");
            while (true) {
                //                 
                if (msgQueue.size() > 0) {
                    System.out.println(msgQueue.take());
                    //             。
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ContinueRead cRead = new ContinueRead();
        int i = cRead.startComPort();
        if (i == 1) {
            //             
            cRead.start();
            try {
                String st = "  ----  ";
                System.out.println("     :" + st.getBytes("gbk").length);
                outputStream.write(st.getBytes("gbk"), 0,
                        st.getBytes("gbk").length);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            return;
        }
    }
}

 
16進bytes配列を付けて16進文字列を回転するツールクラス
package com.dahuatech.bjtrack.ytbjtimesynchronizer.util;

public class ByteArrayHexUtil {

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    //       16      
    public static String byteToHexString(byte b) {
        return getByteToHexHighString(b) + getByteToHexLowString(b);
    }

    //         16          
    public static String getByteToHexHighString(byte b) {
        int n = b;
        if (n < 0){
            n += 256;
        }
        int d1 = n / 16; //   4 
        return hexDigits[d1];
    }

    //         16          
    public static String getByteToHexLowString(byte b) {
        int n = b;
        if (n < 0){
            n += 256;
        }
        int d2 = n % 16; //   4 
        return hexDigits[d2];
    }

    //        16     
    public static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));
        return resultSb.toString();
    }

}