java SerialPort串口通讯的使用

api文档

http://fazecast.github.io/jSerialComm/javadoc/com/fazecast/jSerialComm/package-summary.html

 

 maven依赖

<!-- https://mvnrepository.com/artifact/com.fazecast/jSerialComm -->
<dependency>
    <groupId>com.fazecast</groupId>
    <artifactId>jSerialComm</artifactId>
    <!--<version>2.5.2</version>-->
    <version>[2.0.0,3.0.0)</version>
</dependency> 

基于事件的阅读用法示例

可供读取的数据示例

以下示例显示了使用此事件触发器的一种方法:

    SerialPort comPort = SerialPort.getCommPorts()[0];
    comPort.openPort();
    comPort.addDataListener(new SerialPortDataListener() {
        @Override
        public int getListeningEvents() { return SerialPort.LISTENING_EVENT_DATA_AVAILABLE; }
        @Override
        public void serialEvent(SerialPortEvent event)
        {
            if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
                return;
            byte[] newData = new byte[comPort.bytesAvailable()];
            int numRead = comPort.readBytes(newData, newData.length);
            System.out.println("Read " + numRead + " bytes.");
        }

    });

 

 非阻塞阅读用法示例

package com.bhu.utils;

import com.fazecast.jSerialComm.SerialPort;


public class SerialComm {

    /*public static void main(String[] args) throws InterruptedException {
        SerialComm serialComm = new SerialComm("COM3");
        serialComm.openPort();
        while (true) {
            byte[] bs = serialComm.writeAndRead("010300000002");
            Double[] d = Utils.analysisData(bs, 3, 5, 2);
            if (d != null) {
                for (Double a : d) {
                    System.out.println(a);
                }
            }

            Thread.sleep(1000);
        }
    }*/


    public SerialComm(String portDescriptor) {
        this.portDescriptor = portDescriptor;
    }

    public SerialComm(String portDescriptor, Integer baudRate) {
        this.portDescriptor = portDescriptor;
        this.baudRate = baudRate;
    }

    private String portDescriptor;
    private Integer baudRate;

    private SerialPort comPort;

    public boolean isOpen() {
        return comPort.isOpen();
    }

    /**
     * 打开串口
     *
     * @return 打开的状态
     */
    public boolean openPort() {
        return openPort(portDescriptor, baudRate);
    }

    /**
     * 打开串口
     *
     * @param portDescriptor COM口
     * @return 打开的状态
     */
    public boolean openPort(String portDescriptor) {
        return openPort(portDescriptor, null);
    }

    /**
     * 打开串口
     *
     * @param portDescriptor COM口
     * @param baudRate       波特率
     * @return 打开的状态
     */
    public boolean openPort(String portDescriptor, Integer baudRate) {
        comPort = SerialPort.getCommPort(portDescriptor);
        if (baudRate != null) {
            comPort.setBaudRate(baudRate);
        }
        if (!comPort.isOpen()) {
            return comPort.openPort();
        } else {
            return true;
        }
    }


    /**
     * 关闭串口
     *
     * @return
     */
    public boolean closePort() {
        if (comPort != null && comPort.isOpen()) {
            return comPort.closePort();
        }
        return true;
    }

    /**
     * 向com口发送数据并且读取数据
     */
    public byte[] writeAndRead(String instruct) {
        byte[] reslutData = null;
        try {
            if (!comPort.isOpen()) throw new BhudyException(BhudyExceptionCode.CODE_18);

            int numWrite = comPort.writeBytes(Utils.getCRC(instruct), Utils.getCRC(instruct).length);
            if (numWrite > 0) {
                int i = 0;
                while (comPort.bytesAvailable() > 0 && i++ < 5) Thread.sleep(20);
                byte[] readBuffer = new byte[comPort.bytesAvailable()];
                int numRead = comPort.readBytes(readBuffer, readBuffer.length);
                if (numRead > 0) {
                    reslutData = readBuffer;
                }
            }
        } catch (InterruptedException e) {
            throw new BhudyException(e.getMessage());
        }
        return reslutData;
    }

}
 
posted @ 2019-11-27 14:39  变红叶  阅读(2722)  评论(0编辑  收藏  举报