注意!注意!注意!开箱即用,无需过度的配置,开箱即用,此处用接口调用的方式获取,需要处理为推送的请自行进行数据推送
xml引入依赖包 jSerialComm
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>2.10.4</version>
</dependency>
创建 SerialPortListener 工具类
package org.example;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import lombok.extern.slf4j.Slf4j;
/**
* 串口监听
*/
@Slf4j
public class SerialPortListener implements SerialPortDataListener {
private DataAvailableListener mDataAvailableListener;
public SerialPortListener(DataAvailableListener mDataAvailableListener) {
this.mDataAvailableListener = mDataAvailableListener;
}
@Override
public int getListeningEvents() {//必须是return这个才会开启串口工具的监听
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
}
public void serialEvent(SerialPortEvent serialPortEvent) {
if (mDataAvailableListener != null) {
mDataAvailableListener.dataAvailable();
}
}
}
创建 SerialPortManager 工具类
package org.example;
import com.fazecast.jSerialComm.SerialPort;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class SerialPortManager {
//查找所有可用端口
public static List<String> findPorts() {
// 获得当前所有可用串口
SerialPort[] serialPorts = SerialPort.getCommPorts();
List<String> portNameList = new ArrayList<String>();
// 将可用串口名添加到List并返回该List
for (SerialPort serialPort : serialPorts) {
portNameList.add(serialPort.getSystemPortName());
}
//去重
portNameList = portNameList.stream().distinct().collect(Collectors.toList());
return portNameList;
}
/**
* 打开串口
*
* @param portName 端口名称
* @param baudRate 波特率
* @return 串口对象
*/
public static SerialPort openPort(String portName, Integer baudRate) {
SerialPort serialPort = SerialPort.getCommPort(portName);
if (baudRate != null) {
serialPort.setBaudRate(baudRate);
}
//开启串口
if (!serialPort.isOpen()) {
serialPort.openPort(1000);
} else {
return serialPort;
}
// 设置一下串口的波特率等参数
// 数据位:8
// 停止位:1
// 校验位:None
serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
serialPort.setComPortParameters(baudRate, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);
return serialPort;
}
/**
* 关闭串口
*
* @param serialPort 待关闭的串口对象
*/
public static void closePort(SerialPort serialPort) {
if (serialPort != null && serialPort.isOpen()) {
serialPort.closePort();
}
}
/**
* 往串口发送数据
*
* @param serialPort 串口对象
* @param content 待发送数据
*/
public static void sendToPort(SerialPort serialPort, byte[] content) {
if (!serialPort.isOpen()) {
return;
}
serialPort.writeBytes(content, content.length);
}
/**
* 从串口读取数据
*
* @param serialPort 当前已建立连接的SerialPort对象
* @return 读取到的数据
*/
public static byte[] readFromPort(SerialPort serialPort) {
byte[] reslutData = null;
try {
if (!serialPort.isOpen()) {
return null;
}
;
int i = 0;
while (serialPort.bytesAvailable() > 0 && i++ < 5) Thread.sleep(20);
byte[] readBuffer = new byte[serialPort.bytesAvailable()];
int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
if (numRead > 0) {
reslutData = readBuffer;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return reslutData;
}
/**
* 添加监听器
*
* @param serialPort 串口对象
* @param listener 串口存在有效数据监听
*/
public static void addListener(SerialPort serialPort, DataAvailableListener listener) {
try {
// 给串口添加监听器
serialPort.addDataListener(new SerialPortListener(listener));
} catch (Exception e) {
e.printStackTrace();
}
}
}
接口 interface DataAvailableListener
package org.example;
/**
* 串口存在有效数据监听
*/
public interface DataAvailableListener {
/**
* 串口存在有效数据
*/
void dataAvailable();
}
注意最最最重要的一点来了,调用实现
package org.example.controller;
import com.fazecast.jSerialComm.SerialPort;
import org.example.DataAvailableListener;
import org.example.SerialPortManager;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
@RestController
@RequestMapping("/weight")
@CrossOrigin(origins = "*")
public class WeightController {
private Integer integerValue = -1;
/**
* 获取重量
*/
@GetMapping("/getWeight")
public Integer getWeight() {
return integerValue;
}
@PostConstruct
public void start() {
SerialPort serialPort = SerialPortManager.openPort("COM1", 9600);
//给当前串口对象设置监听器
SerialPortManager.addListener(serialPort, new DataAvailableListener() {
@Override
public void dataAvailable() {
// 当前监听器监听到的串口返回数据 back
byte[] back = SerialPortManager.readFromPort(serialPort);
// Convert byte array to string
String receivedData = new String(back);
// 使用正则表达式提取数字部分
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\+(\\d{6})");
java.util.regex.Matcher matcher = pattern.matcher(receivedData);
// 查找匹配项
if (matcher.find()) {
// 提取匹配的数字部分
String numericPart = matcher.group(1);
// 转换为整数
integerValue = Integer.parseInt(numericPart);
// 打印整数值
System.out.println("Received integer value: " + integerValue);
} else {
System.out.println("No match found in the received data.");
}
}
});
//当前向串口发送的数据(模拟假数据)
// byte[] content = new byte[10];
//向当前串口发送数据
// SerialPortManager.sendToPort(serialPort,content);
}
}