Browse Source

fix: 下发信号,读取信号,NDC交互修复

master
yanps 2 months ago
parent
commit
afcba1e6ee
  1. 13
      acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/auto/run/TwoNDCSocketConnectionAutoRun.java
  2. 3
      acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/impl/DeviceServiceImpl.java
  3. 26
      acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/agv/ndctwo/AgvNdcTwoDeviceDriver.java
  4. 424
      acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java
  5. 2
      acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcConfig.java

13
acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/auto/run/TwoNDCSocketConnectionAutoRun.java

@ -248,11 +248,11 @@ public class TwoNDCSocketConnectionAutoRun extends AbstractAutoRunnable {
log.info(agvaddr + "对应设备号为空!");
return;
}
if (ObjectUtil.isNotEmpty(device)) {
if (ObjectUtil.isNotEmpty(device)) {
if (device.getDeviceDriver() instanceof StandardAutodoorDeviceDriver) {
standardAutodoorDeviceDriver = (StandardAutodoorDeviceDriver) device.getDeviceDriver();
if (standardAutodoorDeviceDriver.getDoor() == 1) {
standardAutodoorDeviceDriver.writing("item_to_command",1);
standardAutodoorDeviceDriver.writing("to_command", 1);
}
if (standardAutodoorDeviceDriver.getTo_command() == 1) {
data = ndcAgvService.sendAgvTwoModeInst(phase, index, 0);
@ -271,12 +271,11 @@ public class TwoNDCSocketConnectionAutoRun extends AbstractAutoRunnable {
}
if (ObjectUtil.isNotEmpty(device)) {
if (device.getDeviceDriver() instanceof StandardAutodoorDeviceDriver) {
data = ndcAgvService.sendAgvTwoModeInst(phase, index, 0);
}
data = ndcAgvService.sendAgvTwoModeInst(phase, index, 0);
}
else {
log.info(device_code + "对应设备号为空!");
}
} else {
log.info(device_code + "对应设备号为空!");
}
} else {
//上报异常信息
//(不需要WCS反馈)

3
acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/impl/DeviceServiceImpl.java

@ -1325,7 +1325,8 @@ public class DeviceServiceImpl extends CommonServiceImpl<DeviceMapper, Device> i
itemString.add(json.getString("code"));
}
final Map<String, Object> readList = ReadUtil.read(itemString);
Server server = ReadUtil.getServer(opc_id);
final Map<String, Object> readList = ReadUtil.read(itemString,server);
JSONArray result = new JSONArray();
for (int i = 0; i < dbItems.size(); i++) {

26
acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/agv/ndctwo/AgvNdcTwoDeviceDriver.java

@ -36,8 +36,8 @@ import org.nl.config.lucene.service.LuceneExecuteLogService;
import org.nl.config.lucene.service.dto.LuceneLogDto;
import org.nl.system.service.param.ISysParamService;
import org.nl.config.SpringContextHolder;
import java.util.Map;
import java.util.Map;
/**
@ -305,6 +305,14 @@ public class AgvNdcTwoDeviceDriver extends AbstractDeviceDriver implements Devic
standardOrdinarySiteDeviceDriver.setAgvphase(phase);
standardOrdinarySiteDeviceDriver.setIndex(index);
standardOrdinarySiteDeviceDriver.setInst(inst);
} else {
data = ndcAgvService.sendAgvTwoModeInst(phase, index, 0, 0, 0);
LuceneLogDto logDto = LuceneLogDto.builder()
.device_code(this.getDeviceCode())
.content("agvphase:" + phase + "反馈:" + data)
.build();
logDto.setLog_level(4);
luceneExecuteLogService.deviceExecuteLog(logDto);
}
}
@ -433,10 +441,16 @@ public class AgvNdcTwoDeviceDriver extends AbstractDeviceDriver implements Devic
standardOrdinarySiteDeviceDriver.setAgvphase(phase);
standardOrdinarySiteDeviceDriver.setIndex(index);
standardOrdinarySiteDeviceDriver.setInst(inst);
} else {
data = ndcAgvService.sendAgvTwoModeInst(phase, index, 0, 0, 0);
LuceneLogDto logDto = LuceneLogDto.builder()
.device_code(this.getDeviceCode())
.content("agvphase:" + phase + "反馈:" + data)
.build();
logDto.setLog_level(4);
luceneExecuteLogService.deviceExecuteLog(logDto);
}
}
else if (phase == 0x70) {
} else if (phase == 0x70) {
//x坐标
x = ikey;
LuceneLogDto logDto = LuceneLogDto.builder()
@ -554,9 +568,7 @@ public class AgvNdcTwoDeviceDriver extends AbstractDeviceDriver implements Devic
.build();
logDto.setLog_level(4);
luceneExecuteLogService.deviceExecuteLog(logDto);
if (StrUtil.equals(inst.getAgv_system_type(), "2")) {
TwoNDCSocketConnectionAutoRun.write(data);
}
TwoNDCSocketConnectionAutoRun.write(data);
}
}

424
acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java

@ -5,19 +5,6 @@ import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscriptionManager;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedDataItem;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedSubscription;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
import org.nl.acs.AcsConfig;
import org.nl.acs.instruction.service.InstructionService;
import org.nl.acs.opc.service.dto.OpcServerManageDto;
@ -25,18 +12,13 @@ import org.nl.acs.udw.UnifiedDataAccessor;
import org.nl.acs.udw.UnifiedDataAccessorFactory;
import org.nl.acs.udw.UnifiedDataAppService;
import org.nl.common.enums.LogTypeEnum;
import org.nl.common.exception.BadRequestException;
import org.nl.config.SpringContextHolder;
import org.nl.config.lucene.service.LuceneExecuteLogService;
import org.nl.config.lucene.service.dto.LuceneLogDto;
import org.nl.system.service.param.ISysParamService;
import org.openscada.opc.lib.da.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Pattern;
@ -112,7 +94,6 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
private void runOld() {
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService .class);
while (true) {
start:
try {
if (this.group != null) {
@ -174,134 +155,132 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
tag = tag + "," + this.getOpcGroupID();
}
}
OpcServerManageDto opcServer = this.getOpcServer();
if (opcServer.getOpc_code().equals("MXDDHJ")) {
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
boolean time_out = false;
while (DeviceOpcSynchronizeAutoRun.isRun) {
long begin = System.currentTimeMillis();
if (log.isTraceEnabled()) {
log.trace("{} 开始记时{}", tag, DateUtil.now());
}
Map<Item, ItemState> itemStatus = group.read(true, (Item[]) itemsMap.values().toArray(new Item[0]));
long end = System.currentTimeMillis();
long duration = end - begin;
if (log.isTraceEnabled()) {
log.trace("{} 读取耗时:{}", tag, duration);
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
boolean time_out = false;
while (DeviceOpcSynchronizeAutoRun.isRun) {
long begin = System.currentTimeMillis();
if (log.isTraceEnabled()) {
log.trace("{} 开始记时{}", tag, DateUtil.now());
}
Map<Item, ItemState> itemStatus = group.read(true, (Item[]) itemsMap.values().toArray(new Item[0]));
long end = System.currentTimeMillis();
long duration = end - begin;
if (log.isTraceEnabled()) {
log.trace("{} 读取耗时:{}", tag, duration);
}
if (duration > 1000L) {
if (!time_out) {
log.warn("{} 读取超时 : {}", tag, duration);
}
if (duration > 1000L) {
if (!time_out) {
log.warn("{} 读取超时 : {}", tag, duration);
}
time_out = true;
} else {
time_out = false;
}
time_out = true;
boolean valueAllNotNull = false;
Set<Item> items = itemStatus.keySet();
Iterator var18 = items.iterator();
while (var18.hasNext()) {
Item item = (Item) var18.next();
ItemState itemState = (ItemState) itemStatus.get(item);
Object value = OpcUtl.getValue(item, itemState);
if (value != null) {
valueAllNotNull = true;
} else {
time_out = false;
log.info("item:{},velue为空,value:{}", item.getId(), value);
}
boolean valueAllNotNull = false;
Set<Item> items = itemStatus.keySet();
Iterator var18 = items.iterator();
while (var18.hasNext()) {
Item item = (Item) var18.next();
ItemState itemState = (ItemState) itemStatus.get(item);
Object value = OpcUtl.getValue(item, itemState);
if (value != null) {
valueAllNotNull = true;
} else {
log.info("item:{},velue为空,value:{}", item.getId(), value);
}
String itemId = item.getId();
Object his = accessor_value.getValue(itemId);
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && his != null) {
log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality());
valueAllNotNull = false;
}
String itemId = item.getId();
Object his = accessor_value.getValue(itemId);
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && his != null) {
log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality());
valueAllNotNull = false;
if (!UnifiedDataAppService.isEquals(value, his)) {
OpcItemDto itemDto = this.getItem(itemId);
if (true) {
this.logItemChanged(itemId, accessor_value, value, itemDto);
}
if (!UnifiedDataAppService.isEquals(value, his)) {
OpcItemDto itemDto = this.getItem(itemId);
if (true) {
this.logItemChanged(itemId, accessor_value, value, itemDto);
}
if (!ObjectUtil.isEmpty(value) || "".equals(value)) {
accessor_value.setValue(itemId, value);
}
if (ObjectUtil.isEmpty(value) && !"".equals(value)) {
accessor_value.removeValue(itemId);
}
if(!ObjectUtil.isEmpty(value) || "".equals(value)){
accessor_value.setValue(itemId, value);
}
if(ObjectUtil.isEmpty(value) && !"".equals(value)){
accessor_value.removeValue(itemId);
}
}
}
end = System.currentTimeMillis();
if (log.isTraceEnabled()) {
log.trace("{}", itemsString);
log.trace("{} 计算完成耗时{}", tag, end - begin);
}
end = System.currentTimeMillis();
if (log.isTraceEnabled()) {
log.trace("{}", itemsString);
log.trace("{} 计算完成耗时{}", tag, end - begin);
}
ThreadUtl.sleep((long) OpcConfig.synchronized_millisecond);
if (this.error_num != 0) {
this.error_num = 0;
this.message = null;
}
ThreadUtl.sleep((long) OpcConfig.synchronized_millisecond);
if (this.error_num != 0) {
this.error_num = 0;
this.message = null;
}
if (!valueAllNotNull) {
if (this.all_null < 3) {
if (log.isWarnEnabled()) {
log.warn("OPC数据源: {} 所有内容都为空,检查网络, all_null:{} ,暂定{}s", tag, all_null, 3);
}
while (var18.hasNext()) {
Item item = (Item) var18.next();
String itemId = item.getId();
OpcItemDto itemDto = this.getItem(itemId);
LuceneLogDto logDto = LuceneLogDto.builder()
.device_code("OPC数据源")
.content("OPC数据源:" + tag + "内容为:" + itemDto)
.build();
logDto.setLog_level(4);
luceneExecuteLogService.deviceExecuteLog(logDto);
}
ThreadUtl.sleep(3000);
break start;
} else if (this.all_null < 6) {
if (log.isWarnEnabled()) {
log.warn(tag + "重新创建server");
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null, 3);
}
ThreadUtl.sleep(3000);
break start;
} else if (this.all_null < 12) {
if (log.isWarnEnabled()) {
log.warn(tag + "重新创建server");
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null, 3);
}
ThreadUtl.sleep(3000);
break start;
} else {
if (log.isWarnEnabled()) {
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}ms", tag, all_null, 5000);
}
if (!valueAllNotNull) {
if (this.all_null < 3) {
if (log.isWarnEnabled()) {
log.warn("OPC数据源: {} 所有内容都为空,检查网络, all_null:{} ,暂定{}s", tag, all_null,3);
}
while (var18.hasNext()) {
Item item = (Item) var18.next();
String itemId = item.getId();
OpcItemDto itemDto = this.getItem(itemId);
LuceneLogDto logDto = LuceneLogDto.builder()
.device_code("OPC数据源")
.content("OPC数据源:" + tag + "内容为:" + all_null)
.content("OPC数据源:" + tag + "内容为:" + itemDto)
.build();
logDto.setLog_level(4);
luceneExecuteLogService.deviceExecuteLog(logDto);
ThreadUtl.sleep((long) (5000));
break start;
}
// ++this.all_null;
ThreadUtl.sleep( 3000);
break start;
} else if (this.all_null < 6) {
if (log.isWarnEnabled()) {
log.warn(tag + "重新创建server");
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,3);
}
ThreadUtl.sleep(3000);
break start;
} else if (this.all_null < 12) {
if (log.isWarnEnabled()) {
log.warn(tag + "重新创建server");
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,3);
}
ThreadUtl.sleep(3000);
break start;
} else {
this.all_null = 0;
if (log.isWarnEnabled()) {
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}ms", tag, all_null, 5000);
}
LuceneLogDto logDto = LuceneLogDto.builder()
.device_code("OPC数据源")
.content("OPC数据源:" + tag + "内容为:" + all_null)
.build();
logDto.setLog_level(4);
luceneExecuteLogService.deviceExecuteLog(logDto);
ThreadUtl.sleep((long) (5000));
break start;
}
// break start;
// ++this.all_null;
} else {
this.all_null = 0;
}
// break start;
}
log.warn("opc线程停止。。。");
@ -337,165 +316,68 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
private void runNew() {
try{
OpcUaClient client = createClient();
client.connect().get();
managedSubscriptionEvent(client);
} catch (Exception e){
e.printStackTrace();
}
}
// private final static String endPointUrl = "opc.tcp://127.0.0.1:49320";
private static OpcUaClient createClient() throws Exception {
ISysParamService paramService = SpringContextHolder.getBean(ISysParamService.class);
String endPointUrl = paramService.findByCode(AcsConfig.OPCURL).getValue();
if (StrUtil.isEmpty(endPointUrl)){
throw new BadRequestException("opc地址未配置!");
}
//opc ua服务端地址
Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
Files.createDirectories(securityTempDir);
if (!Files.exists(securityTempDir)) {
throw new Exception("unable to create security dir: " + securityTempDir);
}
return OpcUaClient.create(endPointUrl, endpoints -> endpoints.stream().filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri())).findFirst(), configBuilder -> configBuilder.setApplicationName(LocalizedText.english("eclipse milo opc-ua client")).setApplicationUri("urn:eclipse:milo:examples:client")
//访问方式
.setIdentityProvider(new AnonymousProvider()).setRequestTimeout(UInteger.valueOf(5000)).build());
}
/**
* 批量订阅
*
* @param client
* @throws Exception
*/
private void managedSubscriptionEvent(OpcUaClient client) throws Exception {
final CountDownLatch eventLatch = new CountDownLatch(1);
//添加订阅监听器,用于处理断线重连后的订阅问题
client.getSubscriptionManager().addSubscriptionListener(new DeviceOpcProtocolRunable.CustomSubscriptionListener(client));
//处理订阅业务
handlerNode(client);
//持续监听
eventLatch.await();
}
/**
* 处理订阅业务
*
* @param client OPC UA客户端
*/
public void handlerNode(OpcUaClient client) {
try {
//创建订阅
ManagedSubscription subscription = ManagedSubscription.create(client);
//你所需要订阅的key
List<String> key = new ArrayList<>();
List<String> itemsString = new ArrayList();
Iterator var3 = this.protocols.iterator();
while (var3.hasNext()) {
OpcItemDto protocol = (OpcItemDto) var3.next();
String item = protocol.getItem_code();
key.add(item);
}
List<NodeId> nodeIdList = new ArrayList<>();
for (String s : key) {
nodeIdList.add(new NodeId(2, s));
}
//监听
List<ManagedDataItem> dataItemList = subscription.createDataItems(nodeIdList);
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
if (!OpcStartTag.is_run) {
OpcStartTag.is_run = true;
}
for (ManagedDataItem managedDataItem : dataItemList) {
managedDataItem.addDataValueListener((t) -> {
if(ObjectUtil.isNotEmpty(managedDataItem.getNodeId().getIdentifier())){
//managedDataItem.getNodeId().getIdentifier() ZJXXHJ.ZJXXHJ.ZXQ_05.to_command
//System.out.println(managedDataItem.getNodeId().getIdentifier().toString() + ":" + t.getValue().getValue());
//需要判断连接是否正常
if( t.getStatusCode().isGood()){
//字符串存在为空的情况
if(ObjectUtil.isNotEmpty(t.getValue().getValue())){
if(!ObjectUtil.equal(accessor_value.getValue(managedDataItem.getNodeId().getIdentifier().toString()),t.getValue().getValue().toString())){
OpcItemDto itemDto = this.getItem(managedDataItem.getNodeId().getIdentifier().toString());
this.logItemChanged(managedDataItem.getNodeId().getIdentifier().toString(), accessor_value, OpcUtl.getValue(t.getValue().getValue()),itemDto);
accessor_value.setValue(managedDataItem.getNodeId().getIdentifier().toString(), OpcUtl.getValue(t.getValue().getValue()));
}
} else {
if(!ObjectUtil.equal(accessor_value.getValue(managedDataItem.getNodeId().getIdentifier().toString()),t.getValue().getValue())){
OpcItemDto itemDto = this.getItem(managedDataItem.getNodeId().getIdentifier().toString());
this.logItemChanged(managedDataItem.getNodeId().getIdentifier().toString(), accessor_value, OpcUtl.getValue(t.getValue()),itemDto);
accessor_value.setValue(managedDataItem.getNodeId().getIdentifier().toString(), OpcUtl.getValue(t.getValue().getValue()));
}
}
}
Async20Access accessor = null;
while (true) {
String opcGroupId = this.getOpcGroupID();
try {
if (this.server == null) {
// this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain());
this.server = OpcUtl.getServer(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain());
this.server.addStateListener(this);
accessor = new Async20Access(this.server, OpcConfig.synchronized_millisecond, true);
Iterator var9 = this.protocols.iterator();
while (var9.hasNext()) {
OpcItemDto protocol = (OpcItemDto) var9.next();
String itemId = protocol.getItem_code();
accessor.addItem(itemId, this);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 自定义订阅监听
*/
private class CustomSubscriptionListener implements UaSubscriptionManager.SubscriptionListener {
accessor.bind();
log.info("Async20Access bind {}", opcGroupId);
}
private OpcUaClient client;
Thread.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000));
} catch (Exception var8) {
if (accessor != null) {
try {
log.warn("Async20Access unbind {}", opcGroupId);
accessor.unbind();
} catch (Exception var7) {
var7.printStackTrace();
}
CustomSubscriptionListener(OpcUaClient client) {
this.client = client;
}
accessor = null;
}
@Override
public void onKeepAlive(UaSubscription subscription, DateTime publishTime) {
// System.out.println("onKeepAlive");
}
if (this.server != null) {
try {
this.server.disconnect();
} catch (Exception var6) {
}
@Override
public void onStatusChanged(UaSubscription subscription, StatusCode status) {
// System.out.println("onStatusChanged");
}
this.server = null;
}
@Override
public void onPublishFailure(UaException exception) {
// System.out.println("onPublishFailure");
}
if (var8 instanceof InterruptedException) {
log.warn("OPC 同步线程(%s)被中断", opcGroupId);
return;
}
@Override
public void onNotificationDataLost(UaSubscription subscription) {
// System.out.println("onNotificationDataLost");
}
log.warn("设备信息同步异常", var8);
ThreadUtl.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000));
String error_message = var8.getMessage();
if (error_message == null) {
error_message = var8.toString();
}
/**
* 重连时 尝试恢复之前的订阅失败时 会调用此方法
* @param uaSubscription 订阅
* @param statusCode 状态
*/
@Override
public void onSubscriptionTransferFailed(UaSubscription uaSubscription, StatusCode statusCode) {
System.out.println("恢复订阅失败 需要重新订阅");
//在回调方法中重新订阅
handlerNode(client);
++this.error_num;
if (this.error_num > 3 && !StrUtil.equals(this.message, error_message)) {
this.message = error_message;
}
}
}
}

2
acs/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcConfig.java

@ -17,5 +17,5 @@ public class OpcConfig {
/**
* OPC 数据同步是否采用回调机制实现之前是线程定期全部读效率低
*/
public static Boolean opc_item_read_using_callback = true;
public static Boolean opc_item_read_using_callback = false;
}

Loading…
Cancel
Save