Browse Source

rev opc

master
汪菘 1 year ago
parent
commit
fffcf2e84f
  1. 8
      acs/nladmin-system/src/main/java/org/nl/acs/device_driver/basedriver/agv/ndcone/AgvNdcOneDeviceDriver.java
  2. 72
      acs/nladmin-system/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java
  3. 272
      acs/nladmin-system/src/main/java/org/nl/acs/opc/DeviceOpcSynchronizeAutoRun.java
  4. 318
      acs/nladmin-system/src/main/java/org/nl/acs/opc/OpcEntity.java

8
acs/nladmin-system/src/main/java/org/nl/acs/device_driver/basedriver/agv/ndcone/AgvNdcOneDeviceDriver.java

@ -229,13 +229,13 @@ public class AgvNdcOneDeviceDriver extends AbstractDeviceDriver implements Devic
//标准版-机械手对接位 //标准版-机械手对接位
if (device.getDeviceDriver() instanceof LnshPalletizingManipulatorSiteDeviceDriver) { if (device.getDeviceDriver() instanceof LnshPalletizingManipulatorSiteDeviceDriver) {
lnshPalletizingManipulatorSiteDeviceDriver = (LnshPalletizingManipulatorSiteDeviceDriver) device.getDeviceDriver(); lnshPalletizingManipulatorSiteDeviceDriver = (LnshPalletizingManipulatorSiteDeviceDriver) device.getDeviceDriver();
lnshPalletizingManipulatorSiteDeviceDriver.writing(2);
if (lnshPalletizingManipulatorSiteDeviceDriver.getMode() != 0 if (lnshPalletizingManipulatorSiteDeviceDriver.getMode() != 0
&& lnshPalletizingManipulatorSiteDeviceDriver.getMove() != 0 && lnshPalletizingManipulatorSiteDeviceDriver.getMove() != 0
&& (lnshPalletizingManipulatorSiteDeviceDriver.getIo_action() == 3 || lnshPalletizingManipulatorSiteDeviceDriver.getIo_action() == 1) && (lnshPalletizingManipulatorSiteDeviceDriver.getIo_action() == 3 || lnshPalletizingManipulatorSiteDeviceDriver.getIo_action() == 1)
&& (lnshPalletizingManipulatorSiteDeviceDriver.getAction() == 3 || lnshPalletizingManipulatorSiteDeviceDriver.getAction() == 1)) { && (lnshPalletizingManipulatorSiteDeviceDriver.getAction() == 3 || lnshPalletizingManipulatorSiteDeviceDriver.getAction() == 1)) {
inst.setExecute_status("1"); inst.setExecute_status("1");
instructionService.update(inst); instructionService.update(inst);
lnshPalletizingManipulatorSiteDeviceDriver.writing(2);
data = AgvService.sendAgvOneModeInst(phase, index, 0); data = AgvService.sendAgvOneModeInst(phase, index, 0);
lnshPalletizingManipulatorSiteDeviceDriver.setMessage(""); lnshPalletizingManipulatorSiteDeviceDriver.setMessage("");
flag = true; flag = true;
@ -264,7 +264,6 @@ public class AgvNdcOneDeviceDriver extends AbstractDeviceDriver implements Devic
//标准版-工位(交互模板) //标准版-工位(交互模板)
if(device.getDeviceDriver() instanceof LnshStationDeviceDriver){ if(device.getDeviceDriver() instanceof LnshStationDeviceDriver){
lnshStationDeviceDriver=(LnshStationDeviceDriver) device.getDeviceDriver(); lnshStationDeviceDriver=(LnshStationDeviceDriver) device.getDeviceDriver();
lnshStationDeviceDriver.writing(3);
if(lnshStationDeviceDriver.getMode()!=0 if(lnshStationDeviceDriver.getMode()!=0
&&lnshStationDeviceDriver.getMove() != 0 &&lnshStationDeviceDriver.getMove() != 0
&& (lnshStationDeviceDriver.getIo_action() == 3 || lnshStationDeviceDriver.getIo_action() == 1) && (lnshStationDeviceDriver.getIo_action() == 3 || lnshStationDeviceDriver.getIo_action() == 1)
@ -352,7 +351,6 @@ public class AgvNdcOneDeviceDriver extends AbstractDeviceDriver implements Devic
//标准版-下发条码输送线 //标准版-下发条码输送线
if(device.getDeviceDriver() instanceof ConveyorBarcodeDeviceDriver){ if(device.getDeviceDriver() instanceof ConveyorBarcodeDeviceDriver){
conveyorBarcodeDeviceDriver = (ConveyorBarcodeDeviceDriver) device.getDeviceDriver(); conveyorBarcodeDeviceDriver = (ConveyorBarcodeDeviceDriver) device.getDeviceDriver();
conveyorBarcodeDeviceDriver.writing(3);
if (conveyorBarcodeDeviceDriver.getMode() == 2 if (conveyorBarcodeDeviceDriver.getMode() == 2
) { ) {
inst.setExecute_status("1"); inst.setExecute_status("1");
@ -380,7 +378,6 @@ public class AgvNdcOneDeviceDriver extends AbstractDeviceDriver implements Devic
//标准版-叠盘机 LnshFoldDiscSiteDeviceDriverl //标准版-叠盘机 LnshFoldDiscSiteDeviceDriverl
if(device.getDeviceDriver() instanceof LnshFoldDiscSiteDeviceDriver){ if(device.getDeviceDriver() instanceof LnshFoldDiscSiteDeviceDriver){
lnshFoldDiscSiteDeviceDriver = (LnshFoldDiscSiteDeviceDriver) device.getDeviceDriver(); lnshFoldDiscSiteDeviceDriver = (LnshFoldDiscSiteDeviceDriver) device.getDeviceDriver();
lnshFoldDiscSiteDeviceDriver.writing(3);
if (lnshFoldDiscSiteDeviceDriver.getMode() != 0 if (lnshFoldDiscSiteDeviceDriver.getMode() != 0
&& lnshFoldDiscSiteDeviceDriver.getContainer_qty() > 0) { && lnshFoldDiscSiteDeviceDriver.getContainer_qty() > 0) {
// && (lnshFoldDiscSiteDeviceDriver.getIo_action() == 3 || lnshFoldDiscSiteDeviceDriver.getIo_action() == 1) // && (lnshFoldDiscSiteDeviceDriver.getIo_action() == 3 || lnshFoldDiscSiteDeviceDriver.getIo_action() == 1)
@ -408,6 +405,7 @@ public class AgvNdcOneDeviceDriver extends AbstractDeviceDriver implements Devic
} }
message += "不允许AGV取货。"; message += "不允许AGV取货。";
agv_message = lnshFoldDiscSiteDeviceDriver.getDevice_code() + message; agv_message = lnshFoldDiscSiteDeviceDriver.getDevice_code() + message;
agv_device.setStatus_message(agv_message);
lnshFoldDiscSiteDeviceDriver.setMessage(message); lnshFoldDiscSiteDeviceDriver.setMessage(message);
logService.deviceExecuteLog(device_code, "", "", message); logService.deviceExecuteLog(device_code, "", "", message);
lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message)); lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
@ -1251,7 +1249,7 @@ public class AgvNdcOneDeviceDriver extends AbstractDeviceDriver implements Devic
//任务号 //任务号
jo.put("task_code", ObjectUtil.isEmpty(instruction) ? "0" : instruction.getTask_code()); jo.put("task_code", ObjectUtil.isEmpty(instruction) ? "0" : instruction.getTask_code());
//异常 //异常
jo.put("fault", this.getError_message()); jo.put("message", agv_message);
return jo; return jo;
} }

72
acs/nladmin-system/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java

@ -7,6 +7,9 @@ import lombok.extern.slf4j.Slf4j;
import org.nl.acs.udw.UnifiedDataAccessor; import org.nl.acs.udw.UnifiedDataAccessor;
import org.nl.acs.udw.UnifiedDataAccessorFactory; import org.nl.acs.udw.UnifiedDataAccessorFactory;
import org.nl.acs.udw.UnifiedDataAppService; import org.nl.acs.udw.UnifiedDataAppService;
import org.nl.modules.lucene.service.LuceneExecuteLogService;
import org.nl.modules.lucene.service.dto.LuceneLogDto;
import org.nl.modules.wql.util.SpringContextHolder;
import org.openscada.opc.lib.da.*; import org.openscada.opc.lib.da.*;
import java.util.*; import java.util.*;
@ -24,6 +27,9 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
private int all_null; private int all_null;
private Map<String, OpcItemDto> itemSearchCache; private Map<String, OpcItemDto> itemSearchCache;
LuceneExecuteLogService lucene = SpringContextHolder.getBean(LuceneExecuteLogService.class);
public DeviceOpcProtocolRunable() { public DeviceOpcProtocolRunable() {
this.error_num = 0; this.error_num = 0;
this.all_null = 0; this.all_null = 0;
@ -48,10 +54,12 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
this.OpcServer = opcServer; this.OpcServer = opcServer;
} }
private OpcItemDto getItem(String item) { private OpcItemDto getItem(String item) {
OpcItemDto x = (OpcItemDto) this.itemSearchCache.get(item); OpcItemDto x = (OpcItemDto) this.itemSearchCache.get(item);
if (x == null) { if (x == null) {
Iterator var3 = this.protocols.iterator(); Iterator var3 = this.protocols.iterator();
while (var3.hasNext()) { while (var3.hasNext()) {
OpcItemDto dto = (OpcItemDto) var3.next(); OpcItemDto dto = (OpcItemDto) var3.next();
if (StrUtil.equals(item, dto.getItem_code())) { if (StrUtil.equals(item, dto.getItem_code())) {
@ -61,9 +69,11 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
} }
} }
} }
return x; return x;
} }
@Override @Override
public void run() { public void run() {
if (OpcConfig.opc_item_read_using_callback) { if (OpcConfig.opc_item_read_using_callback) {
@ -73,7 +83,9 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
} }
} }
private void runOld() { private void runOld() {
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService .class);
while (true) { while (true) {
start: start:
try { try {
@ -87,10 +99,10 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
log.trace("清理server..."); log.trace("清理server...");
} }
this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain()); group =opcServerService.getServer(this.getOpcServer().getOpc_code());
this.server.addStateListener(this); // this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain());
group = this.server.addGroup(); // this.server.addStateListener(this);
// group = this.server.addGroup();
List<String> itemsString = new ArrayList(); List<String> itemsString = new ArrayList();
Iterator var3 = this.protocols.iterator(); Iterator var3 = this.protocols.iterator();
@ -130,7 +142,6 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
OpcStartTag.is_run = true; OpcStartTag.is_run = true;
} }
//线程名
tag = ""; tag = "";
if (log.isWarnEnabled()) { if (log.isWarnEnabled()) {
tag = Thread.currentThread().getName(); tag = Thread.currentThread().getName();
@ -138,10 +149,10 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
tag = tag + this.getOpcGroupID(); tag = tag + this.getOpcGroupID();
} }
} }
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key); UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
boolean time_out = false; boolean time_out = false;
label97:
while (DeviceOpcSynchronizeAutoRun.isRun) { while (DeviceOpcSynchronizeAutoRun.isRun) {
long begin = System.currentTimeMillis(); long begin = System.currentTimeMillis();
if (log.isTraceEnabled()) { if (log.isTraceEnabled()) {
@ -154,6 +165,7 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
if (log.isTraceEnabled()) { if (log.isTraceEnabled()) {
log.trace("{} 读取耗时:{}", tag, duration); log.trace("{} 读取耗时:{}", tag, duration);
} }
if (duration > 1000L) { if (duration > 1000L) {
if (!time_out) { if (!time_out) {
log.warn("{} 读取超时 : {}", tag, duration); log.warn("{} 读取超时 : {}", tag, duration);
@ -180,6 +192,10 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
Object his = accessor_value.getValue(itemId); Object his = accessor_value.getValue(itemId);
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && his != null) { if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && his != null) {
log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality()); log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality());
// valueAllNotNull = false;
ThreadUtl.sleep((long) ((new Random()).nextInt(3) +1) * 1000);
break start;
} }
if (!UnifiedDataAppService.isEquals(value, his)) { if (!UnifiedDataAppService.isEquals(value, his)) {
@ -187,10 +203,11 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
if (true) { if (true) {
this.logItemChanged(itemId, accessor_value, value, itemDto); this.logItemChanged(itemId, accessor_value, value, itemDto);
} }
if(!ObjectUtil.isEmpty(value)){
accessor_value.setValue(itemId, value); accessor_value.setValue(itemId, value);
} }
} }
}
end = System.currentTimeMillis(); end = System.currentTimeMillis();
if (log.isTraceEnabled()) { if (log.isTraceEnabled()) {
@ -209,17 +226,17 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
random *= 1000; random *= 1000;
if (this.all_null < 3) { if (this.all_null < 3) {
if (log.isWarnEnabled()) { if (log.isWarnEnabled()) {
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null, 5000 + random); log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,5000 + random);
} }
ThreadUtl.sleep((long) (5000 + random)); ThreadUtl.sleep((long) (5000 + random));
} else if (this.all_null < 6) { } else if (this.all_null < 6) {
if (log.isWarnEnabled()) { if (log.isWarnEnabled()) {
log.warn(tag + "重新创建server"); log.warn(tag + "重新创建server");
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null, 30000 + random); log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,30000 + random);
} }
// ThreadUtl.sleep((long) (30000 + random)); // ThreadUtl.sleep((long) (30000 + random));
ThreadUtl.sleep((long) ((new Random()).nextInt(3) + 1) * 1000); ThreadUtl.sleep((long) ((new Random()).nextInt(3) +1) * 1000);
break start; break start;
} else if (this.all_null < 12) { } else if (this.all_null < 12) {
if (log.isWarnEnabled()) { if (log.isWarnEnabled()) {
@ -233,8 +250,8 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
} }
ThreadUtl.sleep((long) (120000 + random)); ThreadUtl.sleep((long) (120000 + random));
} }
++this.all_null; ++this.all_null;
} else { } else {
this.all_null = 0; this.all_null = 0;
@ -250,9 +267,9 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
try { try {
this.server.disconnect(); this.server.disconnect();
} catch (Exception var25) { } catch (Exception var25) {
} }
} }
this.server = null; this.server = null;
if (!DeviceOpcSynchronizeAutoRun.isRun) { if (!DeviceOpcSynchronizeAutoRun.isRun) {
log.warn("opc线程停止2。。。"); log.warn("opc线程停止2。。。");
@ -339,6 +356,7 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
} }
} }
public void connectionStateChanged(boolean connected) { public void connectionStateChanged(boolean connected) {
if (!connected) { if (!connected) {
this.server = null; this.server = null;
@ -359,6 +377,8 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
long seconds = mss % 60000L / 1000L; long seconds = mss % 60000L / 1000L;
return days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds "; return days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
} }
public void changed(Item item, ItemState itemState) { public void changed(Item item, ItemState itemState) {
String itemId = item.getId(); String itemId = item.getId();
@ -400,11 +420,31 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
Object obj = accessor_value.getValue(relate); Object obj = accessor_value.getValue(relate);
sb.append("key:" + relate + "value:" + obj + ";"); sb.append("key:" + relate + "value:" + obj + ";");
} }
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value, sb}); //log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value, sb});
// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{};信号快照:{}", new Object[]{itemId, his, value, sb}); if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time")) {
if(!ObjectUtil.equal(his,"null") || !ObjectUtil.equal(value,"null") || !ObjectUtil.isEmpty(his) || !ObjectUtil.isEmpty(value)){
// log.warn("{} 信号 {} 发生变更 {} -> {} 信号快照 {}", itemDto.getDevice_code(), itemCode, his, value, sb);
lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value)));
}
}
} else {
//log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value});
if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time")) {
// 存在上次点位值为null情况 则不记录日志
if((ObjectUtil.equal(his,"null") || ObjectUtil.isEmpty(his)) || (ObjectUtil.equal(value,"null") || ObjectUtil.isEmpty(value)) ){
//lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value)));
System.out.println("his:"+his + ",value:"+ value);
} else { } else {
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value}); lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value)));
// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{}", new Object[]{itemId, his, value}); }
// if(!ObjectUtil.equal(his,"null") || !ObjectUtil.equal(value,"null") || !ObjectUtil.isEmpty(his) || !ObjectUtil.isEmpty(value)){
// log.warn("{} 信号 {} 发生变更 {} -> {} 信号快照 {}", itemDto.getDevice_code(), itemCode, his, value, sb);
// lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value)));
// }
}
} }
} }

272
acs/nladmin-system/src/main/java/org/nl/acs/opc/DeviceOpcSynchronizeAutoRun.java

@ -1,5 +1,7 @@
package org.nl.acs.opc; package org.nl.acs.opc;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.NamedThreadFactory; import org.apache.lucene.util.NamedThreadFactory;
import org.nl.acs.auto.run.AbstractAutoRunnable; import org.nl.acs.auto.run.AbstractAutoRunnable;
@ -25,260 +27,66 @@ import java.util.concurrent.*;
@Component @Component
@Slf4j @Slf4j
public class DeviceOpcSynchronizeAutoRun extends AbstractAutoRunnable { public class DeviceOpcSynchronizeAutoRun extends AbstractAutoRunnable {
static boolean isRun = true;
public static boolean isRun = false;
ExecutorService executorService = Executors.newCachedThreadPool();
@Autowired @Autowired
private DeviceAppService deviceAppService; private DeviceAppService deviceAppService;
@Autowired @Autowired
private OpcServerManageService opcServerManageService; private OpcServerManageService opcServerManageService;
@Autowired
LuceneExecuteLogService lucene;
static ExecutorService executorService;
public static Map<String, OpcServerManageDto> opcServersConfig;
public static Map<String, OpcItemDto> itemCodeOpcItemDtoMapping = new ConcurrentHashMap();
static boolean canRefreshOpcEntity = true;
private long lastRefreshOpcEntityTime;
static UnifiedDataAccessor udw;
private static Map<String, Boolean> canReadOpcValues;
private static volatile Map<String, OpcEntity> opcCodeOpcEntityMapping;
public DeviceOpcSynchronizeAutoRun() {
this.lastRefreshOpcEntityTime = 0L;
}
@Override
public String getCode() { public String getCode() {
return DeviceOpcSynchronizeAutoRun.class.getSimpleName(); return DeviceOpcSynchronizeAutoRun.class.getSimpleName();
} }
@Override
public String getName() { public String getName() {
return "opc设备同步器"; return "opc设备同步器";
} }
static Group getGroup(String opcCode) throws Exception { @Override
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class); public void autoRun() throws Exception {
return opcServerService.getServer(opcCode); {
} isRun = true;
static void submitTimeLimitTask(Runnable runnable, String opcCode) { Map<String, OpcServerManageDto> servers = this.opcServerManageService.queryAllServerMap();
CompletableFuture<Void> future = CompletableFuture.runAsync(runnable, executorService); Map<String, List<List<OpcItemDto>>> pros;
do{
// try { Thread.sleep(1000L);
// future.get(10L, TimeUnit.SECONDS); pros = this.deviceAppService.findAllFormatProtocolFromDriver();
// } catch (InterruptedException var9) { }while (ObjectUtil.isEmpty(pros));
// Thread.currentThread().interrupt(); Set<String> keys = pros.keySet();
// } catch (ExecutionException var10) { Iterator var4 = keys.iterator();
// var10.printStackTrace(); //代码执行一次
// } catch (TimeoutException var11) { while (var4.hasNext()) {
// itemCodeOpcItemDtoMapping.keySet().forEach((key) -> { String key = (String) var4.next();
// udw.setValue(key, (Object) null); List<List<OpcItemDto>> list = (List) pros.get(key);
// }); OpcServerManageDto opcServer = (OpcServerManageDto) servers.get(key);
// canReadOpcValues = new ConcurrentHashMap<>(); Iterator var8 = list.iterator();
// System.out.println("opc设备同步器 任务执行超时,取消任务..."); while (var8.hasNext()) {
// future.cancel(true); List<OpcItemDto> groupProtols = (List) var8.next();
// } finally { DeviceOpcProtocolRunable runable = new DeviceOpcProtocolRunable();
// canRefreshOpcEntity = true; runable.setProtocols(groupProtols);
// if (opcCode != null) { runable.setOpcServer(opcServer);
// canReadOpcValues.put(opcCode, true); this.executorService.submit(runable);
// }
//
// }
} }
private ExecutorService createThreadPool() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(32, 32, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory("opc-sync"));
executor.allowCoreThreadTimeOut(true);
return executor;
} }
public void autoRun() { // 同步无光电设备信号
OpcStartTag.is_run = true; //Map<String, List<List<OpcItemDto>>> pros1 = this.deviceAppService.findAllFormatProtocolFromDriver();
opcServersConfig = this.opcServerManageService.queryAllServerMap(); //List<DeviceDriver> opcDrivers = this.deviceAppService.findDeviceDriver(DeviceDriver.class);
executorService = this.createThreadPool();
opcCodeOpcEntityMapping = new ConcurrentHashMap();
itemCodeOpcItemDtoMapping.keySet().forEach((key) -> {
udw.setValue(key, (Object) null);
});
canRefreshOpcEntity = true;
canReadOpcValues.clear();
while (true) { while (true) {
this.refreshOpcEntity(); Thread.sleep(3000L);
Iterator var1 = opcServersConfig.keySet().iterator();
while (var1.hasNext()) {
String opcCode = (String) var1.next();
submitTimeLimitTask(() -> {
boolean in = false;
try {
if (canReadOpcValues.computeIfAbsent(opcCode, (key) -> true)) {
in = true;
canReadOpcValues.put(opcCode, false);
this.readOpcValues(opcCode);
}
} catch (Exception var3) {
var3.printStackTrace();
} finally {
canRefreshOpcEntity = true;
if (opcCode != null && in) {
canReadOpcValues.put(opcCode, true);
}
}
}, opcCode);
}
ThreadUtl.sleep((long) OpcConfig.synchronized_millisecond);
}
}
private void readOpcValues(String opcCode) throws Exception {
synchronized (opcCode.intern()) {
OpcEntity opcEntity = (OpcEntity) opcCodeOpcEntityMapping.get(opcCode);
if (opcEntity != null) {
if (opcEntity.getItems().size() != 0) {
long begin = System.currentTimeMillis();
if (log.isTraceEnabled()) {
log.trace("opc {} 开始计时{}", opcCode, begin);
} }
new HashMap();
Map<Item, ItemState> itemStatus;
try {
itemStatus = opcEntity.readAll();
} catch (Exception var15) {
itemStatus = opcEntity.readDividually();
}
long end = System.currentTimeMillis();
long duration = end - begin;
if (log.isTraceEnabled()) {
log.trace("opc {} 读取耗时:{}", opcCode, duration);
} }
if (duration > 1000L) {
log.warn("opc {} 读取超时 : {}", opcCode, duration);
}
// boolean allNull = itemStatus.entrySet().stream().map((map) -> {
// try {
// return OpcUtl.getValue((Item)map.getKey(), (ItemState)map.getValue());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }).allMatch(Objects::isNull);
// if (allNull) {
// opcEntity.getItems().clear();
// }
UnifiedDataAccessor udw = opcEntity.getUdw();
Set<Item> items = itemStatus.keySet();
Iterator var18 = items.iterator();
while (var18.hasNext()) {
Item item = (Item) var18.next();
ItemState itemState = (ItemState) itemStatus.get(item);
Object nowValue = OpcUtl.getValue(item, itemState);
String itemId = item.getId();
Object historyValue = udw.getValue(itemId);
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && historyValue != null) {
log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality());
}
if (!UnifiedDataAppService.isEquals(nowValue, historyValue)) {
OpcItemDto itemDto = (OpcItemDto) itemCodeOpcItemDtoMapping.get(itemId);
if (true) {
this.logItemChanged(itemId, udw, nowValue, itemDto);
}
udw.setValue(itemId, nowValue);
}
}
}
}
}
}
private void refreshOpcEntity() {
if (canRefreshOpcEntity) {
canRefreshOpcEntity = false;
long now = System.currentTimeMillis();
if (now - this.lastRefreshOpcEntityTime >= 20000L) {
this.lastRefreshOpcEntityTime = now;
submitTimeLimitTask(() -> {
try {
Map<String, List<List<OpcItemDto>>> protocol = this.deviceAppService.findAllFormatProtocolFromDriver();
Iterator var2 = protocol.entrySet().iterator();
while (var2.hasNext()) {
Entry<String, List<List<OpcItemDto>>> stringListEntry = (Entry) var2.next();
String opcCode = (String) stringListEntry.getKey();
List<List<OpcItemDto>> opcItemDtos = (List) stringListEntry.getValue();
((OpcEntity) opcCodeOpcEntityMapping.computeIfAbsent(opcCode, OpcEntity::new)).reload(opcItemDtos);
}
} catch (Exception var6) {
var6.printStackTrace();
} finally {
canRefreshOpcEntity = true;
}
}, (String) null);
}
}
}
private void logMessage(String errorMessage) {
try {
// issueLogger.setResource(OpcConfig.resource_code, OpcConfig.resource_name).setError(StringUtl.getString(100), "设备同步通信异常").log(errorMessage, new Object[0]);
// businessLogger.setResource(OpcConfig.resource_code, OpcConfig.resource_name).setError(StringUtl.getString(100), "设备同步通信异常").log(errorMessage, new Object[0]);
} catch (Exception var5) {
var5.printStackTrace();
}
} }
@Override
public void after() { public void after() {
OpcStartTag.is_run = false; isRun = false;
opcCodeOpcEntityMapping.values().forEach((opcEntity) -> { this.executorService.shutdownNow();
opcEntity.cleanUdwCache(); this.executorService = Executors.newCachedThreadPool();
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class);
opcServerService.cleanGroups(opcEntity.getOpcCode());
});
opcCodeOpcEntityMapping = new ConcurrentHashMap();
itemCodeOpcItemDtoMapping = new ConcurrentHashMap();
executorService.shutdownNow();
}
private void logItemChanged(String itemCode, UnifiedDataAccessor udw, Object value, OpcItemDto itemDto) {
Object his = udw.getValue(itemCode);
List<String> relate_items = itemDto.getRelate_items();
if (relate_items != null && !relate_items.isEmpty()) {
StringBuilder sb = new StringBuilder();
Iterator var8 = relate_items.iterator();
while (var8.hasNext()) {
String relate = (String) var8.next();
Object obj = udw.getValue(relate);
sb.append("key:").append(relate).append("value:").append(obj).append(";");
}
if (!itemCode.endsWith("heartbeat") && !itemCode.endsWith("time")) {
log.warn("{} 信号 {} 发生变更 {} -> {} 信号快照 {}", itemDto.getDevice_code(), itemCode, his, value, sb);
lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value)));
}
} else {
if (!itemCode.endsWith("heartbeat") && !itemCode.endsWith("time")) {
log.warn("{} 信号 {} 发生变更 {} -> {}", itemDto.getDevice_code(), itemCode, his, value);
lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value)));
}
}
}
static {
udw = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
canReadOpcValues = new ConcurrentHashMap();
opcCodeOpcEntityMapping = new ConcurrentHashMap();
} }
} }

318
acs/nladmin-system/src/main/java/org/nl/acs/opc/OpcEntity.java

@ -13,163 +13,163 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class OpcEntity { public class OpcEntity {
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class); // OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class);
private final UnifiedDataAccessor udw; // private final UnifiedDataAccessor udw;
private Map<String, List<Item>> items; // private Map<String, List<Item>> items;
private Map<String, List<String>> someFailDevices; // private Map<String, List<String>> someFailDevices;
private String opcCode; // private String opcCode;
//
public OpcEntity(String opcCode) { // public OpcEntity(String opcCode) {
this.udw = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key); // this.udw = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
this.items = new ConcurrentHashMap(); // this.items = new ConcurrentHashMap();
this.someFailDevices = new ConcurrentHashMap(); // this.someFailDevices = new ConcurrentHashMap();
this.opcCode = opcCode; // this.opcCode = opcCode;
} // }
//
public void reload(List<List<OpcItemDto>> opcItemDtos) { // public void reload(List<List<OpcItemDto>> opcItemDtos) {
Map<String, List<String>> itemCodes = new ConcurrentHashMap(); // Map<String, List<String>> itemCodes = new ConcurrentHashMap();
(opcItemDtos.stream().flatMap(Collection::stream).collect(Collectors.groupingBy(OpcItemDto::getDevice_code))).forEach((deviceCodes, opcItemDtoList) -> { // (opcItemDtos.stream().flatMap(Collection::stream).collect(Collectors.groupingBy(OpcItemDto::getDevice_code))).forEach((deviceCodes, opcItemDtoList) -> {
itemCodes.put(deviceCodes, opcItemDtoList.stream().map(OpcItemDto::getItem_code).collect(Collectors.toList())); // itemCodes.put(deviceCodes, opcItemDtoList.stream().map(OpcItemDto::getItem_code).collect(Collectors.toList()));
}); // });
DeviceOpcSynchronizeAutoRun.itemCodeOpcItemDtoMapping.putAll((Map)opcItemDtos.stream().flatMap(Collection::stream).collect(Collectors.toMap(OpcItemDto::getItem_code, (obj) -> { // DeviceOpcSynchronizeAutoRun.itemCodeOpcItemDtoMapping.putAll((Map)opcItemDtos.stream().flatMap(Collection::stream).collect(Collectors.toMap(OpcItemDto::getItem_code, (obj) -> {
return obj; // return obj;
},(k, v) -> k))); // },(k, v) -> k)));
if (this.items.size() == 0) { // if (this.items.size() == 0) {
itemCodes.values().stream().flatMap(Collection::stream).forEach((key) -> { // itemCodes.values().stream().flatMap(Collection::stream).forEach((key) -> {
this.udw.setValue(key, (Object)null); // this.udw.setValue(key, (Object)null);
}); // });
this.addItemsIntoGroup(itemCodes); // this.addItemsIntoGroup(itemCodes);
} else { // } else {
if (this.someFailDevices.size() > 0) { // if (this.someFailDevices.size() > 0) {
this.reAddDevices(); // this.reAddDevices();
} // }
//
} // }
} // }
//
private void reAddDevices() { // private void reAddDevices() {
Map<String, List<Item>> addItems = new ConcurrentHashMap(); // Map<String, List<Item>> addItems = new ConcurrentHashMap();
StringBuilder err_message = new StringBuilder(); // StringBuilder err_message = new StringBuilder();
this.someFailDevices.forEach((deviceCode, itemCodesList) -> { // this.someFailDevices.forEach((deviceCode, itemCodesList) -> {
itemCodesList.forEach((itemCode) -> { // itemCodesList.forEach((itemCode) -> {
try { // try {
Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode); // Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode);
((List)addItems.computeIfAbsent(deviceCode, (key) -> { // ((List)addItems.computeIfAbsent(deviceCode, (key) -> {
return new ArrayList(); // return new ArrayList();
})).add(group.addItem(itemCode)); // })).add(group.addItem(itemCode));
} catch (Exception var6) { // } catch (Exception var6) {
err_message.append(itemCode).append(" 添加失败; "); // err_message.append(itemCode).append(" 添加失败; ");
} // }
//
}); // });
List<Item> deviceItems = (List)addItems.get(deviceCode); // List<Item> deviceItems = (List)addItems.get(deviceCode);
if (deviceItems != null && deviceItems.size() == itemCodesList.size()) { // if (deviceItems != null && deviceItems.size() == itemCodesList.size()) {
this.someFailDevices.remove(deviceCode); // this.someFailDevices.remove(deviceCode);
} else if (itemCodesList.size() == 0) { // } else if (itemCodesList.size() == 0) {
addItems.remove(deviceCode); // addItems.remove(deviceCode);
} else { // } else {
assert deviceItems != null; // assert deviceItems != null;
//
((List)this.someFailDevices.get(deviceCode)).removeAll(deviceItems); // ((List)this.someFailDevices.get(deviceCode)).removeAll(deviceItems);
} // }
//
synchronized(this.opcCode.intern()) { // synchronized(this.opcCode.intern()) {
this.items.putAll(addItems); // this.items.putAll(addItems);
} // }
//
if (err_message.length() > 0) { // if (err_message.length() > 0) {
String errMsg = err_message.toString(); // String errMsg = err_message.toString();
//this.log.warn("{}:{}", com.wxzd.wcs.opc.OpcConfig.resource_code, errMsg); // //this.log.warn("{}:{}", com.wxzd.wcs.opc.OpcConfig.resource_code, errMsg);
} // }
//
}); // });
} // }
//
private void addItemsIntoGroup(Map<String, List<String>> itemCodes) { // private void addItemsIntoGroup(Map<String, List<String>> itemCodes) {
try { // try {
Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode); // Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode);
StringBuilder err_message = new StringBuilder(); // StringBuilder err_message = new StringBuilder();
Map<String, List<Item>> items = new ConcurrentHashMap(); // Map<String, List<Item>> items = new ConcurrentHashMap();
itemCodes.forEach((deviceCode, itemCodesList) -> { // itemCodes.forEach((deviceCode, itemCodesList) -> {
itemCodesList.forEach((itemCode) -> { // itemCodesList.forEach((itemCode) -> {
try { // try {
((List)items.computeIfAbsent(deviceCode, (key) -> { // ((List)items.computeIfAbsent(deviceCode, (key) -> {
return new ArrayList(); // return new ArrayList();
})).add(group.addItem(itemCode)); // })).add(group.addItem(itemCode));
} catch (Exception var7) { // } catch (Exception var7) {
((List)this.someFailDevices.computeIfAbsent(deviceCode, (key) -> { // ((List)this.someFailDevices.computeIfAbsent(deviceCode, (key) -> {
return new ArrayList(); // return new ArrayList();
})).add(itemCode); // })).add(itemCode);
this.udw.setValue(itemCode, (Object)null); // this.udw.setValue(itemCode, (Object)null);
err_message.append(itemCode).append(" 添加失败; "); // err_message.append(itemCode).append(" 添加失败; ");
} // }
//
}); // });
List<Item> deviceItems = (List)items.get(deviceCode); // List<Item> deviceItems = (List)items.get(deviceCode);
if (deviceItems != null && deviceItems.size() != itemCodesList.size()) { // if (deviceItems != null && deviceItems.size() != itemCodesList.size()) {
items.remove(deviceCode); // items.remove(deviceCode);
this.someFailDevices.put(deviceCode, itemCodesList); // this.someFailDevices.put(deviceCode, itemCodesList);
} // }
//
}); // });
synchronized(this.opcCode.intern()) { // synchronized(this.opcCode.intern()) {
this.items = items; // this.items = items;
} // }
//
if (err_message.length() > 0) { // if (err_message.length() > 0) {
String errMsg = err_message.toString(); // String errMsg = err_message.toString();
// this.log.warn("{}:{}", OpcConfig.resource_code, errMsg); //// this.log.warn("{}:{}", OpcConfig.resource_code, errMsg);
} // }
} catch (Exception var8) { // } catch (Exception var8) {
var8.printStackTrace(); // var8.printStackTrace();
} // }
//
} // }
//
public void cleanUdwCache() { // public void cleanUdwCache() {
this.items.values().stream().flatMap(Collection::stream).map(Item::getId).forEach((key) -> { // this.items.values().stream().flatMap(Collection::stream).map(Item::getId).forEach((key) -> {
this.udw.setValue(key, (Object)null); // this.udw.setValue(key, (Object)null);
}); // });
} // }
//
public Map<Item, ItemState> readAll() throws Exception { // public Map<Item, ItemState> readAll() throws Exception {
return opcServerService.getServer(this.opcCode).read(true, (Item[])this.items.values().stream().flatMap(Collection::stream).toArray((x$0) -> { // return opcServerService.getServer(this.opcCode).read(true, (Item[])this.items.values().stream().flatMap(Collection::stream).toArray((x$0) -> {
return new Item[x$0]; // return new Item[x$0];
})); // }));
} // }
//
public Map<Item, ItemState> readDividually() { // public Map<Item, ItemState> readDividually() {
Map<Item, ItemState> result = new HashMap(); // Map<Item, ItemState> result = new HashMap();
CompletableFuture[] futures = (CompletableFuture[])this.items.entrySet().stream().map((entry) -> { // CompletableFuture[] futures = (CompletableFuture[])this.items.entrySet().stream().map((entry) -> {
return CompletableFuture.runAsync(() -> { // return CompletableFuture.runAsync(() -> {
try { // try {
Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode); // Group group = DeviceOpcSynchronizeAutoRun.getGroup(this.opcCode);
result.putAll(group.read(true, (Item[])((List)entry.getValue()).toArray(new Item[0]))); // result.putAll(group.read(true, (Item[])((List)entry.getValue()).toArray(new Item[0])));
} catch (Exception var5) { // } catch (Exception var5) {
String deviceCode = (String)entry.getKey(); // String deviceCode = (String)entry.getKey();
// to do // // to do
// this.someFailDevices.put(deviceCode, ((List)entry.getValue()).stream().map(Item::getId).collect(Collectors.toList())); //// this.someFailDevices.put(deviceCode, ((List)entry.getValue()).stream().map(Item::getId).collect(Collectors.toList()));
this.items.remove(deviceCode); // this.items.remove(deviceCode);
} // }
//
}, DeviceOpcSynchronizeAutoRun.executorService); // }, DeviceOpcSynchronizeAutoRun.executorService);
}).toArray((x$0) -> { // }).toArray((x$0) -> {
return new CompletableFuture[x$0]; // return new CompletableFuture[x$0];
}); // });
CompletableFuture.allOf(futures).join(); // CompletableFuture.allOf(futures).join();
return result; // return result;
} // }
//
//
public UnifiedDataAccessor getUdw() { // public UnifiedDataAccessor getUdw() {
return this.udw; // return this.udw;
} // }
//
public Map<String, List<Item>> getItems() { // public Map<String, List<Item>> getItems() {
return this.items; // return this.items;
} // }
//
public String getOpcCode() { // public String getOpcCode() {
return this.opcCode; // return this.opcCode;
} // }
} }

Loading…
Cancel
Save