|
@@ -21,10 +21,7 @@ import org.springframework.stereotype.Component;
|
|
|
import javax.annotation.Resource;
|
|
|
import java.util.ArrayList;
|
|
|
import java.util.HashMap;
|
|
|
-import java.util.concurrent.ExecutionException;
|
|
|
-import java.util.concurrent.Executors;
|
|
|
-import java.util.concurrent.ScheduledExecutorService;
|
|
|
-import java.util.concurrent.TimeUnit;
|
|
|
+import java.util.concurrent.*;
|
|
|
|
|
|
/**
|
|
|
* plc连接
|
|
@@ -57,6 +54,8 @@ public class PlcConnectServiceRunner implements CommandLineRunner {
|
|
|
|
|
|
private ArrayList<String> reTryPlc = new ArrayList<>();
|
|
|
|
|
|
+ private HashMap<String, ScheduledFuture<?>> heartbeatThreads = new HashMap<>();
|
|
|
+
|
|
|
/**
|
|
|
* 初始化
|
|
|
*/
|
|
@@ -70,6 +69,7 @@ public class PlcConnectServiceRunner implements CommandLineRunner {
|
|
|
if (s7PLC.checkConnected()){
|
|
|
plcToolsMap.put(plcConfig.getName(),s7PLC);
|
|
|
SpringUtil.getApplicationContext().publishEvent(new Device(plcConfig.getName(), "1"));
|
|
|
+ plcConnectsTheHeartbeat(plcConfig,s7PLC);
|
|
|
log.info("plc:{},ip:{},连接成功",plcConfig.getName(),plcConfig.getIp());
|
|
|
}
|
|
|
}catch (Exception e){
|
|
@@ -83,6 +83,10 @@ public class PlcConnectServiceRunner implements CommandLineRunner {
|
|
|
|
|
|
public void retry(PlcConfig plcConfig) {
|
|
|
reTryPlc.add(plcConfig.getName());
|
|
|
+ ScheduledFuture<?> scheduledFuture = heartbeatThreads.get(plcConfig.getName());
|
|
|
+ if (ObjectUtil.isNotNull(scheduledFuture)){
|
|
|
+ scheduledFuture.cancel(true);
|
|
|
+ }
|
|
|
threadPoolTaskExecutor.execute (() -> {
|
|
|
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
|
|
|
.retryIfResult(Boolean.FALSE::equals)
|
|
@@ -124,17 +128,18 @@ public class PlcConnectServiceRunner implements CommandLineRunner {
|
|
|
private void plcConnectsTheHeartbeat(PlcConfig plcConfig,S7PLC s7PLC){
|
|
|
String heartbeatAdd = plcConfig.getHeartbeat();
|
|
|
if (StringUtils.isNotEmpty(heartbeatAdd)){
|
|
|
- scheduledExecutorService.scheduleWithFixedDelay(()->{
|
|
|
- if (!reTryPlc.contains(plcConfig.getName())){
|
|
|
+ ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
|
|
|
+ if (!reTryPlc.contains(plcConfig.getName())) {
|
|
|
try {
|
|
|
s7PLC.readBoolean(plcConfig.getHeartbeat());
|
|
|
- }catch (Exception e){
|
|
|
- log.error("设备:{},连接中断",plcConfig.getName());
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("设备:{},连接中断", plcConfig.getName());
|
|
|
SpringUtil.getApplicationContext().publishEvent(new Device(plcConfig.getName(), "2"));
|
|
|
retry(plcConfig);
|
|
|
}
|
|
|
}
|
|
|
- },0,3,TimeUnit.SECONDS);
|
|
|
+ }, 0, 3, TimeUnit.SECONDS);
|
|
|
+ heartbeatThreads.put(plcConfig.getName(),scheduledFuture);
|
|
|
}
|
|
|
}
|
|
|
|