java串口通信

实体

package com.hwd.campus.common.common.utils.http;

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_EVEN;
    }

    /**
     * 默认参数:
     * 	数据位: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 + "]";
    }
}

工具类

package com.hwd.campus.common.common.utils.http;

import gnu.io.*;

import javax.xml.bind.DatatypeConverter;
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 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 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 void setListenerToSerialPort(SerialPort serialPort,
                                               SerialPortEventListener listener) throws TooManyListenersException {
        // 给串口添加事件监听
        serialPort.addEventListener(listener);
        // 串口有数据监听
        serialPort.notifyOnDataAvailable(true);
        // 中断事件监听
        serialPort.notifyOnBreakInterrupt(true);
    }
    private static byte charToByte(char c)
    {
        return (byte) "0123456789abcdef".indexOf(c);
    }

    public static byte[] hexStringToBytes(String hexString)

    {

        hexString = hexString.toLowerCase();

        String[] hexStrings = hexString.split(" ");

        byte[] bytes = new byte[hexString.length()];
        for (int i = 0; i < hexStrings.length; i++)
        {
            char[] hexChars = hexStrings[i].toCharArray();
            bytes[i] = (byte) (charToByte(hexChars[0]) << 4 | charToByte(hexChars[1]));
        }
        System.out.println("byte1"+bytes);
        return bytes;

    }

    public static void main(String[] args) {
        try {
            SerialPortUtil serialPortUtil = new SerialPortUtil();
            List<String> portList = SerialPortUtil.getSerialPortList();
            System.out.println(portList);
            SerialPort serialPort = serialPortUtil.openSerialPort("COM3");
            String s = "FEFEFE6822081300963168110433333433B616";
            byte[] bytes1 = hexStringToBytes(s);

            serialPortUtil.sendData(serialPort, bytes1);// 发送数据
            System.out.println( new String(bytes1)+"发送成功");
            // 设置串口的listener,用来监听串口是否有数据达到:回调方法中接收串口数据
            serialPortUtil.setListenerToSerialPort(serialPort, new SerialPortEventListener() {
                @Override
                public void serialEvent(SerialPortEvent event) {
                    if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {// 数据通知
                        System.out.println("aaa");
                        // 接受数据
                        byte[] bytes = SerialPortUtil.readData(serialPort);
                        System.out.println("收到的数据长度:" + bytes.length);
                        String s1 = DatatypeConverter.printHexBinary(bytes);
                        System.out.println("收到的数据:" + new String(s1));
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
posted @ 2023-06-12 08:39  小侯学编程  阅读(176)  评论(0)    收藏  举报