diff --git a/src/main/java/com/xydl/cac/serialport/SerialPortServer.java b/src/main/java/com/xydl/cac/serialport/SerialPortServer.java index 1fbd079..795f1f2 100644 --- a/src/main/java/com/xydl/cac/serialport/SerialPortServer.java +++ b/src/main/java/com/xydl/cac/serialport/SerialPortServer.java @@ -7,8 +7,10 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; +import javax.annotation.PreDestroy; import java.util.ArrayList; import java.util.Arrays; +import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; @@ -16,8 +18,6 @@ import java.util.regex.Pattern; @Slf4j public class SerialPortServer { - @Value("${cac.warnport.name}") - public String warnportname; @Value("${cac.warnport.intervaltime:60}") public Integer intervaltime; @Value("${cac.warnport.warntime:5}") @@ -27,6 +27,9 @@ public class SerialPortServer { public long LastWarningTime;//最后一次硬接点告警时间 public boolean started = false; + byte[] openbuffer = new byte[]{00, (byte) 0xf1, (byte) 0xff};//发送串口告警 + byte[] stopbuffer = new byte[]{00, (byte) 0x01, (byte) 0xff};//关闭串口告警 + public void discoverSerialPort() { if (currentPort == null) { List serialPortList = new ArrayList<>(); @@ -35,25 +38,25 @@ public class SerialPortServer { serialPortList = Arrays.asList(commPorts); for (SerialPort port : serialPortList) { log.info("获取串口: " + port.getSystemPortName()); - Pattern pattern = Pattern.compile("ttyCH341."); String systemPortName = port.getSystemPortName(); if (systemPortName != null) { - if (pattern.matcher(systemPortName).matches()) { + if (systemPortName.startsWith("ttyCH341")) { currentPort = port; log.info("获取到硬接点告警串口: " + port.getSystemPortName()); } } } - } else { - log.error("未获取到硬接点告警串口!"); } + } else { + log.error("硬接点串口存在!"); } + } public void closeSerialPort() { if (currentPort != null) { - SerialPort port = currentPort; - port.closePort(); + log.info("断开串口成功!"); + currentPort.closePort(); } else { log.error("断开串口失败,没有对应的硬接点告警串口!"); } @@ -66,8 +69,6 @@ public class SerialPortServer { if (!started) { started = true; if (openSerialPort()) { - byte[] openbuffer = new byte[]{00, (byte) 0xf1, (byte) 0xff};//发送串口告警 - byte[] stopbuffer = new byte[]{00, (byte) 0x01, (byte) 0xff};//关闭串口告警 SerialPort port = currentPort; if (port != null) { long l = System.currentTimeMillis(); @@ -82,13 +83,11 @@ public class SerialPortServer { LastWarningTime = l; port.writeBytes(openbuffer, openbuffer.length); int seconds = 0; - while (StaticVariable.shutdown == 0 && seconds > warntime) { + while (StaticVariable.shutdown == 0 && seconds < warntime) { try { Thread.sleep(1000); seconds++; } catch (Exception ignore) { - port.writeBytes(stopbuffer, stopbuffer.length); - started = false; } } port.writeBytes(stopbuffer, stopbuffer.length); @@ -138,4 +137,9 @@ public class SerialPortServer { } } + @PreDestroy + private void stop() { + closeSerialPort(); + } + }