Java連接串口代碼

類庫和實例程序下載

https://download.csdn.net/download/TaiJi1985/12538399

代碼

import java.util.ArrayList;

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

public class DemoSP {
	public static void main(String[] args) throws Exception {
		ArrayList<String> ret = SerialPortUtil.findPort();
		for(String string : ret){
			System.out.println(string);
		}
		
		
		SerialPort p1 = SerialPortUtil.openPort("COM1", 9600, 8, 0, 1);
		
		SerialPortUtil.sendToPort(p1, "hello".getBytes());
		SerialPortUtil.addListener(p1, new SerialPortEventListener() {
			
			@Override
			public void serialEvent(SerialPortEvent e) {
				System.out.println(e.getEventType());
				if(SerialPortEvent.DATA_AVAILABLE != e.getEventType())return;
				try {
					byte[] a = SerialPortUtil.readFromPort(p1);
					System.out.println(new String(a));
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
			}
		});
	}
}

下面這個類庫是從互聯網獲取的幫助類

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

/**
 * 模塊名稱:projects-parent com.yotrio.common
 * 功能說明:串口服務類,提供打開、關閉串口,讀取、發送串口數據等服務(採用單例設計模式)
 * <br>
 * 開發人員:Wangyq 
 * 創建時間: 2018-09-20 10:05
 * 系統版本:1.0.0
 **/

public class SerialPortUtil {

    private static SerialPortUtil serialPortUtil = null;

    static {
        //在該類被ClassLoader加載時就初始化一個SerialTool對象
        if (serialPortUtil == null) {
            serialPortUtil = new SerialPortUtil();
        }
    }

    //私有化SerialTool類的構造方法,不允許其他類生成SerialTool對象
    private SerialPortUtil() {
    }

    /**
     * 獲取提供服務的SerialTool對象
     *
     * @return serialPortUtil
     */
    public static SerialPortUtil getSerialPortUtil() {
        if (serialPortUtil == null) {
            serialPortUtil = new SerialPortUtil();
        }
        return serialPortUtil;
    }


    /**
     * 查找所有可用端口
     *
     * @return 可用端口名稱列表
     */
    public static final ArrayList<String> findPort() {
        //獲得當前所有可用串口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();

        ArrayList<String> portNameList = new ArrayList<>();

        //將可用串口名添加到List並返回該List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }

        return portNameList;
    }

    /**
     * 打開串口
     *
     * @param portName 端口名稱
     * @param baudrate 波特率
     * @param databits 數據位
     * @param parity   校驗位(奇偶位)
     * @param stopbits 停止位
     * @return 串口對象
     * @throws SerialPortParameterFailure 設置串口參數失敗
     * @throws NotASerialPort             端口指向設備不是串口類型
     * @throws NoSuchPort                 沒有該端口對應的串口設備
     * @throws PortInUse                  端口已被佔用
     */
    public static final SerialPort openPort(String portName, int baudrate, int databits, int parity, int stopbits) throws Exception {

        try {
            //通過端口名識別端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);

            //打開端口,並給端口名字和一個timeout(打開操作的超時時間)
            CommPort commPort = portIdentifier.open(portName, 2000);

            //判斷是不是串口
            if (commPort instanceof SerialPort) {

                SerialPort serialPort = (SerialPort) commPort;
                try {
                    //設置一下串口的波特率等參數
                    serialPort.setSerialPortParams(baudrate, databits, stopbits, parity);
                } catch (UnsupportedCommOperationException e) {
                    throw new Exception("unsupported operation ");
                }

                //System.out.println("Open " + portName + " sucessfully !");
                return serialPort;
            } else {
                //不是串口
                throw new Exception("no port ");
            }
        } catch (NoSuchPortException e1) {
            throw new Exception("no such port ");
        } catch (PortInUseException e2) {
            throw new Exception(" port in use ");
        }
    }

    /**
     * 關閉串口
     *
     * @param serialPort 待關閉的串口對象
     */
    public static void closePort(SerialPort serialPort) {
        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }

    /**
     * 往串口發送數據
     *
     * @param serialPort 串口對象
     * @param order      待發送數據
     * @throws SendDataToSerialPortFailure        向串口發送數據失敗
     * @throws SerialPortOutputStreamCloseFailure 關閉串口對象的輸出流出錯
     */
    public static void sendToPort(SerialPort serialPort, byte[] order) throws Exception {
        OutputStream out = null;
        try {
            out = serialPort.getOutputStream();
            out.write(order);
            out.flush();
        } catch (IOException e) {
            throw new Exception("send fail");
        } finally {
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
               
            }
        }
    }

    /**
     * 從串口讀取數據
     *
     * @param serialPort 當前已建立連接的SerialPort對象
     * @return 讀取到的數據
     * @throws ReadDataFromSerialPortFailure     從串口讀取數據時出錯
     * @throws SerialPortInputStreamCloseFailure 關閉串口對象輸入流出錯
     */
    public static byte[] readFromPort(SerialPort serialPort) throws Exception {

        InputStream in = null;
        byte[] bytes = null;

        try {
            in = serialPort.getInputStream();
            int bufflenth = in.available();        //獲取buffer裏的數據長度

            while (bufflenth != 0) {
                bytes = new byte[bufflenth];    //初始化byte數組爲buffer中數據的長度
                in.read(bytes);
                bufflenth = in.available();
            }
        } catch (IOException e) {
            throw new Exception("read fail");
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (IOException e) {
            }
        }

        return bytes;

    }

    /**
     * 添加監聽器
     *
     * @param port     串口對象
     * @param listener 串口監聽器
     * @throws TooManyListeners 監聽類對象過多
     */
    public static void addListener(SerialPort port, SerialPortEventListener listener) throws Exception {

        try {
            //給串口添加監聽器
            port.addEventListener(listener);
            //設置當有數據到達時喚醒監聽接收線程
            port.notifyOnDataAvailable(true);
            //設置當通信中斷時喚醒中斷線程
            port.notifyOnBreakInterrupt(true);
        } catch (TooManyListenersException e) {
            throw new Exception("too many listeners");
        }
    }

    /**
     * 刪除監聽器
     *
     * @param port     串口對象
     * @param listener 串口監聽器
     * @throws TooManyListeners 監聽類對象過多
     */
    public static void removeListener(SerialPort port, SerialPortEventListener listener) {
        //刪除串口監聽器
        port.removeEventListener();
    }

}
···
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章