This commit is contained in:
psh
2024-05-20 09:39:55 +08:00
parent 698b0c2bdc
commit 7539874c85
25 changed files with 601 additions and 249 deletions

View File

@@ -19,6 +19,7 @@ import org.nl.acs.opc.DeviceAppServiceImpl;
import org.nl.system.service.param.ISysParamService;
import org.nl.common.utils.CodeUtil;
import org.nl.config.SpringContextHolder;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.util.HashMap;
@@ -27,6 +28,7 @@ import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
@Lazy
public class NDCAgvServiceImpl implements NDCAgvService {
private final DeviceAppService deviceAppService;

View File

@@ -19,6 +19,7 @@ import org.nl.system.service.param.ISysParamService;
import org.nl.config.SpringContextHolder;
import org.nl.system.service.param.impl.SysParamServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.io.DataInputStream;
@@ -33,6 +34,7 @@ import static org.nl.acs.agv.server.impl.NDCAgvServiceImpl.Bytes2HexString;
@Slf4j
@Component
@Lazy
public class OneNDCSocketConnectionAutoRun extends AbstractAutoRunnable {
Socket s;

View File

@@ -24,11 +24,13 @@ import org.nl.acs.task.service.dto.TaskDto;
import org.nl.system.service.param.ISysParamService;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
@Slf4j
@Lazy
public class AcsToWmsServiceImpl implements AcsToWmsService {
@Autowired
ISysParamService paramService;

View File

@@ -26,6 +26,10 @@ public class Instruction extends InstructionDto implements Serializable {
public Instruction() {
}
public Instruction(InstructionDto instructionDto) {
BeanUtil.copyProperties(instructionDto,this, CopyOptions.create().setIgnoreNullValue(true));
}
public void copyFrom(Instruction source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}

View File

@@ -5,7 +5,6 @@ import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@@ -18,8 +17,6 @@ import org.apache.commons.lang3.ObjectUtils;
import org.nl.acs.AcsConfig;
import org.nl.acs.agv.server.MagicAgvService;
import org.nl.acs.agv.server.NDCAgvService;
import org.nl.acs.agv.server.XianGongAgvService;
import org.nl.acs.agv.server.ZheDaAgvService;
import org.nl.acs.auto.initial.ApplicationAutoInitial;
import org.nl.acs.device.domain.Device;
import org.nl.acs.device.service.DeviceService;
@@ -242,6 +239,7 @@ public class InstructionServiceImpl extends CommonServiceImpl<InstructionMapper,
if (!StrUtil.isEmpty(create_time) && !StrUtil.isEmpty(end_time)) {
wrapper.between(InstructionMybatis::getCreate_time,create_time,end_time);
}
wrapper.orderByDesc(InstructionMybatis::getCreate_time);
IPage<InstructionMybatis> insPage = instructionMapper.selectPage(queryPage,wrapper);
final JSONObject json = (JSONObject) JSON.toJSON(ConvertUtil.convertPage(insPage, InstructionDto.class));
return json;
@@ -452,27 +450,12 @@ public class InstructionServiceImpl extends CommonServiceImpl<InstructionMapper,
if (StrUtil.equals(shortPathsList.get(0).getType(), "1")) {
NDCAgvService ndcAgvService = SpringContextHolder.getBean(NDCAgvService.class);
ndcAgvService.sendAgvInstToNDC(task.getAgv_system_type(), dto);
} else if (StrUtil.equals(shortPathsList.get(0).getType(), "2")) {
ZheDaAgvService zheDaAgvService = SpringContextHolder.getBean(ZheDaAgvService.class);
HttpResponse result = zheDaAgvService.sendAgvInstToAgv(dto);
if (!ObjectUtils.isEmpty(result)) {
JSONObject jo = JSON.parseObject(result.body());
if (jo.getInteger("status") != 200) {
dto.setSend_status("2");
} else {
dto.setSend_status("1");
}
} else {
dto.setSend_status("2");
}
}
} catch(Exception e)
{
} catch (Exception e) {
dto.setSend_status("2");
e.printStackTrace();
log.error("");
}
// WQLObject wo = WQLObject.getWQLObject("acs_instruction");
// JSONObject json = (JSONObject) JSONObject.toJSON(dto);
// wo.insert(json);
@@ -825,7 +808,7 @@ public class InstructionServiceImpl extends CommonServiceImpl<InstructionMapper,
if (StrUtil.equals(task.getNext_device_code(), instnextdevice)) {
taskService.finish(task.getTask_id());
} else {
finishAndCreateNextInst((Instruction) entity);
finishAndCreateNextInst(new Instruction(entity));
}
}
@@ -995,23 +978,26 @@ public class InstructionServiceImpl extends CommonServiceImpl<InstructionMapper,
entity.setRoute_plan_code(task.getRoute_plan_code());
}
// != 0 1=NDC任务 2=RGV任务
if (StrUtil.equals(task.getAgv_system_type(), "1")
// != 0 为agv任务 1=magic 2=NDC 3=XZ,4=ZHEDA
if (StrUtil.equals(paramService.findByCode(AcsConfig.AGVTYPE).getValue(), "1")
&& !StrUtil.equals(entity.getSend_status(), "2")) {
// NDC agv指令不当场取消指令,需要等agv上报
if (!StrUtil.isEmpty(entity.getAgv_jobno())) {
ndcAgvService.deleteAgvInstToNDC((Instruction)entity);
}
MagicAgvService magicAgvService = SpringContextHolder.getBean(MagicAgvService.class);
magicAgvService.deleteAgvInst(entity.getInstruction_code());
flag = true;
} else if (StrUtil.equals(task.getAgv_system_type(), "2")) {
try {
ZheDaAgvService zheDaAgvService = SpringContextHolder.getBean(ZheDaAgvService.class);
zheDaAgvService.deleteZDAgvInst(entity.getInstruction_code());
}catch (Exception e){
log.error("下发浙大取消指令失败{}",e.getMessage());
} else if (StrUtil.equals(paramService.findByCode(AcsConfig.AGVTYPE).getValue(), "2")) {
// NDC agv指令不当场取消指令,需要等agv上报
if (!StrUtil.isEmpty(entity.getAgv_jobno())) {
ndcAgvService.deleteAgvInstToNDC(new Instruction(entity));
}
// } else {
flag = true;
// }
// } else if (StrUtil.equals(paramService.findByCode(AcsConfig.AGVTYPE).getValue(), "3")
// && !StrUtil.equals(entity.getSend_status(), "2")) {
// XianGongAgvService xianGongAgvService = SpringContextHolder.getBean(XianGongAgvService.class);
// xianGongAgvService.deleteXZAgvInst(entity.getInstruction_code());
// flag = true;
} else {
flag = true;
}

View File

@@ -15,13 +15,7 @@ import org.nl.acs.device_driver.driver.OpcDeviceDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
@Slf4j
@Service

View File

@@ -13,13 +13,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.*;
@Service
@Slf4j

View File

@@ -7,16 +7,8 @@ import org.nl.config.thread.TheadFactoryName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.*;
import java.util.concurrent.*;
@Component
@Slf4j

View File

@@ -4,12 +4,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
import eu.bitwalker.useragentutils.DeviceType;
import lombok.Data;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
@Data
public class DeviceManageDto {

View File

@@ -9,25 +9,14 @@ import org.nl.acs.udw.UnifiedDataAccessor;
import org.nl.acs.udw.UnifiedDataAccessorFactory;
import org.nl.acs.udw.UnifiedDataAppService;
import org.nl.config.SpringContextHolder;
import org.openscada.opc.lib.da.Async20Access;
import org.openscada.opc.lib.da.DataCallback;
import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ItemState;
import org.openscada.opc.lib.da.Server;
import org.openscada.opc.lib.da.ServerConnectionStateListener;
import org.openscada.opc.lib.da.*;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.*;
/**
* @author 20220102CG\noblelift
*/
@Slf4j
@Service
public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerConnectionStateListener {
@@ -369,6 +358,7 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
}
@Override
public void connectionStateChanged(boolean connected) {
if (!connected) {
this.server = null;
@@ -391,6 +381,7 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
}
@Override
public void changed(Item item, ItemState itemState) {
String itemId = item.getId();
@@ -435,7 +426,17 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
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});
} else {
if(his instanceof int[]){
if(!Arrays.equals((long[]) his, (long[]) value)){
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value});
}
} else if(his instanceof String){
if(!StrUtil.equals((CharSequence) his, (CharSequence) value)){
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value});
}
} else {
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value});
}
// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{}", new Object[]{itemId, his, value});
}
}

View File

@@ -1,83 +1,313 @@
package org.nl.acs.opc;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.NamedThreadFactory;
import org.nl.acs.auto.run.AbstractAutoRunnable;
import org.nl.acs.opc.service.dto.OpcServerManageDto;
import org.nl.acs.udw.UnifiedDataAccessor;
import org.nl.acs.udw.UnifiedDataAccessorFactory;
import org.nl.acs.udw.UnifiedDataAppService;
import org.nl.config.SpringContextHolder;
import org.nl.system.service.param.ISysParamService;
import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ItemState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.regex.Pattern;
/**
* OPC设备同步启动
*/
@Component
@Slf4j
public class DeviceOpcSynchronizeAutoRun extends AbstractAutoRunnable {
public static boolean isRun = false;
ExecutorService executorService = Executors.newCachedThreadPool();
static boolean isRun = true;
@Autowired
private DeviceAppService deviceAppService;
@Autowired
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() {
return DeviceOpcSynchronizeAutoRun.class.getSimpleName();
}
@Override
public String getName() {
return "opc设备同步器";
}
@Override
public void autoRun() throws Exception {
{
isRun = true;
Map<String, OpcServerManageDto> servers = this.opcServerManageService.queryAllServerMap();
Map<String, List<List<OpcItemDto>>> pros;
do{
Thread.sleep(1000L);
pros = this.deviceAppService.findAllFormatProtocolFromDriver();
}while (ObjectUtil.isEmpty(pros));
Set<String> keys = pros.keySet();
Iterator var4 = keys.iterator();
//代码执行一次
while (var4.hasNext()) {
String key = (String) var4.next();
List<List<OpcItemDto>> list = (List) pros.get(key);
OpcServerManageDto opcServer = (OpcServerManageDto) servers.get(key);
Iterator var8 = list.iterator();
while (var8.hasNext()) {
List<OpcItemDto> groupProtols = (List) var8.next();
DeviceOpcProtocolRunable runable = new DeviceOpcProtocolRunable();
runable.setProtocols(groupProtols);
runable.setOpcServer(opcServer);
this.executorService.submit(runable);
}
static Group getGroup(String opcCode) throws Exception {
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class);
return opcServerService.getServer(opcCode);
}
// 同步无光电设备信号
//Map<String, List<List<OpcItemDto>>> pros1 = this.deviceAppService.findAllFormatProtocolFromDriver();
//List<DeviceDriver> opcDrivers = this.deviceAppService.findDeviceDriver(DeviceDriver.class);
static void submitTimeLimitTask(Runnable runnable, String opcCode) {
CompletableFuture<Void> future = CompletableFuture.runAsync(runnable, executorService);
// try {
// future.get(10L, TimeUnit.SECONDS);
// } catch (InterruptedException var9) {
// Thread.currentThread().interrupt();
// } catch (ExecutionException var10) {
// var10.printStackTrace();
// } catch (TimeoutException var11) {
// itemCodeOpcItemDtoMapping.keySet().forEach((key) -> {
// udw.setValue(key, (Object) null);
// });
// canReadOpcValues = new ConcurrentHashMap<>();
// System.out.println("opc设备同步器 任务执行超时,取消任务...");
// future.cancel(true);
// } finally {
// canRefreshOpcEntity = true;
// if (opcCode != null) {
// canReadOpcValues.put(opcCode, true);
// }
//
// }
}
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;
opcServersConfig = this.opcServerManageService.queryAllServerMap();
executorService = this.createThreadPool();
opcCodeOpcEntityMapping = new ConcurrentHashMap();
itemCodeOpcItemDtoMapping.keySet().forEach((key) -> {
udw.setValue(key, (Object) null);
});
canRefreshOpcEntity = true;
canReadOpcValues.clear();
while (true) {
Thread.sleep(3000L);
this.refreshOpcEntity();
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) -> {
// return OpcUtl.getValue((Item)map.getKey(), (ItemState)map.getValue());
// }).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);
}
}
}
}
}
}
@Override
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();
}
}
public void after() {
isRun = false;
this.executorService.shutdownNow();
this.executorService = Executors.newCachedThreadPool();
OpcStartTag.is_run = false;
opcCodeOpcEntityMapping.values().forEach((opcEntity) -> {
opcEntity.cleanUdwCache();
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class);
opcServerService.cleanGroups(opcEntity.getOpcCode());
});
opcCodeOpcEntityMapping = new ConcurrentHashMap();
itemCodeOpcItemDtoMapping = new ConcurrentHashMap();
executorService.shutdownNow();
}
private void logItemChanged(String itemId, UnifiedDataAccessor accessor_value, Object value, OpcItemDto itemDto) {
ISysParamService paramService = SpringContextHolder.getBean(ISysParamService.class);
Object his = accessor_value.getValue(itemId);
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 = accessor_value.getValue(relate);
sb.append("key:" + relate + "value: " + obj + ";");
}
if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time") && !itemDto.getItem_code().endsWith("consumption")) {
// 存在上次点位值为null情况 则不记录日志
if(!(his instanceof Float) && !(value instanceof Float)){
log.info(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(),4, itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value));
// LuceneLogDto luceneLogDto = new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(),4, itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1),
// String.valueOf(his), String.valueOf(value));
// luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc());
// String logLevel = paramService.findByCode(AcsConfig.LOGLEVEL).getValue();
// if(StrUtil.isNotEmpty(logLevel) && isNumeric(logLevel) && (luceneLogDto.getLog_level() >= Integer.parseInt(logLevel))){
// log.info("{}", JSON.toJSONString(luceneLogDto));
// }
}
}
} else {
// if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time") && !itemDto.getItem_code().endsWith("consumption")) {
// if(!(his instanceof Float) && !(value instanceof Float)){
// LuceneLogDto luceneLogDto = 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));
// luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc());
// log.info("{}", JSON.toJSONString(luceneLogDto));
// }
// }
if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time") && !itemDto.getItem_code().endsWith("consumption")) {
log.info(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(),4, itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1), String.valueOf(his), String.valueOf(value));
// if(!(his instanceof Float) && !(value instanceof Float)){
// LuceneLogDto luceneLogDto = new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(),4, itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1),
// String.valueOf(his), String.valueOf(value));
// luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc());
// String logLevel = paramService.findByCode(AcsConfig.LOGLEVEL).getValue();
// if(StrUtil.isNotEmpty(logLevel) && isNumeric(logLevel) && (luceneLogDto.getLog_level() >= Integer.parseInt(logLevel))){
// log.info("{}", JSON.toJSONString(luceneLogDto));
// }
// }
}
}
}
static {
udw = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
canReadOpcValues = new ConcurrentHashMap();
opcCodeOpcEntityMapping = new ConcurrentHashMap();
}
public static boolean isNumeric(String str) {
return Pattern.compile("^[0-9]+$").matcher(str).matches();
}
}

View File

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

View File

@@ -18,4 +18,6 @@ public interface OpcServerService {
void writeInteger(String var1, ItemValue... var2);
void clearServer(String var1);
void cleanGroups(String var1);
}

View File

@@ -145,6 +145,24 @@ public class OpcServerServiceImpl implements OpcServerService, ApplicationAutoIn
this.groups.remove(code);
}
public void cleanGroups(String opcCode) {
Group group = (Group)this.groups.get(opcCode);
if (group != null) {
Server server = group.getServer();
try {
group.remove();
} catch (JIException var5) {
var5.printStackTrace();
}
this.groups.remove(opcCode);
server.disconnect();
this.servers.remove(opcCode);
}
}
public void writeInteger(String code, ItemValue... values) {
try {
Group group = this.getServer(code);

View File

@@ -3,22 +3,11 @@ package org.nl.acs.opc;
import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.core.IJIUnsigned;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIUnsignedByte;
import org.jinterop.dcom.core.JIUnsignedShort;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.core.*;
import org.nl.acs.device_driver.driver.ItemValue;
import org.nl.common.exception.BadRequestException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.AddFailedException;
import org.openscada.opc.lib.da.AutoReconnectController;
import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ItemState;
import org.openscada.opc.lib.da.Server;
import org.openscada.opc.lib.da.WriteRequest;
import org.openscada.opc.lib.da.*;
import java.util.ArrayList;
import java.util.Iterator;

View File

@@ -2,17 +2,9 @@ package org.nl.acs.opc.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.*;
import lombok.experimental.Accessors;
import org.nl.acs.common.base.CommonModel;

View File

@@ -2,17 +2,9 @@ package org.nl.acs.opc.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.*;
import lombok.experimental.Accessors;
import org.nl.acs.common.base.CommonModel;

View File

@@ -11,14 +11,7 @@ import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

View File

@@ -1,11 +1,7 @@
package org.nl.acs.opc.service.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;

View File

@@ -1,11 +1,7 @@
package org.nl.acs.opc.service.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;

View File

@@ -33,13 +33,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
* @author jiaolm

View File

@@ -56,6 +56,7 @@ import org.nl.common.utils.CodeUtil;
import org.nl.config.SpringContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@@ -79,6 +80,7 @@ import java.util.stream.Collectors;
*/
@Service
@Slf4j
@Lazy
// @CacheConfig(cacheNames = TaskService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TaskServiceImpl extends CommonServiceImpl<TaskMapper, Task> implements TaskService, ApplicationAutoInitial {

View File

@@ -7,8 +7,8 @@ spring:
db-type: com.alibaba.druid.pool.DruidDataSource
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
# url: jdbc:log4jdbc:mysql://${DB_HOST:192.168.81.252}:${DB_PORT:3306}/${DB_NAME:stand_acs}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:xftn_acs}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
username: ${DB_USER:generallu}
url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:tn_acs}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
username: ${DB_USER:root}
# password: ${DB_PWD:Root.123456}
password: ${DB_PWD:123456}
# 初始连接数

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 120 KiB

View File

@@ -6,9 +6,9 @@ spring:
druid:
db-type: com.alibaba.druid.pool.DruidDataSource
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:xftn_lms}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:tn_lms}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
# url: jdbc:log4jdbc:mysql://${DB_HOST:47.111.78.178}:${DB_PORT:3306}/${DB_NAME:stand_lms}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
username: ${DB_USER:generallu}
username: ${DB_USER:root}
password: ${DB_PWD:123456}
# password: ${DB_PWD:P@ssw0rd}
# 初始连接数