JAVA serial programming

RXTX library implements serial programming JAVA

  • First, download the library RXTX corresponding resource file, the corresponding address http://fizzed.com/oss/rxtx-for-java

  • Windows 32-bit systems: mfz-rxtx-2.2-20081207-win-x86

  • Windows64 bit systems: mfz-rxtx-2.2-20081207-win-x64

  • Configuring dynamic link library
    - to copy rxtxSerial.dll% JAVA_HOME% \ jre \ bin
    - to copy rxtxParallel.dll% JAVA_HOME% \ jre \ bin

  • When java.lang.UnsatisfiedLinkError errors or class gnu.io under during operation throws can not find, copy rxtx extract the package rxtxParallel.dll, rxtxSerial.dll these two files to the C: \ Windows \ System32 directory to resolve the error


RXTXcomm.jar copy to the project

Here Insert Picture Description


Packaging category serial port parameters: SerialPortParameter

package com.ycom.serialport;

import gnu.io.SerialPort;

/**
 * 串口参数封装类
 * @author Administrator
 *
 */
public class SerialPortParameter {
	/**
     * 串口名称(COM1、COM2、COM3等等)
     */
    private String serialPortName;
    
    /**
     * 波特率
     * 默认:9600
     */
    private int baudRate;
    
    /**
     * 数据位 
     * 可以设置的值:SerialPort.DATABITS_5、SerialPort.DATABITS_6、SerialPort.DATABITS_7、SerialPort.DATABITS_8
     * 默认:SerialPort.DATABITS_8
     */
    private int dataBits;
    
    /**
     * 停止位
     * 可以设置的值:SerialPort.STOPBITS_1、SerialPort.STOPBITS_2、SerialPort.STOPBITS_1_5
     * 默认:SerialPort.STOPBITS_1
     */
    private int stopBits;
    
    /**
     * 校验位
     * 可以设置的值:SerialPort.PARITY_NONE、SerialPort.PARITY_ODD、SerialPort.PARITY_EVEN、SerialPort.PARITY_MARK、SerialPort.PARITY_SPACE
     * 默认:SerialPort.PARITY_NONE
     */
    private int parity;
    
    /**
     * 默认参数:
     *  波特率:9600
     * 	数据位:8位
     * 	停止位:1位
     * 	校    验:无
     * @param serialPortName 串口名称, "COM1"、"COM2"
     */
    public SerialPortParameter(String serialPortName) {
        this.serialPortName = serialPortName;
        this.baudRate = 9600;
        this.dataBits = SerialPort.DATABITS_8;
        this.stopBits = SerialPort.STOPBITS_1;
        this.parity = SerialPort.PARITY_NONE;
    }
    
    /**
     * 默认参数:
     * 	数据位:8位
     * 	停止位:1位
     * 	校    验:无
     * @param serialPortName 串口名称, "COM1"、"COM2"
     * @param baudRate 波特率
     */
    public SerialPortParameter(String serialPortName, int baudRate) {
        this.serialPortName = serialPortName;
        this.baudRate = baudRate;
        this.dataBits = SerialPort.DATABITS_8;
        this.stopBits = SerialPort.STOPBITS_1;
        this.parity = SerialPort.PARITY_NONE;
    }

	public String getSerialPortName() {
		return serialPortName;
	}

	public void setSerialPortName(String serialPortName) {
		this.serialPortName = serialPortName;
	}

	public int getBaudRate() {
		return baudRate;
	}

	public void setBaudRate(int baudRate) {
		this.baudRate = baudRate;
	}

	public int getDataBits() {
		return dataBits;
	}

	public void setDataBits(int dataBits) {
		this.dataBits = dataBits;
	}

	public int getStopBits() {
		return stopBits;
	}

	public void setStopBits(int stopBits) {
		this.stopBits = stopBits;
	}

	public int getParity() {
		return parity;
	}

	public void setParity(int parity) {
		this.parity = parity;
	}

	@Override
	public String toString() {
		return "SerialPortParameter [serialPortName=" + serialPortName
				+ ", baudRate=" + baudRate + ", dataBits=" + dataBits
				+ ", stopBits=" + stopBits + ", parity=" + parity + "]";
	}
}

Serial Packaging Tools: SerialPortUtil

package com.ycom.serialport;

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;

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

/**
 * 串口工具类
 * @author Administrator
 *
 */
public class SerialPortUtil {
	
	/**
	 * 获得系统可用的端口名称列表(COM1、COM2、COM3等等)
	 * @return List<String>可用端口名称列表
	 */
	public static List<String> getSerialPortList() {
        List<String> systemPorts = new ArrayList<>();
        //获得系统可用的端口
        @SuppressWarnings("unchecked")
		Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();//获得端口的名字
            systemPorts.add(portName);
        }
        return systemPorts;
    }
	
	/**
	 * 打开串口
	 * @param parameter 串口参数对象
	 * @param timeout 串口打开超时时间
	 * @return SerialPort串口对象
	 * @throws NoSuchPortException	对应串口不存在
	 * @throws PortInUseException	 串口在使用中
	 * @throws UnsupportedCommOperationException 不支持操作
	 */
	public static SerialPort openSerialPort(SerialPortParameter parameter,int timeout) 
			throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
		// 通过端口名称得到端口
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(parameter.getSerialPortName());
		// 打开端口,(自定义名字,打开超时时间)
		CommPort commPort = portIdentifier.open(parameter.getSerialPortName(), timeout);
		// 判断是不是串口
		if (commPort instanceof SerialPort) {
			SerialPort serialPort = (SerialPort) commPort;
			// 设置串口参数(波特率,数据位8,停止位1,校验位无)
			serialPort.setSerialPortParams(parameter.getBaudRate(),
					parameter.getDataBits(), parameter.getStopBits(), parameter.getParity());
			return serialPort;
		} else {
			// 是其他类型的端口
			throw new NoSuchPortException();
		}
	}
	
	/**
	 * 打开串口
	 * @param parameter 串口参数对象
	 * @return SerialPort串口对象
	 * @throws NoSuchPortException 	对应串口不存在
	 * @throws PortInUseException	串口在使用中
	 * @throws UnsupportedCommOperationException 不支持操作
	 */
	public static SerialPort openSerialPort(SerialPortParameter parameter)
            throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
        return openSerialPort(parameter, 2000);
    }
	
	/**
	 * 打开串口 	默认参数: 9600,8,1,N
	 * @param serialPortName 串口名称
	 * @return SerialPort串口对象
	 * @throws NoSuchPortException  对应串口不存在
	 * @throws PortInUseException	串口在使用中
	 * @throws UnsupportedCommOperationException 不支持操作
	 */
	public static SerialPort openSerialPort(String serialPortName)
            throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
        SerialPortParameter parameter = new SerialPortParameter(serialPortName);
        return openSerialPort(parameter);
    }
	
	/**
	 * 打开串口 	默认参数: 8,1,N
	 * @param serialPortName	串口名称
	 * @param baudRate			波特率
	 * @return	SerialPort串口对象
	 * @throws NoSuchPortException	对应串口不存在
	 * @throws PortInUseException	串口在使用中
	 * @throws UnsupportedCommOperationException 不支持操作
	 */
	public static SerialPort openSerialPort(String serialPortName, int baudRate)
			throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
		SerialPortParameter parameter = new SerialPortParameter(serialPortName, baudRate);
		return openSerialPort(parameter);
	}
	
	/**
	 * 打开串口 	默认参数: 8,1,N 
	 * @param serialPortName	串口名称
	 * @param baudRate			波特率
	 * @param timeout			串口打开超时时间
	 * @return					SerialPort串口对象
	 * @throws NoSuchPortException 	对应串口不存在
	 * @throws PortInUseException	串口在使用中
	 * @throws UnsupportedCommOperationException 不支持操作
	 */
	public static SerialPort openSerialPort(String serialPortName, int baudRate, int timeout)
			throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
		SerialPortParameter parameter = new SerialPortParameter(serialPortName, baudRate);
		return openSerialPort(parameter, timeout);
	}
	
	/**
	 * 关闭串口
	 * @param serialPort
	 */
	public static void closeSerialPort(SerialPort serialPort) {
		if (serialPort != null) {
			serialPort.close();
			serialPort = null;
		}
	}
	
	/**
	 * 向串口发送数据
	 * @param serialPort 	串口对象
	 * @param data			发送的数据
	 */
	public static void sendData(SerialPort serialPort, byte[] data) {
        OutputStream os = null;
        try {
            //获得串口的输出流
            os = serialPort.getOutputStream();
            os.write(data);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
	
	/**
	 * 从串口读取数据
	 * @param serialPort  要读取的串口对象
	 * @return	读取的数据
	 */
	public static byte[] readData(SerialPort serialPort) {
		InputStream is = null;
		byte[] bytes = null;
		try {
			// 获得串口的输入流
			is = serialPort.getInputStream();
			// 获得数据长度
			int bufflenth = is.available();
			while (bufflenth != 0) {
				// 初始化byte数组
				bytes = new byte[bufflenth];
				is.read(bytes);
				bufflenth = is.available();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bytes;
	}
	
	/**
	 * 给串口设置监听
	 * @param serialPort  要读取的串口对象
	 * @param listener	SerialPortEventListener监听对象
	 * @throws TooManyListenersException 监听对象太多
	 */
	public static void setListenerToSerialPort(SerialPort serialPort,
			SerialPortEventListener listener) throws TooManyListenersException {
		// 给串口添加事件监听
		serialPort.addEventListener(listener);
		// 串口有数据监听
		serialPort.notifyOnDataAvailable(true);
		// 中断事件监听
		serialPort.notifyOnBreakInterrupt(true);
	}
}
Published 13 original articles · won praise 2 · Views 296

Guess you like

Origin blog.csdn.net/MOOG007/article/details/104800019