Browse Source

add:com口读取工具

master
zhangzq 3 weeks ago
parent
commit
6dae0474c0
  1. 74
      acs/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ComPortUtil.java

74
acs/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ComPortUtil.java

@ -0,0 +1,74 @@
package org.nl.common.utils;
import com.fazecast.jSerialComm.SerialPort;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import java.util.function.Function;
@Service
@ConditionalOnProperty(prefix = "comPort",name = "need")
public class ComPortUtil {
private static SerialPort serialPort;
@Value("${comPort.name}")
private String cname;
@Value("${comPort.newBaudRate}")
private static int newBaudRate;
@Value("${comPort.newDataBits}")
private static int newDataBits;
@Value("${comPort.newStopBits}")
private static int newStopBits;
@Value("${comPort.newParity}")
private static int newParity;
public ComPortUtil() {
SerialPort[] commPorts = SerialPort.getCommPorts();
if (commPorts ==null || commPorts.length < 1 || StringUtils.isEmpty(cname)){
throw new RuntimeException("项目启动失败:无法识别com口信息");
}
for (SerialPort commPort : commPorts) {
if (commPort.getSystemPortName().equals(cname)){
serialPort = commPort;
}
throw new RuntimeException("项目启动失败:没有找到对应com口");
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("---项目停机执行关闭逻辑---");
this.doDestroy();
}));
}
private static void readComMsg(Function function){
if (serialPort!=null){
try {
serialPort.openPort();// 打开串口
serialPort.setComPortParameters(newBaudRate, newDataBits, newStopBits, newParity);// 设置串口参数
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
byte[] buffer = new byte[1024];
while (serialPort.isOpen()){
Thread.sleep(500);
int bytesRead = serialPort.readBytes(buffer, buffer.length);
if (bytesRead > 0) {
String msg = new String(buffer, 0, bytesRead);
System.out.println("--获取COM口信息--"+msg);
function.apply(msg);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (serialPort!=null && serialPort.isOpen()) {
serialPort.closePort();// 关闭串口
}
}
}
}
private void doDestroy(){
if (serialPort!=null && serialPort.isOpen()) {
serialPort.closePort();// 关闭串口
}
}
}
Loading…
Cancel
Save