SerialTest/src/sample/Controller.java

99 lines
2.9 KiB
Java

package sample;
import gnu.io.SerialPort;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import sample.utils.*;
import java.util.ArrayList;
public class Controller {
@FXML
Button writeButton;
@FXML
TextArea readTextarea;
@FXML
TextArea writeTextarea;
@FXML
TextField comName;
// 串口
SerialPort port = null;
/** 开启串口
*
*/
@FXML
public void startCom() {
if(port != null){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "串口已经打开:" + port.getName());
alert.show();
return;
}
ArrayList<String> findPorts = SerialTool.findPort();
if(findPorts.isEmpty()){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "未找到串口信息!");
alert.show();
return;
}
String portName = findPorts.get(0);//默认打开第一个串口
// 设置使用的串口
comName.setText(portName);
try {
port = SerialTool.openPort(portName, 9600);//打开串口
} catch (RuntimeException e){
Alert alert = new Alert(Alert.AlertType.ERROR, e.getMessage());
alert.show();
return;
}
SerialTool.addListener(port, () -> {
byte[] data = null;
try {
if (port == null) {
System.out.println("串口对象为空,监听失败!");
} else {
// 读取串口数据
data = SerialTool.readFromPort(port);
String resultHEX = SerialTool.byteArrayToHexString(data);
readTextarea.setText(resultHEX);
}
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR, "发生了一个异常:".concat(e.getMessage()));
alert.show();
}
});
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "串口开启成功!");
alert.show();
}
/** 写入串口数据
*
*/
@FXML
public void writeCom() {
if(port == null){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "请先开启串口!");
alert.show();
return;
}
String content = writeTextarea.getText();
if(content == null || content.trim().length() <=0){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "请填写写入的数据!");
alert.show();
return;
}
//设定发送字符串
byte[] bs = SerialTool.hex2Bytes(content);
SerialTool.sendToPort(port, bs);//写入,写入应该在监听器打开之后而不是之前
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "写入成功!");
alert.show();
}
}