Java串口调试助手

建立工程

使用IDEA Gradle 建立工程,文件结构如下
Java串口调试助手_第1张图片

添加第三方依赖库

在build.gradle文件中添加rxtxcomm 依赖,如下:

plugins {
    id 'java'
}

group 'Demo'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    implementation 'org.bidib.jbidib.org.qbang.rxtx:rxtxcomm:2.2'
}

JavaFX 文件

SerialAssistant.fxml文件内容如下








<AnchorPane fx:id="anchorage" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="427.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SerialAssistant">
   <children>
      <TextArea fx:id="receiveText" layoutX="11.0" layoutY="14.0" prefHeight="285.0" prefWidth="579.0" />
       <TextArea fx:id="sendText" layoutX="11.0" layoutY="309.0" prefHeight="104.0" prefWidth="425.0" />
       <Button fx:id="sendBnt" layoutX="445.0" layoutY="387.0" mnemonicParsing="false" onAction="#onActionSendBtn" prefHeight="26.0" prefWidth="141.0" text="Send" />
       <Button fx:id="openBnt" layoutX="446.0" layoutY="348.0" mnemonicParsing="false" onAction="#onActionOpenBtn" prefHeight="26.0" prefWidth="141.0" text="Open" />
       <ComboBox fx:id="comboBox" layoutX="446.0" layoutY="309.0" onShown="#onShowComboBox" prefHeight="26.0" prefWidth="141.0" />
   children>
AnchorPane>

效果如如下
Java串口调试助手_第2张图片

串口通讯控制

文件名 SerialController.java

import gnu.io.*;

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;

public class SerialController {

    private SerialPort serialPort;

    /**
     * 获得系统可用端口的列表
     *
     * @return 可用的端口名称列表
     */
    @SuppressWarnings("unchecked")
    public static List<String> getSystemPort() {
        List<String> systemPorts = new ArrayList<>();
        //获得系统可用的端口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            systemPorts.add(portName);
        }
        System.out.println("系统可用端口列表: " + systemPorts);
        return systemPorts;
    }

    /**
     * 开启串口
     *
     * @param name     串口名称
     * @param baudRete 波特率
     * @return 串口对象
     */
    public boolean open(String name, int baudRete) {
        try {
            // 通过端口名称得到端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(name);
            // 打开端口  自定义名字,打开超时时间
            CommPort commPort = portIdentifier.open(name, 2222);
            // 判断是不是串口
            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                //设置串口参数(波特率,数据位8, 停止位1, 校验位无)
                serialPort.setSerialPortParams(baudRete, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                return true;
            } else {
                //是其他类型端口
                throw new NoSuchPortException();
            }
        } catch (UnsupportedCommOperationException | NoSuchPortException | PortInUseException e) {
            serialPort.close();
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 关闭串口
     */
    public void close() {
        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }

    /**
     * 向串口发送数据
     *
     * @param data 发送的数据
     */
    public void sendData(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();
                    os = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取串口数据
     *
     * @return 返回串口数据
     */
    public byte[] readData() {
        InputStream is = null;
        byte[] bytes = null;
        try {
            is = serialPort.getInputStream(); //获取输入流
            int bufflenth = is.available(); //获取数据长度
            while (bufflenth != 0) {
                bytes = new byte[bufflenth];
                int read = is.read(bytes);
                bufflenth = is.available();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    /**
     * 监听事件
     */
    public void setListenerToSerialPort(SerialPortEventListener listener) {
        try {
            //给串口添加事件监听
            serialPort.addEventListener(listener);
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
        serialPort.notifyOnDataAvailable(true);//串口有数据监听
        serialPort.notifyOnBreakInterrupt(true);//中断事件监听
    }
}

Ui 控制

文件名 SerialAssistant.java

import gnu.io.SerialPortEvent;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;

import java.util.List;

public class SerialAssistant {
    @FXML
    private TextArea receiveText;
    @FXML
    private TextArea sendText;
    @FXML
    private Button openBnt;
    @FXML
    private ComboBox<String> comboBox;

    private SerialController serialController;
    private List<String> systemPorts;
    private boolean isOpen = false;

    public SerialAssistant() {
        systemPorts = SerialController.getSystemPort();
        serialController = new SerialController();
    }

    /**
     * 点击commbox,刷新里面的数据
     */
    public void onShowComboBox(Event event) {
        comboBox.getItems().clear();
        comboBox.getItems().addAll(systemPorts);
    }

    /**
     * 打开串口
     */
    public void onActionOpenBtn(ActionEvent actionEvent) {
        if (!isOpen) {
            if (!serialController.open(comboBox.getValue(), 115200)) {
                return;
            }
            serialController.setListenerToSerialPort(ev -> {
                if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                    receiveText.appendText( new String(serialController.readData()));
                }
            });
            isOpen = true;
            openBnt.setText("Close");
        } else {
            isOpen = false;
            serialController.close();
            openBnt.setText("Open");
        }
    }

    /**
     * 发送数据
     */
    public void onActionSendBtn(ActionEvent actionEvent) {
        serialController.sendData(sendText.getText().getBytes());
    }
}

程序入口

文件名 Main.java

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class Main extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Parent root = null;
        try {
            root = FXMLLoader.load(getClass().getResource("SerialAssistant.fxml"));
            primaryStage.setTitle("SerialAssistant");
            primaryStage.setScene(new Scene(root));
            primaryStage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

源码下载

你可能感兴趣的:(Java)