From c8f14aecd678707f88d410a7c23113ed57112e59 Mon Sep 17 00:00:00 2001 From: gengby <858962040@qq.com> Date: Tue, 9 Apr 2024 15:27:55 +0800 Subject: [PATCH] =?UTF-8?q?rev:=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nladmin-system/nlsso-server/pom.xml | 81 ++- .../nl/acs/common/AbstractDriverService.java | 61 -- .../org/nl/acs/common/IDriverService.java | 23 - ...ardCoveyorControlWithPlcScannerDevice.java | 33 - ...andardCoveyorControlWithScannerDevice.java | 33 - .../acs/common/StandardInspectSiteDevice.java | 24 - .../common/StandardOrdinarySiteDevice.java | 33 - .../standard_inspect/BaseDeviceDriver.java | 25 - .../standard_inspect/ItemProtocol.java | 63 -- .../nl/acs/device/rest/DeviceController.java | 19 + .../nl/acs/device/service/DeviceService.java | 6 + .../service/impl/DeviceServiceImpl.java | 170 +++-- .../device_driver/ArrayComparisonUtil.java | 72 +++ .../nl/acs/device_driver/ArrayConverter.java | 189 ++++++ .../acs/device_driver/BaseTagsDataReader.java | 233 +++++++ .../agv/xg_agv/XgagvDeviceDriver.java | 26 +- .../StandardAutodoorDeviceDriver.java | 23 +- .../BeltConveyorDeviceDriver.java | 51 +- .../WithStationDeviceDriver.java | 23 - .../DoubleBeltConveyorDeviceDriver.java | 54 +- .../DoubleStationStackerDeviceDriver.java | 22 +- .../conveyor/lnsh_station2/ItemProtocol.java | 72 +++ .../lnsh_station2/LnshStationDefination.java | 57 ++ .../LnshStationDeviceDriver.java | 167 +++++ .../SiemensConveyorDeviceDriver.java | 15 +- .../StandardCoveyorControlDeviceDriver.java | 19 +- ...eyorControlWithPlcScannerDeviceDriver.java | 15 +- ...CoveyorControlWithScannerDeviceDriver.java | 21 +- .../StandardInspectSiteDeviceDriver.java | 11 +- .../driver/AbstractDeviceDriver.java | 2 + .../driver/AbstractOpcDeviceDriver.java | 339 +++------- .../device_driver/driver/OpcDeviceDriver.java | 27 +- ...ConveyorWithScannerWeightDeviceDriver.java | 42 +- .../device_driver/rgv/RgvDeviceDriver.java | 2 +- .../StandardStackerDeviceDriver.java | 6 +- .../LampThreecolorDeviceDriver.java | 2 +- .../nl/acs/device_driver/xx/ItemProtocol.java | 64 ++ .../nl/acs/device_driver/xx/XxDefinition.java | 56 ++ .../device_driver/xx/XxxxDeviceDriver.java | 162 +++++ .../impl/DeviceExecuteLogServiceImpl.java | 1 - .../nl/acs/opc/DeviceOpcProtocolRunable.java | 461 -------------- .../acs/opc/DeviceOpcSynchronizeAutoRun.java | 85 --- .../src/main/java/org/nl/acs/opc/JsonUtl.java | 128 ---- .../main/java/org/nl/acs/opc/ObjectUtl.java | 70 --- .../java/org/nl/acs/opc/OpcServerService.java | 103 ++- .../org/nl/acs/opc/OpcServerServiceImpl.java | 486 +++++++-------- .../java/org/nl/acs/opc/OpcServerUtl.java | 48 +- .../src/main/java/org/nl/acs/opc/OpcUtl.java | 586 +++++++++--------- .../main/java/org/nl/acs/opc/domain/Opc.java | 35 +- .../org/nl/acs/opc/service/dto/OpcDto.java | 36 +- .../acs/opc/service/impl/OpcServiceImpl.java | 14 +- .../service/mapper/StorageCellMapper.java | 4 +- .../nl/acs/udw/mqttUdw/ItemsDataAccessor.java | 14 + .../acs/udw/mqttUdw/ItemsProcessService.java | 34 + .../factory/ItemDataAccessorFactory.java | 18 + .../factory/ItemsProcessServiceFactory.java | 17 + .../nl/acs/udw/mqttUdw/service/ItemData.java | 28 + .../nl/acs/udw/mqttUdw/service/ItemUnit.java | 22 + .../service/ItemsDataAccessorImpl.java | 39 ++ .../udw/mqttUdw/service/ItemsProcessImpl.java | 127 ++++ .../main/java/org/nl/acs/utils/ReadUtil.java | 324 +++++----- .../main/java/org/nl/config/RedisConfig.java | 20 + .../config/driver/ExcelTemplateCreator.java | 172 +++++ .../driver/GeneratorDriverTemplate.java | 385 ++++++++++++ .../java/org/nl/config/mqtt2/ItemUtil.java | 43 ++ .../java/org/nl/config/mqtt2/MqttService.java | 347 +++++++++++ .../nl/config/mqtt2/config/MqttConfig.java | 40 ++ .../java/org/nl/config/mqtt2/msg/Item.java | 16 + .../resources/config/application-dev2.yml | 195 ++++++ .../resources/config/application-prod.yml | 13 + .../src/main/resources/config/application.yml | 6 +- .../src/main/resources/logback-spring.xml | 5 +- nladmin-ui/src/api/acs/device/device.js | 46 +- nladmin-ui/src/i18n/langs/en.js | 1 + nladmin-ui/src/i18n/langs/in.js | 1 + nladmin-ui/src/i18n/langs/opc/en.js | 1 + nladmin-ui/src/i18n/langs/opc/in.js | 1 + nladmin-ui/src/i18n/langs/opc/zh.js | 1 + nladmin-ui/src/i18n/langs/zh-CN.js | 1 + .../acs/device/generation/UploadDialog.vue | 116 ++++ .../src/views/acs/device/generation/index.vue | 130 ++++ nladmin-ui/src/views/acs/device/opc/index.vue | 95 ++- 82 files changed, 4220 insertions(+), 2438 deletions(-) delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/AbstractDriverService.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/IDriverService.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithPlcScannerDevice.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithScannerDevice.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardInspectSiteDevice.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardOrdinarySiteDevice.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/BaseDeviceDriver.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/ItemProtocol.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayComparisonUtil.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayConverter.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/BaseTagsDataReader.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/ItemProtocol.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDefination.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDeviceDriver.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/ItemProtocol.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxDefinition.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxxxDeviceDriver.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcSynchronizeAutoRun.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/JsonUtl.java delete mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/ObjectUtl.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsDataAccessor.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsProcessService.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemDataAccessorFactory.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemsProcessServiceFactory.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemData.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemUnit.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsDataAccessorImpl.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsProcessImpl.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/ExcelTemplateCreator.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/GeneratorDriverTemplate.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/ItemUtil.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/MqttService.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/config/MqttConfig.java create mode 100644 nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/msg/Item.java create mode 100644 nladmin-system/nlsso-server/src/main/resources/config/application-dev2.yml create mode 100644 nladmin-ui/src/views/acs/device/generation/UploadDialog.vue create mode 100644 nladmin-ui/src/views/acs/device/generation/index.vue diff --git a/nladmin-system/nlsso-server/pom.xml b/nladmin-system/nlsso-server/pom.xml index ee3e714..0644044 100644 --- a/nladmin-system/nlsso-server/pom.xml +++ b/nladmin-system/nlsso-server/pom.xml @@ -374,38 +374,38 @@ commons-io 2.8.0 - - org.openscada.jinterop - org.openscada.jinterop.core - 2.1.8 - - - org.bouncycastle - bcprov-jdk15on - - - - - org.openscada.jinterop - org.openscada.jinterop.deps - 1.5.0 - - - org.bouncycastle - bcprov-jdk15on - - - - - org.openscada.utgard - org.openscada.opc.dcom - 1.5.0 - - - org.openscada.utgard - org.openscada.opc.lib - 1.5.0 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.bouncycastle @@ -445,6 +445,23 @@ xercesImpl 2.12.0 --> + + org.springframework.boot + spring-boot-starter-integration + + + org.springframework.integration + spring-integration-stream + + + org.springframework.integration + spring-integration-mqtt + + + com.hivemq + hivemq-mqtt-client + 1.3.3 + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/AbstractDriverService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/AbstractDriverService.java deleted file mode 100644 index edae461..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/AbstractDriverService.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.nl.acs.common; - -import com.alibaba.fastjson.JSONObject; -import org.nl.acs.device.domain.Device; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @param 抽象类 - * @author geng by - */ -public class AbstractDriverService implements IDriverService { - @Override - public JSONObject getDeviceInfo(Device device) { - return null; - } - - @Override - public Integer getDbValue(Device device, String dbName) { - return null; - } - - - public Integer getDbValue(T t, String dbName) { - Integer dbValue = 0; - try { - Class tClass = t.getClass(); - Method methodDb = tClass.getMethod("get" + dbName); - dbValue = (Integer) methodDb.invoke(t); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - return dbValue; - } - - - public JSONObject getCommonDeviceInfo(T t, int i, int j) { - JSONObject map = new JSONObject(); - try { - Class tClass = t.getClass(); - Method methodGetHasGoods = tClass.getMethod("getHasGoods"); - Method methodGetIsonline = tClass.getMethod("getIsonline"); - Integer hasGoods = (Integer) methodGetHasGoods.invoke(t); - Boolean isOnline = (Boolean) methodGetIsonline.invoke(t); - map.put("hasGoods", hasGoods); - map.put("isOnline", isOnline); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - return map; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/IDriverService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/IDriverService.java deleted file mode 100644 index 276788b..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/IDriverService.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.nl.acs.common; - -import com.alibaba.fastjson.JSONObject; -import org.nl.acs.device.domain.Device; - - -public interface IDriverService { - /** - * 获取设备监控信息 - * - * @param device - * @return - */ - JSONObject getDeviceInfo(Device device); - - /** - * getDbValue - * @param device - * @param dbName - * @return - */ - Integer getDbValue(Device device, String dbName); -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithPlcScannerDevice.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithPlcScannerDevice.java deleted file mode 100644 index d0b27a7..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithPlcScannerDevice.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.nl.acs.common; - -import cn.hutool.core.util.StrUtil; -import com.alibaba.fastjson.JSONObject; -import org.nl.acs.device.domain.Device; -import org.nl.acs.device_driver.conveyor.standard_conveyor_control_with_plcscanner.StandardCoveyorControlWithPlcScannerDeviceDriver; -import org.springframework.stereotype.Service; - -/** - * @author geng by - * 输送机-控制点-PLC扫码器 - */ -@Service("standard_conveyor_control_with_plcscanner") -public class StandardCoveyorControlWithPlcScannerDevice extends AbstractDriverService { - @Override - public JSONObject getDeviceInfo(Device device) { - StandardCoveyorControlWithPlcScannerDeviceDriver standardCoveyorControlWithPlcScannerDeviceDriver = (StandardCoveyorControlWithPlcScannerDeviceDriver) device.getDeviceDriver(); - JSONObject jo = super.getCommonDeviceInfo(standardCoveyorControlWithPlcScannerDeviceDriver, 0, 0); - jo.put("error", standardCoveyorControlWithPlcScannerDeviceDriver.getError()); - jo.put("isError", standardCoveyorControlWithPlcScannerDeviceDriver.getIserror()); - jo.put("height", standardCoveyorControlWithPlcScannerDeviceDriver.getHeight()); - jo.put("operation_type", standardCoveyorControlWithPlcScannerDeviceDriver.getOperation_type()); - jo.put("direction", standardCoveyorControlWithPlcScannerDeviceDriver.getDirection()); - jo.put("action", standardCoveyorControlWithPlcScannerDeviceDriver.getAction()); - jo.put("ioaction", standardCoveyorControlWithPlcScannerDeviceDriver.getIoaction()); - jo.put("container", StrUtil.isEmpty(standardCoveyorControlWithPlcScannerDeviceDriver.getBarcode()) ? "" : standardCoveyorControlWithPlcScannerDeviceDriver.getBarcode()); - jo.put("message", StrUtil.isEmpty(standardCoveyorControlWithPlcScannerDeviceDriver.getMessage()) ? "" : standardCoveyorControlWithPlcScannerDeviceDriver.getMessage()); - jo.put("requestSucess", standardCoveyorControlWithPlcScannerDeviceDriver.getRequireSucess().toString()); - jo.put("applySucess", standardCoveyorControlWithPlcScannerDeviceDriver.getApplySucess().toString()); - jo.put("instruction_message", standardCoveyorControlWithPlcScannerDeviceDriver.getInst_message()); - return jo; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithScannerDevice.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithScannerDevice.java deleted file mode 100644 index 0f09ae0..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardCoveyorControlWithScannerDevice.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.nl.acs.common; - -import cn.hutool.core.util.StrUtil; -import com.alibaba.fastjson.JSONObject; -import org.nl.acs.device.domain.Device; -import org.nl.acs.device_driver.conveyor.standard_conveyor_control_with_scanner.StandardCoveyorControlWithScannerDeviceDriver; -import org.springframework.stereotype.Service; - -/** - * @author geng by - * 输送机控制点-带扫描驱动 - */ -@Service("standard_conveyor_control_with_scanner") -public class StandardCoveyorControlWithScannerDevice extends AbstractDriverService { - - @Override - public JSONObject getDeviceInfo(Device device) { - StandardCoveyorControlWithScannerDeviceDriver standardCoveyorControlWithScannerDeviceDriver = (StandardCoveyorControlWithScannerDeviceDriver) device.getDeviceDriver(); - JSONObject jo = super.getCommonDeviceInfo(standardCoveyorControlWithScannerDeviceDriver, 0, 0); - jo.put("error", standardCoveyorControlWithScannerDeviceDriver.getError()); - jo.put("isError", standardCoveyorControlWithScannerDeviceDriver.getIserror()); - jo.put("action", standardCoveyorControlWithScannerDeviceDriver.getAction()); - try { - jo.put("container", StrUtil.isEmpty(standardCoveyorControlWithScannerDeviceDriver.barcode()) ? "" : standardCoveyorControlWithScannerDeviceDriver.barcode()); - } catch (Exception e) { - e.printStackTrace(); - } - jo.put("message", StrUtil.equals(standardCoveyorControlWithScannerDeviceDriver.getMessage(), "null") ? "" : standardCoveyorControlWithScannerDeviceDriver.getMessage()); - jo.put("requestSucess", standardCoveyorControlWithScannerDeviceDriver.getRequireSucess().toString()); - jo.put("applySucess", standardCoveyorControlWithScannerDeviceDriver.getApplySucess().toString()); - return jo; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardInspectSiteDevice.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardInspectSiteDevice.java deleted file mode 100644 index b419359..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardInspectSiteDevice.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.nl.acs.common; - -import com.alibaba.fastjson.JSONObject; -import org.nl.acs.device.domain.Device; -import org.nl.acs.device_driver.conveyor.standard_inspect_site.StandardInspectSiteDeviceDriver; -import org.springframework.stereotype.Service; - -/** - * @author geng by - * 检测站点 - */ -@Service("standard_inspect_site") -public class StandardInspectSiteDevice extends AbstractDriverService { - @Override - public JSONObject getDeviceInfo(Device device) { - StandardInspectSiteDeviceDriver standardInspectSiteDevicedriver = (StandardInspectSiteDeviceDriver) device.getDeviceDriver(); - JSONObject jo = super.getCommonDeviceInfo(standardInspectSiteDevicedriver, 0, 0); - jo.put("error", standardInspectSiteDevicedriver.getError()); - jo.put("isError", standardInspectSiteDevicedriver.getIserror()); - jo.put("container", standardInspectSiteDevicedriver.getContainer()); - jo.put("message", standardInspectSiteDevicedriver.getMessage()); - return jo; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardOrdinarySiteDevice.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardOrdinarySiteDevice.java deleted file mode 100644 index fddd360..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/common/StandardOrdinarySiteDevice.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.nl.acs.common; - -import com.alibaba.fastjson.JSONObject; -import org.nl.acs.device.domain.Device; -import org.nl.acs.device_driver.conveyor.standard_ordinary_site.StandardOrdinarySiteDeviceDriver; -import org.springframework.stereotype.Service; - -/** - * @author geng by - * 普通站点 - */ -@Service("standard_ordinary_site") -public class StandardOrdinarySiteDevice extends AbstractDriverService { - - @Override - public JSONObject getDeviceInfo(Device device) { - StandardOrdinarySiteDeviceDriver standardOrdinarySiteDeviceDriver = (StandardOrdinarySiteDeviceDriver) device.getDeviceDriver(); - JSONObject jo = new JSONObject(); - jo.put("container", standardOrdinarySiteDeviceDriver.getContainer()); - jo.put("hasGoods", standardOrdinarySiteDeviceDriver.getHasGoods()); - jo.put("isOnline", true); - //点击弹出 - jo.put("is_click", true); - jo.put("device_type", device.getDevice_type()); - jo.put("error", standardOrdinarySiteDeviceDriver.getError()); - jo.put("isError", standardOrdinarySiteDeviceDriver.getIserror()); - jo.put("container", standardOrdinarySiteDeviceDriver.getContainer()); - jo.put("message", standardOrdinarySiteDeviceDriver.getMessage()); - jo.put("material", standardOrdinarySiteDeviceDriver.getMaterial()); - jo.put("batch", standardOrdinarySiteDeviceDriver.getBatch()); - return jo; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/BaseDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/BaseDeviceDriver.java deleted file mode 100644 index 04f8d3b..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/BaseDeviceDriver.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.nl.acs.device.device_driver.standard_inspect; - -import lombok.extern.slf4j.Slf4j; -import org.nl.acs.device.domain.Device; -import org.nl.acs.device_driver.DeviceDriver; -import org.nl.acs.device_driver.driver.AbstractOpcDeviceDriver; -import org.nl.acs.device_driver.driver.ExecutableDeviceDriver; - -@Slf4j -public class BaseDeviceDriver extends AbstractOpcDeviceDriver implements DeviceDriver, ExecutableDeviceDriver { - protected ItemProtocol itemProtocol = new ItemProtocol(this); - - - @Override - public Device getDevice() { - return this.device; - } - - - @Override - public void execute() { - int mode = this.itemProtocol.getMode(); - log.info("驱动执行mode :" + mode); - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/ItemProtocol.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/ItemProtocol.java deleted file mode 100644 index 24304d7..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/device_driver/standard_inspect/ItemProtocol.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.nl.acs.device.device_driver.standard_inspect; - -import lombok.extern.slf4j.Slf4j; - -import java.util.ArrayList; -import java.util.List; - -@Slf4j -public class ItemProtocol { - public static String item_heartbeat = "heartbeat"; - public static String item_mode = "mode"; - public static String item_move = "move"; - public static String item_action = "action"; - public static String item_error = "error"; - public static String item_task = "task"; - public static String item_container_quantity = "container_quantity"; - public static String item_container_code = "container_code"; - public static String item_to_command = "to_command"; - public static String item_to_target = "to_target"; - public static String item_to_task = "to_task"; - public static String item_weight = "weight"; - - private BaseDeviceDriver driver; - - public ItemProtocol(BaseDeviceDriver driver) { - this.driver = driver; - } - - public int getMode() { - return this.getOpcIntegerValue(item_mode); - } - - public int getOpcIntegerValue(String protocol) { - Integer value = this.driver.getIntegeregerValue(protocol); - if (value == null) { - } else { - return value; - } - return 0; - - } - - public static List getReadableItemDtos() { - ArrayList list = new ArrayList(); - list.add(new ItemDto(item_heartbeat, "心跳", "DB100.B0")); - list.add(new ItemDto(item_mode, "工作状态", "DB100.B2", Boolean.valueOf(true))); - list.add(new ItemDto(item_move, "光电开关信号", "DB100.B3")); - list.add(new ItemDto(item_action, "动作信号", "DB100.B4")); - list.add(new ItemDto(item_error, "报警信号", "DB100.B5")); - list.add(new ItemDto(item_task, "任务号", "DB100.D6")); - return list; - } - - public static List getWriteableItemDtos() { - ArrayList list = new ArrayList(); - list.add(new ItemDto(item_to_command, "作业命令", "DB200.W2", Boolean.valueOf(true))); - list.add(new ItemDto(item_to_target, "目标站", "DB200.W4")); - list.add(new ItemDto(item_to_task, "任务号", "DB200.D6")); - return list; - } - -} - diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/rest/DeviceController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/rest/DeviceController.java index ef85d6d..0ef5da2 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/rest/DeviceController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/rest/DeviceController.java @@ -135,6 +135,12 @@ public class DeviceController { return new ResponseEntity<>(ja, HttpStatus.OK); } + @GetMapping("/getAllDriverCode") + @Log("获取所有的设备驱动信息") + public ResponseEntity getAllDriverCode(Pageable page) { + return new ResponseEntity<>(deviceService.getAllDriverCode(page), HttpStatus.OK); + } + @GetMapping({"/{device_code}"}) public ResponseEntity query(@PathVariable String device_code) { @@ -262,4 +268,17 @@ public class DeviceController { deviceService.excelImport(file, request); return new ResponseEntity<>(HttpStatus.OK); } + + @PostMapping("/uploadDriver") + @Log("excel导入驱动信息,自动生成驱动代码") + public ResponseEntity uploadDriver(@RequestParam("file") MultipartFile file, HttpServletRequest request) { + deviceService.uploadDriver(file, request); + return new ResponseEntity<>(HttpStatus.OK); + } + + @Log("导出生成驱动模板") + @GetMapping(value = "/getAllDriverCode/download") + public void templateDriver(HttpServletResponse response) throws IOException { + deviceService.templateDriver(response); + } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/DeviceService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/DeviceService.java index d0fb1a8..91cb982 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/DeviceService.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/DeviceService.java @@ -383,4 +383,10 @@ public interface DeviceService extends CommonService { * @return */ JSONArray selectDriverCodeList(String device_code); + + JSONObject getAllDriverCode(Pageable page); + + void uploadDriver(MultipartFile file, HttpServletRequest request); + + void templateDriver(HttpServletResponse response) throws IOException; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/impl/DeviceServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/impl/DeviceServiceImpl.java index e9c0500..035ce65 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/impl/DeviceServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device/service/impl/DeviceServiceImpl.java @@ -30,13 +30,15 @@ import org.nl.acs.device_driver.conveyor.belt_conveyor.BeltConveyorDeviceDriver; import org.nl.acs.device_driver.one_conveyor.scanner_weight_conveyor.ConveyorWithScannerWeightDeviceDriver; import org.nl.acs.device_driver.stacker.standard_stacker.StandardStackerDeviceDriver; import org.nl.acs.monitor.DeviceStageMonitor; +import org.nl.acs.opc.OpcConfig; import org.nl.acs.route.domain.RouteLine; import org.nl.acs.route.service.mapper.RouteLineMapper; import org.nl.acs.storage_cell.domain.StorageCell; import org.nl.acs.storage_cell.service.mapper.StorageCellMapper; +import org.nl.acs.udw.mqttUdw.ItemsDataAccessor; +import org.nl.acs.udw.mqttUdw.factory.ItemDataAccessorFactory; import org.nl.acs.utils.ConvertUtil; import org.nl.acs.utils.PageUtil; -import org.nl.acs.utils.ReadUtil; import org.nl.acs.device.service.DeviceDriverDefinationAppService; import org.nl.acs.device.service.DeviceExtraService; import org.nl.acs.device_driver.DeviceDriverDefination; @@ -66,14 +68,17 @@ import org.nl.acs.device.service.DeviceService; import org.nl.acs.device.service.dto.DeviceDto; import org.nl.acs.device.service.dto.DeviceQueryParam; import org.nl.acs.device.service.mapper.DeviceMapper; +import org.nl.config.driver.ExcelTemplateCreator; +import org.nl.config.driver.GeneratorDriverTemplate; import org.nl.config.language.LangProcess; +import org.nl.config.mqtt2.MqttService; import org.nl.system.service.dict.ISysDictService; import org.nl.system.service.dict.dao.Dict; import org.nl.system.service.logicflow.dao.mapper.StageMapper; import org.nl.system.service.param.ISysParamService; import org.nl.common.utils.CodeUtil; import org.nl.config.SpringContextHolder; -import org.openscada.opc.lib.da.Server; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; @@ -86,6 +91,7 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.*; +import java.util.stream.Collectors; /** * @author jiaolm @@ -114,6 +120,8 @@ public class DeviceServiceImpl extends CommonServiceImpl i private final DeviceDriverDefinationAppService deviceDriverDefinationAppService; private final DeviceAppService deviceAppService; private final ISysParamService paramService; + @Autowired + private MqttService mqttService; private final ISysDictService iSysDictService; List storageCells = new ArrayList<>(); @@ -330,14 +338,7 @@ public class DeviceServiceImpl extends CommonServiceImpl i @Override @Transactional(rollbackFor = Exception.class) public void deleteAll(String[] ids) { -// WQLObject wo = WQLObject.getWQLObject("acs_device"); -// WQLObject storageTab = WQLObject.getWQLObject("acs_storage_cell"); -// //路由路线表【acs_route_line】 -// WQLObject routeLineTab = WQLObject.getWQLObject("acs_route_line"); -// //路由路线表【stage_actor】 -// WQLObject stageActorTab = WQLObject.getWQLObject("stage_actor"); for (String device_id : ids) { -// JSONObject deviceJson = wo.query("device_id = '" + device_id + "'").uniqueResult(0); Device deviceJson = new LambdaQueryChainWrapper<>(deviceMapper) .eq(Device::getDevice_id, device_id) .one(); @@ -346,33 +347,13 @@ public class DeviceServiceImpl extends CommonServiceImpl i } String device_code = deviceJson.getDevice_code(); log.debug("删除设备时候判断路由是否存在,如果存在,则不允许删除设备!"); -// JSONObject json = routeLineTab.query("device_code = '" + device_code + "' or next_device_code = '" + device_code + "'").uniqueResult(0); - RouteLine json = new LambdaQueryChainWrapper<>(routeLineMapper) + List routeLines = new LambdaQueryChainWrapper<>(routeLineMapper) .eq(RouteLine::getDevice_code, device_code) .or().eq(RouteLine::getNext_device_code, device_code) - .one(); - if (json != null) { + .list(); + if (ObjectUtil.isNotEmpty(routeLines)) { throw new BadRequestException(LangProcess.msg("device_checkRoute", device_code)); } - log.debug("删除舞台里面的设备!"); -// Map map = new HashMap<>(); -// map.put("device_id", ""); -// map.put("device_code", ""); -// map.put("device_name", ""); -// stageActorTab.update(map, "device_code = '" + device_code + "'"); -// stageActorMapper.lambdaUpdate().eq(StageActor::getDevice_code,device_code) -// .set(StageActor::getDevice_code,"") -// .set(StageActor::getDevice_name,"") -// .update(); - log.debug("根据设备编码查询在缓存里面的舞台数据,并删除掉!"); -// JSONArray jsonArr = WQL.getWO("QStage_01").addParam("flag", "1").addParam("device_code", device_code).process().getResultJSONArray(0); - -// List stageList = stageMapper.selectByDeviceCode(device_code); -// for (int i = 0; i < stageList.size(); i++) { -// String stage_code = stageList.get(i).getStage_code(); -// redisUtils.del("stage:mst:" + stage_code); -// redisUtils.del("stage:dtl:" + stage_code); -// } log.debug("删除缓存里面的设备!"); Device deviceByCode = deviceAppService.findDeviceByCode(device_code); List allDevice = deviceAppService.findAllDevice(); @@ -389,23 +370,20 @@ public class DeviceServiceImpl extends CommonServiceImpl i log.info("设备删除成功!"); if (deviceByCode != null) { - if (StrUtil.equals("storage", deviceByCode.getDeviceDriverDefination().getFitDeviceTypes().get(0).name())) { -// storageTab.delete("substring_index( storage_code,'-',1)= '" + device_code + "'"); + DeviceDriverDefination deviceDriverDefination = deviceByCode.getDeviceDriverDefination(); + if (deviceDriverDefination != null && StrUtil.equals("storage", deviceDriverDefination.getFitDeviceTypes().get(0).name())) { storageCellMapper.deleteByStorageCode(device_code); } else { -// JSONObject data = storageTab.query("storage_code ='" + device_code + "'").uniqueResult(0); StorageCell storageCell = new LambdaQueryChainWrapper<>(storageCellMapper) .eq(StorageCell::getStorage_code, device_code) .one(); if (storageCell != null) { -// storageTab.delete("storage_code = '" + device_code + "'"); Map map = new HashMap<>(); map.put("storage_code", device_code); storageCellMapper.deleteByMap(map); } } } -// wo.delete("device_id = '" + device_id + "'"); Map map = new HashMap<>(); map.put("device_id", device_id); deviceMapper.deleteByMap(map); @@ -990,20 +968,20 @@ public class DeviceServiceImpl extends CommonServiceImpl i standardInspectSiteDeviceDriver.setBatch(batch); device.setMaterial_type(material_type); device.setBatch(batch); - } else if (device.getDeviceDriver() instanceof SiemensConveyorDeviceDriver) { + } else if (device.getDeviceDriver() instanceof SiemensConveyorDeviceDriver) { SiemensConveyorDeviceDriver siemensConveyorDeviceDriver = (SiemensConveyorDeviceDriver) device.getDeviceDriver(); siemensConveyorDeviceDriver.setDeviceStatus(form); } else if (device.getDeviceDriver() instanceof StandardCoveyorControlWithScannerDeviceDriver) { StandardCoveyorControlWithScannerDeviceDriver standardCoveyorControlWithScannerDeviceDriver = (StandardCoveyorControlWithScannerDeviceDriver) device.getDeviceDriver(); standardCoveyorControlWithScannerDeviceDriver.setDeviceStatus(form); - }else if (device.getDeviceDriver() instanceof StandardStackerDeviceDriver) { + } else if (device.getDeviceDriver() instanceof StandardStackerDeviceDriver) { StandardStackerDeviceDriver standardStackerDeviceDriver = (StandardStackerDeviceDriver) device.getDeviceDriver(); standardStackerDeviceDriver.setDeviceStatus(form); } else if (device.getDeviceDriver() instanceof ConveyorWithScannerWeightDeviceDriver) { ConveyorWithScannerWeightDeviceDriver conveyorWithScannerWeightDeviceDriver = (ConveyorWithScannerWeightDeviceDriver) device.getDeviceDriver(); conveyorWithScannerWeightDeviceDriver.setDeviceStatus(form); - }else if (device.getDeviceDriver() instanceof BeltConveyorDeviceDriver) { + } else if (device.getDeviceDriver() instanceof BeltConveyorDeviceDriver) { BeltConveyorDeviceDriver beltConveyorDeviceDriver = (BeltConveyorDeviceDriver) device.getDeviceDriver(); beltConveyorDeviceDriver.setDeviceStatus(form); } @@ -1268,47 +1246,65 @@ public class DeviceServiceImpl extends CommonServiceImpl i @Override public JSONArray testRead(Map map) { List dbItems = (List) map.get("dbItems"); - String opc_id = (String) map.get("opc_id"); - - List itemString = new ArrayList(); - - for (int i = 0; i < dbItems.size(); i++) { - Object ob = dbItems.get(i); - JSONObject json = (JSONObject) JSONObject.toJSON(ob); - itemString.add(json.getString("code")); - - } - Server server = ReadUtil.getServer(opc_id); - final Map readList = ReadUtil.read(itemString, server); +// String opc_id = (String) map.get("opc_id"); +// +// List itemString = new ArrayList(); +// +// for (int i = 0; i < dbItems.size(); i++) { +// Object ob = dbItems.get(i); +// JSONObject json = (JSONObject) JSONObject.toJSON(ob); +// itemString.add(json.getString("code")); +// +// } + ItemsDataAccessor accessor = ItemDataAccessorFactory.getItemsDataAccessor(OpcConfig.udw_opc_value_key); JSONArray result = new JSONArray(); for (int i = 0; i < dbItems.size(); i++) { Object ob = dbItems.get(i); JSONObject json = (JSONObject) JSONObject.toJSON(ob); String code = json.getString("code"); - if (readList.containsKey(code)) { - json.put("dbr_value", readList.get(code)); - } + json.put("dbr_value", accessor.getValue(code)); result.add(json); - } return result; + +// Server server = ReadUtil.getServer(opc_id); +// final Map readList = ReadUtil.read(itemString, server); +// +// JSONArray result = new JSONArray(); +// for (int i = 0; i < dbItems.size(); i++) { +// Object ob = dbItems.get(i); +// JSONObject json = (JSONObject) JSONObject.toJSON(ob); +// String code = json.getString("code"); +// if (readList.containsKey(code)) { +// json.put("dbr_value", readList.get(code)); +// } +// result.add(json); +// +// } +// return result; } @Override public void testWrite(Map map) { List dbItems = (List) map.get("dbItems"); - String opc_id = (String) map.get("opc_id"); - Map itemMap = new HashMap(); + List> list = new ArrayList<>(); + //String opc_id = (String) map.get("opc_id"); + // Map itemMap = new HashMap(); for (int i = 0; i < dbItems.size(); i++) { Object ob = dbItems.get(i); JSONObject json = (JSONObject) JSONObject.toJSON(ob); if (!StrUtil.isEmpty(json.getString("dbw_value"))) { - itemMap.put(json.getString("code"), json.getString("dbw_value")); + // itemMap.put(json.getString("code"), json.getString("dbw_value")); + Map valueMap = new HashMap<>(); + valueMap.put("id",json.getString("code")); + valueMap.put("v",json.get("dbw_value")); + list.add(valueMap); } } - Server server = ReadUtil.getServer(opc_id); - ReadUtil.write(itemMap, server); + mqttService.publishMessage(JSON.toJSONString(list)); + // Server server = ReadUtil.getServer(opc_id); + // ReadUtil.write(itemMap, server); } /** @@ -1882,13 +1878,13 @@ public class DeviceServiceImpl extends CommonServiceImpl i String in_device_name = null; String en_device_name = null; String zh_device_name = null; - if(list.size() > 6 && ObjectUtil.isNotEmpty(list.get(6))){ + if (list.size() > 6 && ObjectUtil.isNotEmpty(list.get(6))) { in_device_name = list.get(6).toString(); } - if(list.size() > 7 && ObjectUtil.isNotEmpty(list.get(7))){ + if (list.size() > 7 && ObjectUtil.isNotEmpty(list.get(7))) { en_device_name = list.get(7).toString(); } - if(list.size() > 8 && ObjectUtil.isNotEmpty(list.get(8))){ + if (list.size() > 8 && ObjectUtil.isNotEmpty(list.get(8))) { zh_device_name = list.get(8).toString(); } @@ -1911,13 +1907,13 @@ public class DeviceServiceImpl extends CommonServiceImpl i if (ObjectUtil.isNotEmpty(dto)) { continue; } - if(StrUtil.isEmpty(zh_device_name)){ + if (StrUtil.isEmpty(zh_device_name)) { zh_device_name = StrUtil.isNotEmpty(device_name) ? device_name : device_code; } - if(StrUtil.isEmpty(en_device_name)){ + if (StrUtil.isEmpty(en_device_name)) { en_device_name = StrUtil.isNotEmpty(device_name) ? device_name : device_code; } - if (StrUtil.isEmpty(in_device_name)){ + if (StrUtil.isEmpty(in_device_name)) { in_device_name = StrUtil.isNotEmpty(device_name) ? device_name : device_code; } //按照列获取 @@ -2014,4 +2010,44 @@ public class DeviceServiceImpl extends CommonServiceImpl i ja = JSONArray.parseArray(JSON.toJSONString(uniqueDriverSet)); return ja; } + + @Override + public JSONObject getAllDriverCode(Pageable page) { + List dictList = iSysDictService.getDictByName("device_type"); + Set uniqueDriverSet = new HashSet<>(); + dictList.forEach(dict -> { + List driverList = deviceDriverDefinationAppService.getDeviceDriverDefinations(DeviceType.getName(dict.getLabel())); + driverList.forEach( + deviceDriverDefination -> { + JSONObject jo = new JSONObject(); + jo.put("device_type", dict.getValue()); + jo.put("device_type_name", dict.getLabel()); + jo.put("driver_code", deviceDriverDefination.getDriverCode()); + jo.put("driver_name", deviceDriverDefination.getDriverName()); + jo.put("driver_description", deviceDriverDefination.getDriverDescription()); + uniqueDriverSet.add(jo); + } + ); + }); + List paginatedList = uniqueDriverSet.stream() + .sorted(Comparator.comparing(jsonObject -> jsonObject.getString("device_type"), Comparator.nullsLast(Comparator.naturalOrder()))) + .skip(page.getPageNumber() * page.getPageSize()) + .limit(page.getPageSize()) + .collect(Collectors.toList()); + + JSONObject result = new JSONObject(); + result.put("content", paginatedList); + result.put("totalElements", uniqueDriverSet.size()); + return result; + } + + @Override + public void uploadDriver(MultipartFile file, HttpServletRequest request) { + GeneratorDriverTemplate.generateClass(file); + } + + @Override + public void templateDriver(HttpServletResponse response) throws IOException { + ExcelTemplateCreator.createExcelTemplate(response); + } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayComparisonUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayComparisonUtil.java new file mode 100644 index 0000000..66eddd8 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayComparisonUtil.java @@ -0,0 +1,72 @@ +package org.nl.acs.device_driver; + +import cn.hutool.core.util.ObjectUtil; + +import java.util.Arrays; +import java.util.Objects; + +/** + * @Description TODO + * @Author Gengby + * @Date 2024/4/7 + */ +public class ArrayComparisonUtil { + public static boolean equals(Object oldValue, Object newValue) { + if (oldValue == null || newValue == null) { + return Objects.equals(oldValue, newValue); + } + Class oldType = oldValue.getClass(); + Class newType = newValue.getClass(); + if (oldType.isArray() && newType.isArray()) { + if (oldType.getComponentType().isArray() || newType.getComponentType().isArray()) { + return Arrays.deepEquals(new Object[]{newValue}, new Object[]{oldValue}); + } else { + if (oldValue instanceof Object[] && newValue instanceof Object[]) { + return Arrays.deepEquals((Object[]) oldValue, (Object[]) newValue); + } else if (oldValue instanceof int[] && newValue instanceof int[]) { + return Arrays.equals((int[]) oldValue, (int[]) newValue); + } else if (oldValue instanceof long[] && newValue instanceof long[]) { + return Arrays.equals((long[]) oldValue, (long[]) newValue); + } else if (oldValue instanceof short[] && newValue instanceof short[]) { + return Arrays.equals((short[]) oldValue, (short[]) newValue); + } else if (oldValue instanceof char[] && newValue instanceof char[]) { + return Arrays.equals((char[]) oldValue, (char[]) newValue); + } else if (oldValue instanceof byte[] && newValue instanceof byte[]) { + return Arrays.equals((byte[]) oldValue, (byte[]) newValue); + } else if (oldValue instanceof boolean[] && newValue instanceof boolean[]) { + return Arrays.equals((boolean[]) oldValue, (boolean[]) newValue); + } else if (oldValue instanceof float[] && newValue instanceof float[]) { + return Arrays.equals((float[]) oldValue, (float[]) newValue); + } else if (oldValue instanceof double[] && newValue instanceof double[]) { + return Arrays.equals((double[]) oldValue, (double[]) newValue); + } + } + } + return ObjectUtil.equals(oldValue, newValue); + } + + public static String arrayToString(Object array) { + if (array instanceof int[]) { + return Arrays.toString((int[]) array); + } else if (array instanceof double[]) { + return Arrays.toString((double[]) array); + } else if (array instanceof long[]) { + return Arrays.toString((long[]) array); + } else if (array instanceof char[]) { + return Arrays.toString((char[]) array); + } else if (array instanceof float[]) { + return Arrays.toString((float[]) array); + } else if (array instanceof boolean[]) { + return Arrays.toString((boolean[]) array); + } else if (array instanceof byte[]) { + return Arrays.toString((byte[]) array); + } else if (array instanceof short[]) { + return Arrays.toString((short[]) array); + } else if (array instanceof Object[]) { + return Arrays.deepToString((Object[]) array); + } else { + return Objects.toString(array, "null"); + } + } + +} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayConverter.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayConverter.java new file mode 100644 index 0000000..933b31f --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/ArrayConverter.java @@ -0,0 +1,189 @@ +package org.nl.acs.device_driver; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Arrays; +import java.util.function.Function; + +/** + * @Description TODO + * @Author Gengby + * @Date 2024/4/7 + */ +public interface ArrayConverter { + + static String replaceArrString(String value) { + return value.replaceAll("\\[|\\]", "").trim(); + } + + static int[] convertStringToArrayOfInt(String value) { + return Arrays.stream(preprocessInputString(value)) + .filter(s -> !s.isEmpty()) + .mapToInt(Integer::parseInt) + .toArray(); + } + + static Integer[] convertStringToArrayOfIntegerObject(String value) { + return Arrays.stream(preprocessInputString(value)) + .filter(s -> !s.isEmpty()) + .map(Integer::valueOf) + .toArray(Integer[]::new); + } + + static short[] convertStringToArrayOfShort(String value) { + String[] processed = preprocessInputString(value); + if (processed.length == 0) { + return new short[0]; + } + + short[] result = new short[processed.length]; + for (int i = 0; i < processed.length; i++) { + result[i] = Short.parseShort(processed[i].trim()); + } + return result; + } + + static Short[] convertStringToArrayOfShortObject(String value) { + return Arrays.stream(preprocessInputString(value)) + .filter(s -> !s.isEmpty()) + .map(s -> Short.parseShort(s.trim())) + .toArray(Short[]::new); + } + + static byte[] convertStringToArrayOfByte(String value) { + String[] processed = preprocessInputString(value); + if (processed.length == 0) { + return new byte[0]; + } + byte[] result = new byte[processed.length]; + for (int i = 0; i < processed.length; i++) { + result[i] = Byte.parseByte(processed[i].trim()); + } + return result; + } + + static Byte[] convertStringToArrayOfByteObject(String value) { + return Arrays.stream(preprocessInputString(value)) + .filter(s -> !s.isEmpty()) + .map(s -> Byte.parseByte(s.trim())) + .toArray(Byte[]::new); + } + + static long[] convertStringToArrayOfLong(String value) { + return Arrays.stream(preprocessInputString(value)) + .filter(s -> !s.isEmpty()) + .mapToLong(Long::parseLong) + .toArray(); + } + + static Long[] convertStringToArrayOfLongObject(String value) { + return Arrays.stream(preprocessInputString(value)) + .filter(s -> !s.isEmpty()) + .map(Long::valueOf) + .toArray(Long[]::new); + } + + static char[] convertStringToArrayOfChar(String value) { + if (value == null) { + return new char[0]; + } + return value.toCharArray(); + } + + public static Character[] convertStringToArrayOfCharacterObject(String value) { + if (value == null || value.isEmpty()) { + return new Character[0]; + } + return value.chars() + .mapToObj(c -> (char) c) + .toArray(Character[]::new); + } + + + static boolean[] convertStringToArrayOfBoolean(String value) { + String[] processed = preprocessInputString(value); + if (processed.length == 0) { + return new boolean[0]; + } + boolean[] result = new boolean[processed.length]; + for (int i = 0; i < processed.length; i++) { + result[i] = Boolean.parseBoolean(processed[i].trim()); + } + return result; + } + + static Boolean[] convertStringToArrayOfBooleanObject(String value) { + return Arrays.stream(preprocessInputString(value)) + .filter(s -> !s.isEmpty()) + .map(Boolean::valueOf) + .toArray(Boolean[]::new); + } + + static String[] convertStringToArrayOfString(String value) { + String[] stringArrays = preprocessInputString(value); + return Arrays.stream(stringArrays) + .map(s -> s.replaceAll("^\"|\"$", "")) + .toArray(String[]::new); + } + + static String[] preprocessInputString(String value) { + if (value == null || value.isEmpty() || value.matches("\\[?\\]?")) { + return new String[0]; + } + return value.replace("[", "").replace("]", "").split(","); + } + + static float[] convertStringToArrayOfFloat(String value, PrecisionLimiter limiter) { + Double[] intermediate = Arrays.stream(replaceArrString(value).split(",")) + .filter(s -> !s.isEmpty()) + .map(String::trim) + .map(s -> s.replaceAll("\"", "")) + .map(s -> limiter.apply(s).doubleValue()) + .toArray(Double[]::new); + float[] result = new float[intermediate.length]; + for (int i = 0; i < intermediate.length; i++) { + result[i] = intermediate[i].floatValue(); + } + return result; + } + + static Float[] convertStringToArrayOfFloatObject(String value, PrecisionLimiter limiter) { + return Arrays.stream(replaceArrString(value).split(",")) + .filter(s -> !s.isEmpty()) + .map(String::trim) + .map(s -> s.replaceAll("\"", "")) + .map(s -> Float.valueOf(limiter.apply(s).floatValue())) + .toArray(Float[]::new); + } + + static double[] convertStringToArrayOfDouble(String value, PrecisionLimiter limiter) { + return Arrays.stream(replaceArrString(value).split(",")) + .filter(s -> !s.isEmpty()) + .map(String::trim) + .map(s -> s.replaceAll("\"", "")) + .mapToDouble(s -> limiter.apply(s).doubleValue()) + .toArray(); + } + + static Double[] convertStringToArrayOfDoubleObject(String value, PrecisionLimiter limiter) { + return Arrays.stream(replaceArrString(value).split(",")) + .filter(s -> !s.isEmpty()) + .map(String::trim) + .map(s -> s.replaceAll("\"", "")) + .map(s -> Double.valueOf(limiter.apply(s).doubleValue())) + .toArray(Double[]::new); + } + + + static float limit2Places(String value) { + return BigDecimal.valueOf(Float.parseFloat(value)).setScale(2, RoundingMode.HALF_UP).floatValue(); + } + + static double limit4Places(String value) { + return BigDecimal.valueOf(Double.parseDouble(value)).setScale(4, RoundingMode.HALF_UP).doubleValue(); + } + + @FunctionalInterface + interface PrecisionLimiter extends Function { + } +} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/BaseTagsDataReader.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/BaseTagsDataReader.java new file mode 100644 index 0000000..99f89cd --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/BaseTagsDataReader.java @@ -0,0 +1,233 @@ +package org.nl.acs.device_driver; + +import com.alibaba.fastjson.JSON; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * @Description + * @Author Gengby + * @Date 2024/4/1 + */ +public interface BaseTagsDataReader { + + public static final Logger LOGGER = LoggerFactory.getLogger(BaseTagsDataReader.class); + + public static final boolean ENABLE_LOGGING_FLAG = true; + + public static final String PRE_LAST = "last"; + + public static final Map, Map> FIELD_CACHE = new ConcurrentHashMap<>(); + + public static final Map, Supplier> DEFAULT_VALUES_SUPPLIERS = createDefaultValuesSuppliers(); + + public static final List> LIMIT_CLASS_TYPE_LIST = Arrays.asList(double.class, Double.class, Float.class, float.class); + + public static final List> ARRAY_CLASS_TYPE_LIST = Arrays.asList(int[].class, Integer[].class, byte[].class, Byte[].class, short[].class, Short[].class, long[].class, Long[].class, float[].class, Float[].class, double[].class, Double[].class, char[].class, Character[].class, boolean[].class, Boolean[].class, String[].class); + + static Map, Supplier> createDefaultValuesSuppliers() { + Map, Supplier> defaultMap = new HashMap<>(); + + defaultMap.put(int.class, () -> 0); + defaultMap.put(Integer.class, () -> 0); + defaultMap.put(int[].class, () -> new int[0]); + defaultMap.put(Integer[].class, () -> new Integer[0]); + + defaultMap.put(double.class, () -> 0.0d); + defaultMap.put(Double.class, () -> 0.0d); + defaultMap.put(double[].class, () -> new double[0]); + defaultMap.put(Double[].class, () -> new Double[0]); + + defaultMap.put(long.class, () -> 0L); + defaultMap.put(Long.class, () -> 0L); + defaultMap.put(long[].class, () -> new long[0]); + defaultMap.put(Long[].class, () -> new Long[0]); + + defaultMap.put(boolean.class, () -> false); + defaultMap.put(Boolean.class, () -> Boolean.FALSE); + defaultMap.put(boolean[].class, () -> new boolean[0]); + defaultMap.put(Boolean[].class, () -> new Boolean[0]); + + defaultMap.put(byte.class, () -> (byte) 0); + defaultMap.put(Byte.class, () -> (byte) 0); + defaultMap.put(byte[].class, () -> new byte[0]); + defaultMap.put(Byte[].class, () -> new Byte[0]); + + defaultMap.put(char.class, () -> '\u0000'); + defaultMap.put(Character.class, () -> '\u0000'); + defaultMap.put(char[].class, () -> new char[0]); + defaultMap.put(Character[].class, () -> new Character[0]); + + defaultMap.put(short.class, () -> (short) 0); + defaultMap.put(Short.class, () -> (short) 0); + defaultMap.put(short[].class, () -> new short[0]); + defaultMap.put(Short[].class, () -> new Short[0]); + + defaultMap.put(float.class, () -> 0.0f); + defaultMap.put(Float.class, () -> 0.0f); + defaultMap.put(float[].class, () -> new float[0]); + defaultMap.put(Float[].class, () -> new Float[0]); + + defaultMap.put(String.class, () -> ""); + defaultMap.put(String[].class, () -> new String[0]); + + return defaultMap; + } + + static Map, Supplier> getLimitPlacesValue(Class filedType, T value) { + Map, Supplier> limitMap = new HashMap<>(); + Map, Function>> strategyMap = new HashMap<>(); + strategyMap.put(Double.class, v -> () -> ArrayConverter.limit4Places(String.valueOf(value))); + strategyMap.put(double.class, v -> () -> ArrayConverter.limit4Places(String.valueOf(value))); + strategyMap.put(Float.class, v -> () -> ArrayConverter.limit2Places(String.valueOf(value))); + strategyMap.put(float.class, v -> () -> ArrayConverter.limit2Places(String.valueOf(value))); + Optional.ofNullable(strategyMap.get(filedType)) + .map(func -> func.apply(value)) + .ifPresent(supplier -> limitMap.put(filedType, supplier)); + return limitMap; + } + + static Map, Supplier> getArrayValue(Class filedType, T value) { + Map, Supplier> arrayMap = new HashMap<>(); + Map, Function>> strategyMap = new HashMap<>(); + strategyMap.put(int[].class, v -> () -> ArrayConverter.convertStringToArrayOfInt(JSON.toJSONString(v))); + strategyMap.put(Integer[].class, v -> () -> ArrayConverter.convertStringToArrayOfIntegerObject(JSON.toJSONString(v))); + strategyMap.put(short[].class, v -> () -> ArrayConverter.convertStringToArrayOfShort(JSON.toJSONString(v))); + strategyMap.put(Short[].class, v -> () -> ArrayConverter.convertStringToArrayOfShortObject(JSON.toJSONString(v))); + strategyMap.put(byte[].class, v -> () -> ArrayConverter.convertStringToArrayOfByte(JSON.toJSONString(v))); + strategyMap.put(Byte[].class, v -> () -> ArrayConverter.convertStringToArrayOfByteObject(JSON.toJSONString(v))); + strategyMap.put(long[].class, v -> () -> ArrayConverter.convertStringToArrayOfLong(JSON.toJSONString(v))); + strategyMap.put(Long[].class, v -> () -> ArrayConverter.convertStringToArrayOfLongObject(JSON.toJSONString(v))); + strategyMap.put(char[].class, v -> () -> ArrayConverter.convertStringToArrayOfChar(JSON.toJSONString(v))); + strategyMap.put(Character[].class, v -> () -> ArrayConverter.convertStringToArrayOfCharacterObject(JSON.toJSONString(v))); + strategyMap.put(boolean[].class, v -> () -> ArrayConverter.convertStringToArrayOfBoolean(JSON.toJSONString(v))); + strategyMap.put(Boolean[].class, v -> () -> ArrayConverter.convertStringToArrayOfBooleanObject(JSON.toJSONString(v))); + strategyMap.put(String[].class, v -> () -> ArrayConverter.convertStringToArrayOfString(JSON.toJSONString(v))); + strategyMap.put(Double[].class, v -> () -> ArrayConverter.convertStringToArrayOfDoubleObject(JSON.toJSONString(v), ArrayConverter::limit4Places)); + strategyMap.put(double[].class, v -> () -> ArrayConverter.convertStringToArrayOfDouble(JSON.toJSONString(v), ArrayConverter::limit4Places)); + strategyMap.put(Float[].class, v -> () -> ArrayConverter.convertStringToArrayOfFloatObject(JSON.toJSONString(v), ArrayConverter::limit2Places)); + strategyMap.put(float[].class, v -> () -> ArrayConverter.convertStringToArrayOfFloat(JSON.toJSONString(v), ArrayConverter::limit2Places)); + Optional.ofNullable(strategyMap.get(filedType)) + .map(func -> func.apply(value)) + .ifPresent(supplier -> arrayMap.put(filedType, supplier)); + return arrayMap; + } + + + static T getDefaultPrimitiveValue(Class type) { + Supplier supplier = DEFAULT_VALUES_SUPPLIERS.get(type); + return (supplier != null) ? (T) supplier.get() : null; + } + + default & KeyProvider> void loadAssignData(String currentDeviceCode, Class enumClass) { + initializeFieldCache(this.getClass()); + + Map lastValues = new HashMap<>(); + Map fields = FIELD_CACHE.get(this.getClass()); + + for (E item : enumClass.getEnumConstants()) { + Field field = fields.get(item.getKey()); + if (field != null) { + try { + Object oldValue = field.get(this); + Object tempOldValue = null; + if (oldValue != null && field.getType().isArray()) { + int length = Array.getLength(oldValue); + tempOldValue = Array.newInstance(oldValue.getClass().getComponentType(), length); + } + Object tempValue = Optional.ofNullable(getOpcValue(item, field.getType())).orElse(getDefaultPrimitiveValue(field.getType())); + if (LIMIT_CLASS_TYPE_LIST.contains(field.getType())) { + tempValue = getLimitPlacesValue(field.getType(), tempValue).get(field.getType()).get(); + } else if (ARRAY_CLASS_TYPE_LIST.contains(field.getType()) && field.getType().isArray()) { + tempValue = getArrayValue(field.getType(), tempValue).get(field.getType()).get(); + } + Object newValue = Optional.ofNullable(tempValue).orElse(getDefaultPrimitiveValue(field.getType())); + if (ArrayComparisonUtil.equals(newValue, oldValue)) { + continue; + } + if (field.getType().isArray() && oldValue != null && newValue != null) { + int oldValueLength = Array.getLength(oldValue); + int newValueLength = Array.getLength(newValue); + if (oldValueLength == newValueLength) { + for (int i = 0; i < oldValueLength; i++) { + Object newElement = Array.get(newValue, i); + Array.set(oldValue, i, newElement); + } + } else { + ReflectionUtils.setField(field, this, newValue); + } + } else { + ReflectionUtils.setField(field, this, newValue); + } + if (ENABLE_LOGGING_FLAG && !field.getType().isArray()) { + setLog(item.getKey(), newValue, oldValue); + } else if (ENABLE_LOGGING_FLAG && field.getType().isArray()) { + setLog(item.getKey(), ArrayComparisonUtil.arrayToString(newValue), ArrayComparisonUtil.arrayToString(tempOldValue)); + } + lastValues.put(item.getKey(), newValue); + } catch (IllegalAccessException e) { + LOGGER.error("信号读取和赋值时出现异常: {}", e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage()); + } + } + } + + executeLogic(); + + lastValues.forEach((key, value) -> { + String lastFieldName = PRE_LAST + capitalize(key); + Field lastField = fields.get(lastFieldName); + if (lastField != null) { + try { + ReflectionUtils.setField(lastField, this, value); + } catch (Exception e) { + LOGGER.error("信号赋值时出现异常: {}", e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage()); + } + } + }); + } + + & KeyProvider, T> Object getOpcValue(E item, Class type); + + + default void initializeFieldCache(Class clazz) { + FIELD_CACHE.computeIfAbsent(clazz, k -> { + Map fields = new HashMap<>(); + Class currentClass = clazz; + while (currentClass != null) { + for (Field field : currentClass.getDeclaredFields()) { + ReflectionUtils.makeAccessible(field); + fields.put(field.getName(), field); + } + currentClass = currentClass.getSuperclass(); + } + return fields; + }); + } + + + default String capitalize(String str) { + if (str == null || str.isEmpty()) { + return str; + } + return Character.toUpperCase(str.charAt(0)) + str.substring(1); + } + + + void setLog(String key, Object newValue, Object oldValue); + + + void executeLogic(); + + + interface KeyProvider { + String getKey(); + } +} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/agv/xg_agv/XgagvDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/agv/xg_agv/XgagvDeviceDriver.java index 1785025..6de9e12 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/agv/xg_agv/XgagvDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/agv/xg_agv/XgagvDeviceDriver.java @@ -12,7 +12,6 @@ import org.nl.acs.common.base.CommonFinalParam; import org.nl.acs.device.domain.Device; import org.nl.acs.instruction.domain.Instruction; import org.nl.acs.instruction.enums.InstructionStatusEnum; -import org.nl.acs.utils.ReadUtil; import org.nl.acs.device_driver.DeviceDriver; import org.nl.acs.device_driver.conveyor.standard_inspect_site.StandardInspectSiteDeviceDriver; import org.nl.acs.device_driver.driver.AbstractOpcDeviceDriver; @@ -28,7 +27,6 @@ import org.nl.config.SpringContextHolder; import org.nl.config.language.LangProcess; import org.nl.config.lucene.service.LuceneExecuteLogService; import org.nl.config.lucene.service.dto.LuceneLogDto; -import org.openscada.opc.lib.da.Server; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; @@ -327,18 +325,18 @@ public class XgagvDeviceDriver extends AbstractOpcDeviceDriver implements Device public void writing(String key, int value) { - String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() - + "." + key; - String opcservcerid = this.getDevice().getOpc_server_id(); - Server server = ReadUtil.getServer(opcservcerid); - Map itemMap = new HashMap(); - itemMap.put(to_command, value); - LuceneLogDto resplogDto = LuceneLogDto.builder() - .device_code(device_code) - .content("下发信号" + this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.device_code + "." + key + "value:" + value) - .build(); - - ReadUtil.write(itemMap, server); +// String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() +// + "." + key; +// String opcservcerid = this.getDevice().getOpc_server_id(); +// Server server = ReadUtil.getServer(opcservcerid); +// Map itemMap = new HashMap(); +// itemMap.put(to_command, value); +// LuceneLogDto resplogDto = LuceneLogDto.builder() +// .device_code(device_code) +// .content("下发信号" + this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.device_code + "." + key + "value:" + value) +// .build(); +// +// ReadUtil.write(itemMap, server); } @Override diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/autodoor/standard_autodoor/StandardAutodoorDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/autodoor/standard_autodoor/StandardAutodoorDeviceDriver.java index edcfcfc..1fdb49f 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/autodoor/standard_autodoor/StandardAutodoorDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/autodoor/standard_autodoor/StandardAutodoorDeviceDriver.java @@ -10,9 +10,8 @@ import org.nl.acs.device_driver.driver.AbstractOpcDeviceDriver; import org.nl.acs.device_driver.driver.ExecutableDeviceDriver; import org.nl.acs.log.service.DeviceExecuteLogService; import org.nl.acs.monitor.DeviceStageMonitor; -import org.nl.acs.utils.ReadUtil; import org.nl.config.SpringContextHolder; -import org.openscada.opc.lib.da.Server; + import java.util.HashMap; import java.util.Map; @@ -84,20 +83,20 @@ public class StandardAutodoorDeviceDriver extends AbstractOpcDeviceDriver implem Map itemMap = new HashMap(); itemMap.put(to_param, Integer.parseInt(value)); - this.control(itemMap); + // this.control(itemMap); logServer.deviceExecuteLog(device_code, "", "", "下发电气信号设备号:" + device_code + ",下发电气:" + to_param + ",下发电气值:" + value); } public void writing(String param, int command) { - String to_command = String.format("%s.%s.%s.%s", this.getDevice().getOpc_server_code(), this.getDevice().getOpc_plc_code(), this.getDevice().getDevice_code(), param); - - String opcservcerid = this.getDevice().getOpc_server_id(); - Server server = ReadUtil.getServer(opcservcerid); - Map itemMap = new HashMap(); - itemMap.put(to_command, command); - ReadUtil.write(itemMap, server); - log.info("下发PLC信号:{},{}", to_command, command); - System.out.println("设备:" + this.device_code + ",下发PLC信号:" + to_command + ",value:" + command); +// String to_command = String.format("%s.%s.%s.%s", this.getDevice().getOpc_server_code(), this.getDevice().getOpc_plc_code(), this.getDevice().getDevice_code(), param); +// +// String opcservcerid = this.getDevice().getOpc_server_id(); +// Server server = ReadUtil.getServer(opcservcerid); +// Map itemMap = new HashMap(); +// itemMap.put(to_command, command); +// ReadUtil.write(itemMap, server); +// log.info("下发PLC信号:{},{}", to_command, command); +// System.out.println("设备:" + this.device_code + ",下发PLC信号:" + to_command + ",value:" + command); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_conveyor/BeltConveyorDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_conveyor/BeltConveyorDeviceDriver.java index 2e4f0e1..0c7ea20 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_conveyor/BeltConveyorDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_conveyor/BeltConveyorDeviceDriver.java @@ -350,13 +350,6 @@ public class BeltConveyorDeviceDriver extends AbstractOpcDeviceDriver implements } - public void writing(int command) { - String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() - + "." + org.nl.acs.device_driver.conveyor.standard_conveyor_control_with_scanner.ItemProtocol.item_to_command; - - Map itemMap = new HashMap(); - this.control(itemMap); - } public synchronized void applyAgvTask() { @@ -629,27 +622,27 @@ public class BeltConveyorDeviceDriver extends AbstractOpcDeviceDriver implements public void writing(List list) { - Map itemMap = new HashMap(); - for (int i = 0; i < list.size(); i++) { - Object ob = list.get(i); - JSONObject json = (JSONObject) JSONObject.toJSON(ob); - if (!StrUtil.isEmpty(json.getString("value"))) { - String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() - + "." + json.getString("code"); - itemMap.put(to_param, json.getString("value")); - } - } - logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); - try { - this.checkcontrol(itemMap); - } catch (Exception e) { - e.printStackTrace(); - try { - this.checkcontrol(itemMap); - } catch (Exception e1) { - e1.printStackTrace(); - } - } +// Map itemMap = new HashMap(); +// for (int i = 0; i < list.size(); i++) { +// Object ob = list.get(i); +// JSONObject json = (JSONObject) JSONObject.toJSON(ob); +// if (!StrUtil.isEmpty(json.getString("value"))) { +// String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() +// + "." + json.getString("code"); +// itemMap.put(to_param, json.getString("value")); +// } +// } +// logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e) { +// e.printStackTrace(); +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// } } @@ -663,7 +656,7 @@ public class BeltConveyorDeviceDriver extends AbstractOpcDeviceDriver implements itemMap.put(to_param, Integer.parseInt(param)); //itemMap.put(to_param, Integer.parseInt(value)); - this.control(itemMap); + // this.control(itemMap); logServer.deviceExecuteLog(device_code, "", "", "下发电气信号设备号:" + device_code + ",下发电气:" + to_param + ",下发电气值:" + param); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_with_station/WithStationDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_with_station/WithStationDeviceDriver.java index ee83d20..8abba3e 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_with_station/WithStationDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/belt_with_station/WithStationDeviceDriver.java @@ -179,29 +179,6 @@ public class WithStationDeviceDriver extends AbstractOpcDeviceDriver implements } - public void writing(Map map) { - DeviceExecuteLogService logServer = SpringContextHolder.getBean("deviceExecuteLogServiceImpl"); - Map itemMap = new LinkedHashMap<>(); - map.forEach((key, value) -> { - if (ObjectUtil.isNotEmpty(value)) { - itemMap.put(getToParam() + key, value); - } - }); - if (ObjectUtil.isNotEmpty(itemMap)) { - try { - this.checkcontrol(itemMap); - } catch (Exception e) { - e.printStackTrace(); - try { - this.checkcontrol(itemMap); - } catch (Exception e1) { - e1.printStackTrace(); - } - } - logServer.deviceExecuteLog(this.getDevice().getDevice_code(), "", "", "下发多个电气信号:" + itemMap); - } - } - public String getToParam() { return this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() + "."; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_belt_conveyor/DoubleBeltConveyorDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_belt_conveyor/DoubleBeltConveyorDeviceDriver.java index c40d496..911998f 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_belt_conveyor/DoubleBeltConveyorDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_belt_conveyor/DoubleBeltConveyorDeviceDriver.java @@ -294,38 +294,30 @@ public class DoubleBeltConveyorDeviceDriver extends AbstractOpcDeviceDriver impl } - public void writing(int command) { - String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() - + "." +ItemProtocol.item_to_command; - - Map itemMap = new HashMap(); - this.control(itemMap); - } - public void writing(List list) { - Map itemMap = new HashMap(); - for (int i = 0; i < list.size(); i++) { - Object ob = list.get(i); - JSONObject json = (JSONObject) JSONObject.toJSON(ob); - if (!StrUtil.isEmpty(json.getString("value"))) { - String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() - + "." + json.getString("code"); - itemMap.put(to_param, json.getString("value")); - } - } - logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); - try { - this.checkcontrol(itemMap); - } catch (Exception e) { - e.printStackTrace(); - try { - this.checkcontrol(itemMap); - } catch (Exception e1) { - e1.printStackTrace(); - } - } +// Map itemMap = new HashMap(); +// for (int i = 0; i < list.size(); i++) { +// Object ob = list.get(i); +// JSONObject json = (JSONObject) JSONObject.toJSON(ob); +// if (!StrUtil.isEmpty(json.getString("value"))) { +// String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() +// + "." + json.getString("code"); +// itemMap.put(to_param, json.getString("value")); +// } +// } +// logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e) { +// e.printStackTrace(); +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// } } @@ -534,7 +526,7 @@ public class DoubleBeltConveyorDeviceDriver extends AbstractOpcDeviceDriver impl } }); if (ObjectUtil.isNotEmpty(itemMap)) { - this.control(itemMap); + //this.control(itemMap); logServer.deviceExecuteLog(this.getDevice().getDevice_code(), "", "", "下发多个电气信号:" + itemMap); } } @@ -551,7 +543,7 @@ public class DoubleBeltConveyorDeviceDriver extends AbstractOpcDeviceDriver impl itemMap.put(to_param, Integer.parseInt(param)); //itemMap.put(to_param, Integer.parseInt(value)); - this.control(itemMap); + //this.control(itemMap); logServer.deviceExecuteLog(device_code, "", "", "下发电气信号设备号:" + device_code + ",下发电气:" + to_param + ",下发电气值:" + param); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_station_stacker/DoubleStationStackerDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_station_stacker/DoubleStationStackerDeviceDriver.java index efbcb06..c9b8288 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_station_stacker/DoubleStationStackerDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/double_station_stacker/DoubleStationStackerDeviceDriver.java @@ -829,16 +829,16 @@ public class DoubleStationStackerDeviceDriver extends AbstractOpcDeviceDriver im } } logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); - try { - this.checkcontrol(itemMap); - } catch (Exception e) { - e.printStackTrace(); - try { - this.checkcontrol(itemMap); - } catch (Exception e1) { - e1.printStackTrace(); - } - } +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e) { +// e.printStackTrace(); +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// } } public void writing(Map map) { @@ -850,7 +850,7 @@ public class DoubleStationStackerDeviceDriver extends AbstractOpcDeviceDriver im } }); if (ObjectUtil.isNotEmpty(itemMap)) { - this.control(itemMap); + //this.control(itemMap); logServer.deviceExecuteLog(this.getDevice().getDevice_code(), "", "", "下发多个电气信号:" + itemMap); } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/ItemProtocol.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/ItemProtocol.java new file mode 100644 index 0000000..5293ab2 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/ItemProtocol.java @@ -0,0 +1,72 @@ +package org.nl.acs.device_driver.conveyor.lnsh_station2; + +import org.nl.acs.device.device_driver.standard_inspect.ItemDto; +import org.nl.acs.device_driver.BaseTagsDataReader; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Description TODO + * @Author Gengby + * @Date 2024/4/1 + */ +public enum ItemProtocol implements BaseTagsDataReader.KeyProvider { + HEARTBEAT("heartbeat", "心跳", "DB81.B10"), + MODE("mode", "工作模式", "DB81.B1"), + MOVE("move", "光电开关信号", "DB81.B2"), + ACTION("action", "取放信号", "DB81.B3"), + IO_ACTION("ioAction", "进出信号", "DB81.B4"), + ERROR("error", "报警信号", "DB81.B5"), + TASK("task", "任务号", "DB81.D6"), + WEIGHT("weight", "重量", "DB81.D10"), + MATERIAL("material", "物料", "DB81.STRING14.50"), + BARCODE("barcode", "条码", "DB81.W66"), + + TO_COMMAND("toCommand", "下发作业命令", "DB71.W0"), + TO_TARGET("toTarget", "下发目标站", "DB71.W2"), + TO_TASK("toTask", "下发任务号", "DB71.D4"); + + private final String key; + private final String description; + private final String address; + + ItemProtocol(String key, String description, String address) { + this.key = key; + this.description = description; + this.address = address; + } + + @Override + public String getKey() { + return key; + } + + public String getDescription() { + return description; + } + + public String getAddress() { + return address; + } + + public static List getReadableItemDtos() { + List list = new ArrayList<>(); + for (ItemProtocol prop : values()) { + if (!prop.getKey().contains("to")) { + list.add(new ItemDto(prop.getKey(), prop.getDescription(), prop.getAddress())); + } + } + return list; + } + + public static List getWriteableItemDtos() { + List list = new ArrayList<>(); + for (ItemProtocol prop : values()) { + if (prop.getKey().contains("to")) { + list.add(new ItemDto(prop.getKey(), prop.getDescription(), prop.getAddress())); + } + } + return list; + } +} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDefination.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDefination.java new file mode 100644 index 0000000..cd7b3fe --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDefination.java @@ -0,0 +1,57 @@ +package org.nl.acs.device_driver.conveyor.lnsh_station2; + +import org.nl.acs.device.device_driver.standard_inspect.ItemDto; +import org.nl.acs.device.domain.Device; +import org.nl.acs.device.enums.DeviceType; +import org.nl.acs.device_driver.DeviceDriver; +import org.nl.acs.device_driver.defination.OpcDeviceDriverDefination; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Service +public class LnshStationDefination implements OpcDeviceDriverDefination { + @Override + public String getDriverCode() { + return "standard_station"; + } + + @Override + public String getDriverName() { + return "标准版-工位(交互模板)"; + } + + @Override + public String getDriverDescription() { + return "标准版-工位(交互模板)"; + } + + @Override + public DeviceDriver getDriverInstance(Device device) { + return (new LnshStationDeviceDriver()).setDevice(device).setDriverDefination(this); + } + + @Override + public Class getDeviceDriverType() { + return LnshStationDeviceDriver.class; + } + + @Override + public List getFitDeviceTypes() { + List types = new LinkedList(); + types.add(DeviceType.station); + return types; + } + + @Override + public List getReadableItemDtos() { + return ItemProtocol.getReadableItemDtos(); + } + + @Override + public List getWriteableItemDtos() { + return ItemProtocol.getWriteableItemDtos(); + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDeviceDriver.java new file mode 100644 index 0000000..41ae4f4 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/lnsh_station2/LnshStationDeviceDriver.java @@ -0,0 +1,167 @@ +package org.nl.acs.device_driver.conveyor.lnsh_station2; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.nl.acs.device.domain.Device; +import org.nl.acs.device_driver.BaseTagsDataReader; +import org.nl.acs.device_driver.DeviceDriver; +import org.nl.acs.device_driver.RouteableDeviceDriver; +import org.nl.acs.device_driver.StandardRequestMethod; +import org.nl.acs.device_driver.driver.AbstractOpcDeviceDriver; +import org.nl.acs.device_driver.driver.ExecutableDeviceDriver; +import org.nl.acs.monitor.DeviceStageMonitor; +import org.nl.config.SpringContextHolder; +import org.nl.config.lucene.service.LuceneExecuteLogService; +import org.nl.config.lucene.service.dto.LuceneLogDto; + +import java.util.Date; + +@Slf4j +@Getter +@Setter +@RequiredArgsConstructor +public class LnshStationDeviceDriver extends AbstractOpcDeviceDriver implements + DeviceDriver, + ExecutableDeviceDriver, + RouteableDeviceDriver, + DeviceStageMonitor, + StandardRequestMethod, + BaseTagsDataReader { + + + private final LuceneExecuteLogService logService = SpringContextHolder.getBean(LuceneExecuteLogService.class); + + + /** + * 心跳 + */ + private int heartbeat = 0; + private int lastHeartbeat = 0; + + /** + * 工作模式 + */ + private int mode = 0; + private int lastMode = 0; + + /** + * 光电信号 + */ + private int move = 0; + private int lastMove = 0; + + /** + * 取放信号 + */ + private int action = 0; + private int lastAction = 0; + + /** + * 进出信号 + */ + private int ioAction; + private int lastIoAction = 0; + + /** + * 报警信号 + */ + private Float[] error; + private Float[] lastError; + + /** + * 任务号 + */ + private String[] task; + private String[] lastTask; + + /** + * 重量 + */ + private double[] weight; + private double[] lastWeight; + + /** + * 物料信息 + */ + private String material = ""; + private String lastMaterial = ""; + + /** + * 条码信息 + */ + private int barcode = 0; + private int lastBarcode = 0; + + /** + * 当前设备编号 + */ + private String currentDeviceCode; + + /** + * 消息 + */ + private String message; + + /** + * 请求标记 + */ + boolean requireSuccess = false; + + /** + * 请求时间 + */ + private Date requireTime = new Date(); + + /** + * 请求间隔时间 + */ + private long requireTimeOut = 3000L; + + + @Override + public Device getDevice() { + return this.device; + } + + + @Override + public & KeyProvider, T> T getOpcValue(E item, Class fieldClassType) { + return (T) this.getValue(item.getKey()); + } + + + @Override + public void setLog(String key, Object newValue, Object oldValue) { + logService.deviceExecuteLog(new LuceneLogDto(this.currentDeviceCode, "自动线程读取信号:" + key + ",由" + oldValue + "->" + newValue)); + } + + + @Override + public void execute() { + this.currentDeviceCode = this.getDeviceCode(); + this.loadAssignData(currentDeviceCode, ItemProtocol.class); + } + + + @Override + public void executeLogic() { + //编写业务逻辑方法 + } + + + @Override + public JSONObject getDeviceStatusName() throws Exception { + return null; + } + + + @Override + public void setDeviceStatus(JSONObject data) { + + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/siemens_conveyor/SiemensConveyorDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/siemens_conveyor/SiemensConveyorDeviceDriver.java index 47c38b9..8f69e4f 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/siemens_conveyor/SiemensConveyorDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/siemens_conveyor/SiemensConveyorDeviceDriver.java @@ -42,7 +42,6 @@ import org.nl.common.utils.SecurityUtils; import org.nl.config.language.LangProcess; import org.nl.system.service.param.ISysParamService; import org.nl.config.SpringContextHolder; -import org.openscada.opc.lib.da.Server; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; @@ -424,14 +423,6 @@ public class SiemensConveyorDeviceDriver extends AbstractOpcDeviceDriver impleme } - protected void thingToNothing() throws Exception { - requireSucess = false; - } - - - public void executing(Server server, Map itemMap) { - this.control(itemMap); - } @Override public JSONObject getDeviceStatusName() { @@ -525,11 +516,11 @@ public class SiemensConveyorDeviceDriver extends AbstractOpcDeviceDriver impleme } logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); try { - this.checkcontrol(itemMap); + //this.checkcontrol(itemMap); } catch (Exception e) { e.printStackTrace(); try { - this.checkcontrol(itemMap); + // this.checkcontrol(itemMap); } catch (Exception e1) { e1.printStackTrace(); } @@ -545,7 +536,7 @@ public class SiemensConveyorDeviceDriver extends AbstractOpcDeviceDriver impleme Map itemMap = new HashMap(); itemMap.put(to_param, Integer.parseInt(value)); - this.control(itemMap); + //this.control(itemMap); logServer.deviceExecuteLog(device_code, "", "", "下发电气信号设备号:" + device_code + ",下发电气:" + to_param + ",下发电气值:" + value); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control/StandardCoveyorControlDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control/StandardCoveyorControlDeviceDriver.java index 2508bf7..efee9b9 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control/StandardCoveyorControlDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control/StandardCoveyorControlDeviceDriver.java @@ -34,7 +34,6 @@ import org.nl.acs.utils.ConvertUtil; import org.nl.system.service.param.ISysParamService; import org.nl.common.utils.CodeUtil; import org.nl.config.SpringContextHolder; -import org.openscada.opc.lib.da.Server; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; @@ -312,13 +311,7 @@ public class StandardCoveyorControlDeviceDriver extends AbstractOpcDeviceDriver } - public boolean exe_business() { - return true; - } - protected void executing(Instruction instruction) { - this.executing(1, instruction, ""); - } public void executing(int command, Instruction instruction, String appendMessage) { String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() @@ -338,14 +331,10 @@ public class StandardCoveyorControlDeviceDriver extends AbstractOpcDeviceDriver Map itemMap = new HashMap(); itemMap.put(to_command, 1); itemMap.put(to_task, instruction_num); - this.control(itemMap); + //this.control(itemMap); } - public void executing(Server server, Map itemMap) { - this.control(itemMap); - } - public void writing(int command) { String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() + "." + ItemProtocol.item_to_command; @@ -354,7 +343,7 @@ public class StandardCoveyorControlDeviceDriver extends AbstractOpcDeviceDriver //Server server = ReadUtil.getServer(opcservcerid); Map itemMap = new HashMap(); itemMap.put(to_command, command); - this.control(itemMap); + //this.control(itemMap); } @@ -372,7 +361,7 @@ public class StandardCoveyorControlDeviceDriver extends AbstractOpcDeviceDriver itemMap.put(to_command, command); itemMap.put(to_target, target); itemMap.put(to_task, task); - this.control(itemMap); + // this.control(itemMap); } public void writing(int type, int command) { @@ -393,7 +382,7 @@ public class StandardCoveyorControlDeviceDriver extends AbstractOpcDeviceDriver } else if (type == 3) { itemMap.put(to_task, command); } - this.control(itemMap); + // this.control(itemMap); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_plcscanner/StandardCoveyorControlWithPlcScannerDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_plcscanner/StandardCoveyorControlWithPlcScannerDeviceDriver.java index 8b417ac..ea3f5d6 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_plcscanner/StandardCoveyorControlWithPlcScannerDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_plcscanner/StandardCoveyorControlWithPlcScannerDeviceDriver.java @@ -36,7 +36,6 @@ import org.nl.acs.utils.ConvertUtil; import org.nl.common.utils.SecurityUtils; import org.nl.system.service.param.ISysParamService; import org.nl.config.SpringContextHolder; -import org.openscada.opc.lib.da.Server; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @@ -555,14 +554,10 @@ public class StandardCoveyorControlWithPlcScannerDeviceDriver extends AbstractOp Map itemMap = new HashMap(); itemMap.put(to_command, 1); itemMap.put(to_task, instruction_num); - this.control(itemMap); + // this.control(itemMap); } - public void executing(Server server, Map itemMap) { - this.control(itemMap); - } - public void writing() { String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() @@ -577,7 +572,7 @@ public class StandardCoveyorControlWithPlcScannerDeviceDriver extends AbstractOp itemMap.put(to_command, 1); itemMap.put(to_target, deviceAppservice.findDeviceByCode(inst.getNext_device_code()).getAddress()); itemMap.put(to_task, inst.getInstruction_code()); - this.control(itemMap); + //this.control(itemMap); } public void writing(int command, int target, int task) { @@ -595,7 +590,7 @@ public class StandardCoveyorControlWithPlcScannerDeviceDriver extends AbstractOp itemMap.put(to_target, target); itemMap.put(to_task, task); - this.control(itemMap); + //this.control(itemMap); // this.control(itemMap); } @@ -607,7 +602,7 @@ public class StandardCoveyorControlWithPlcScannerDeviceDriver extends AbstractOp //Server server = ReadUtil.getServer(opcservcerid); Map itemMap = new HashMap(); itemMap.put(to_command, command); - this.control(itemMap); + //this.control(itemMap); } public void writing(int type, int command) { @@ -629,7 +624,7 @@ public class StandardCoveyorControlWithPlcScannerDeviceDriver extends AbstractOp itemMap.put(to_task, command); } - this.control(itemMap); + // this.control(itemMap); } public boolean instruction_require(String container_code) { diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_scanner/StandardCoveyorControlWithScannerDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_scanner/StandardCoveyorControlWithScannerDeviceDriver.java index f2e2c7d..29781ea 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_scanner/StandardCoveyorControlWithScannerDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_conveyor_control_with_scanner/StandardCoveyorControlWithScannerDeviceDriver.java @@ -36,7 +36,6 @@ import org.nl.common.utils.SecurityUtils; import org.nl.config.language.LangProcess; import org.nl.system.service.param.ISysParamService; import org.nl.config.SpringContextHolder; -import org.openscada.opc.lib.da.Server; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; @@ -375,16 +374,6 @@ public class StandardCoveyorControlWithScannerDeviceDriver extends AbstractOpcDe } - public void set_last_container_type_desc(String type) { - } - - public boolean exe_business() { - return true; - } - - public void executing(Server server, Map itemMap) { - this.control(itemMap); - } public void writing(int command, int target, int task) { @@ -401,7 +390,7 @@ public class StandardCoveyorControlWithScannerDeviceDriver extends AbstractOpcDe itemMap.put(to_target, target); itemMap.put(to_task, task); - this.control(itemMap); + //this.control(itemMap); } public void writing(int command) { @@ -411,7 +400,7 @@ public class StandardCoveyorControlWithScannerDeviceDriver extends AbstractOpcDe //Server server = ReadUtil.getServer(opcservcerid); Map itemMap = new HashMap(); itemMap.put(to_command, command); - this.control(itemMap); + // this.control(itemMap); } public void writing(int type, int command) { @@ -434,7 +423,7 @@ public class StandardCoveyorControlWithScannerDeviceDriver extends AbstractOpcDe } - this.control(itemMap); + // this.control(itemMap); } public boolean instruction_require(String container_code) { @@ -786,7 +775,7 @@ public class StandardCoveyorControlWithScannerDeviceDriver extends AbstractOpcDe itemMap.put(to_param, Integer.parseInt(value)); // itemMap.put(to_param, Integer.parseInt(value)); - this.control(itemMap); + // this.control(itemMap); } @@ -805,7 +794,7 @@ public class StandardCoveyorControlWithScannerDeviceDriver extends AbstractOpcDe } } logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); - this.control(itemMap); + // this.control(itemMap); } @Override diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_inspect_site/StandardInspectSiteDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_inspect_site/StandardInspectSiteDeviceDriver.java index f863371..07bb5e8 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_inspect_site/StandardInspectSiteDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/conveyor/standard_inspect_site/StandardInspectSiteDeviceDriver.java @@ -28,7 +28,6 @@ import org.nl.acs.task.service.mapper.TaskMapper; import org.nl.acs.utils.ConvertUtil; import org.nl.common.utils.CodeUtil; import org.nl.config.SpringContextHolder; -import org.openscada.opc.lib.da.Server; import java.util.Date; import java.util.HashMap; @@ -318,14 +317,10 @@ public class StandardInspectSiteDeviceDriver extends AbstractOpcDeviceDriver imp Map itemMap = new HashMap(); itemMap.put(to_command, 1); itemMap.put(to_task, instruction_num); - this.control(itemMap); + //this.control(itemMap); } - public void executing(Server server, Map itemMap) { - this.control(itemMap); - } - public void writing(int command) { String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() + "." + ItemProtocol.item_to_command; @@ -334,7 +329,7 @@ public class StandardInspectSiteDeviceDriver extends AbstractOpcDeviceDriver imp //Server server = ReadUtil.getServer(opcservcerid); Map itemMap = new HashMap(); itemMap.put(to_command, command); - this.control(itemMap); + // this.control(itemMap); } @@ -356,7 +351,7 @@ public class StandardInspectSiteDeviceDriver extends AbstractOpcDeviceDriver imp } else if (type == 3) { itemMap.put(to_task, command); } - this.control(itemMap); + // this.control(itemMap); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractDeviceDriver.java index f475d7e..702af66 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractDeviceDriver.java @@ -12,6 +12,8 @@ public class AbstractDeviceDriver implements DeviceDriver { private DeviceDriverDefination driverDefination; private boolean stop = false; + public Boolean online; + public AbstractDeviceDriver() { // this.execute_log = new BusinessLoggerImpl(BusinessDomain.device_execute.name()); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractOpcDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractOpcDeviceDriver.java index 530bc77..232ce8b 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractOpcDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/AbstractOpcDeviceDriver.java @@ -1,280 +1,117 @@ package org.nl.acs.device_driver.driver; +import com.alibaba.fastjson.JSON; import org.nl.acs.opc.*; -import org.nl.acs.udw.UnifiedDataAccessor; -import org.nl.acs.udw.UnifiedDataAccessorFactory; -import org.nl.acs.udw.UnifiedDataAppService; +import org.nl.acs.udw.mqttUdw.ItemsDataAccessor; +import org.nl.acs.udw.mqttUdw.factory.ItemDataAccessorFactory; +import org.nl.common.exception.BadRequestException; import org.nl.config.SpringContextHolder; -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.nl.config.lucene.service.LuceneExecuteLogService; +import org.nl.config.lucene.service.dto.LuceneLogDto; +import org.nl.config.mqtt2.MqttService; import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public class AbstractOpcDeviceDriver extends AbstractDeviceDriver implements OpcDeviceDriver { - UnifiedDataAccessor opcUdw; - private OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class); + private final MqttService mqttService = SpringContextHolder.getBean(MqttService.class); + private final LuceneExecuteLogService luceneExecuteLogService = SpringContextHolder.getBean(LuceneExecuteLogService.class); + + private final ItemsDataAccessor opcUdw; public AbstractOpcDeviceDriver() { - this.opcUdw = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key); + this.opcUdw = ItemDataAccessorFactory.getItemsDataAccessor(OpcConfig.udw_opc_value_key); } - - private Date sendTime; - private String last_items; - private int noLog_sendTimeOut; - private Date noLog_sendTime; - private String noLog_last_items; - @Override - public UnifiedDataAccessor getOpcValueAccessor() { + public ItemsDataAccessor getOpcValueAccessor() { return this.opcUdw; } - public void checkcontrol(Map itemValues) throws Exception { - Group group = opcServerService.getServer(this.getOpcServer()); - Map write = new HashMap(); - Map readitems = new LinkedHashMap(); - List itemsString = new ArrayList(); - itemsString = new ArrayList<>(itemValues.keySet()); - Iterator is = itemsString.iterator(); - - while (is.hasNext()) { - String string = (String) is.next(); - try { - readitems.put(string, group.addItem(string)); - } catch (Exception e) { - e.printStackTrace(); - } - } - int i = 0; - while (true) { - //下发信号 - try { - if (i == 0) { - control(itemValues); - } else { - controlByNewConn(itemValues); - } - - } catch (Exception e) { - e.printStackTrace(); - } - Map read = new HashMap(); - Map itemStatus = null; - boolean check = true; - try { - if (i > 0) { - group = opcServerService.getServer(this.getOpcServer()); - itemsString = new ArrayList<>(itemValues.keySet()); - Iterator nis = itemsString.iterator(); - - while (nis.hasNext()) { - String string = (String) nis.next(); - try { - readitems.put(string, group.addItem(string)); - } catch (Exception e) { - e.printStackTrace(); - } - } - itemStatus = group.read(true, (Item[]) readitems.values().toArray(new Item[0])); - - } else { - itemStatus = group.read(true, (Item[]) readitems.values().toArray(new Item[0])); - } - Set items = itemStatus.keySet(); - Iterator var15 = items.iterator(); - while (var15.hasNext()) { - Item item = (Item) var15.next(); - ItemState itemState = (ItemState) itemStatus.get(item); - Object value = OpcUtl.getValue(item, itemState); - read.put(item.getId(), value); - } - - Iterator var24 = itemsString.iterator(); - - while (var24.hasNext()) { - String itemString = (String) var24.next(); - if (!ObjectUtl.isEquals(String.valueOf(itemValues.get(itemString)), String.valueOf(read.get(itemString)))) { - check = false; - } - } - } catch (Exception e) { - e.printStackTrace(); - check = false; - } - - if (check) { - return; - } - - if (i > 0) { - ThreadUtl.sleep(300L); - } - - if (i > 3) { -// log.info("写入次数超过3次而失败"); - throw new RuntimeException("写入次数超过3次而失败"); - } - ++i; + /** + * 通过MQTT下发单个电气信号 + * + * @param key + * @param value + */ + public void writing(String key, Object value) { + try { + List> list = new ArrayList<>(); + Map map = new HashMap<>(); + map.put("id", getId() + key); + map.put("v", value); + list.add(map); + mqttService.publishMessage(JSON.toJSONString(list)); + luceneExecuteLogService.deviceExecuteLog(new LuceneLogDto(this.getDevice().getDevice_code(), "下发电气信号 [" + key + ":" + value + "] 成功")); + } catch (Exception e) { + luceneExecuteLogService.deviceExecuteLog(new LuceneLogDto(this.getDevice().getDevice_code(), "下发电气信号 [" + key + ":" + value + "] 失败, 原因:" + e.getMessage())); } } - - public boolean controlByNewConn(Map itemValues) { - - Iterator> it = itemValues.entrySet().iterator(); - - ItemValue[] p2; - p2 = new ItemValue[itemValues.size()]; - int i = 0; - while (it.hasNext()) { - Map.Entry entry = it.next(); - System.out.println("即将写入值:" + entry.getKey() + ":" + entry.getValue()); - p2[i] = new ItemValue(); - p2[i].setItem_code(entry.getKey()); - p2[i].setItem_value(entry.getValue()); - i++; + /** + * 通过MQTT下发多个电气信号 + * + * @param key + * @param value + */ + public void writing(List key, List value) { + if (key.size() != value.size()) { + luceneExecuteLogService.deviceExecuteLog(new LuceneLogDto(this.getDevice().getDevice_code(), "下发电气信号 [" + key + "----" + value + "] 失败, 原因:参数长度不一致,不允许下发")); + throw new BadRequestException("参数长度不一致,不允许下发"); } - - return this.controlByNewConn(p2); - } - - public boolean control(Map itemValues) { - - Iterator> it = itemValues.entrySet().iterator(); - - ItemValue[] p2; - p2 = new ItemValue[itemValues.size()]; - int i = 0; - while (it.hasNext()) { - Map.Entry entry = it.next(); - System.out.println("即将写入值:" + entry.getKey() + ":" + entry.getValue()); - p2[i] = new ItemValue(); - p2[i].setItem_code(entry.getKey()); - p2[i].setItem_value(entry.getValue()); - i++; - } - - return this.control(p2); - } - - - public boolean control(ItemValue[] itemValues) { - if (itemValues != null && itemValues.length != 0) { - String this_items = JsonUtl.parseWithoutException(itemValues); - boolean need_write = false; - StringBuilder sb = new StringBuilder(); - ItemValue[] var5 = itemValues; - int var6 = itemValues.length; - - for (int var7 = 0; var7 < var6; ++var7) { - ItemValue itemValue = var5[var7]; - String code = itemValue.getItem_code(); - Object udw_value = this.getUdwValue(code); - Object write_value = itemValue.getItem_value(); - sb.append(code); - sb.append(":"); - sb.append(JsonUtl.parseWithoutException(udw_value)); - sb.append(";"); - if (!need_write && !UnifiedDataAppService.isEquals(udw_value, write_value)) { - need_write = true; - } else { - //log.warn("下发信号点位{} 当前写入值:{} 与系统内存值:{} 相同,不再写入 ", code, write_value, udw_value ); - } - } - // need_write = true; - - if (need_write) { - Date date = new Date(); - /*if (StringUtl.isEqual(this_items, this.last_items) && date.getTime() - this.sendTime.getTime() < (long) WcsConfig.opc_write_repeat_check) { - log.trace("发送时间因为小于{}毫秒,而被无视", WcsConfig.opc_write_repeat_check); - return false; - }*/ - - this.last_items = this_items; - this.sendTime = date; - /* this.execute_log.setResource(this.getDevice().getCode(), this.getDevice().getName()); - this.execute_log.log("原始记录{}->变更为{}", new Object[]{sb, this_items}); - OpcServerService opcServerService = OpcServerFactory.getOpcServerService();*/ - - OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerServiceImpl.class); - - opcServerService.writeInteger(this.getOpcServer(), itemValues); - UnifiedDataAccessor opcValueAccessor = this.getOpcValueAccessor(); - ItemValue[] var17 = itemValues; - int var18 = itemValues.length; - - for (int var19 = 0; var19 < var18; ++var19) { - ItemValue itemValue = var17[var19]; - String code = itemValue.getItem_code(); - Object value = itemValue.getItem_value(); - opcValueAccessor.setValue(code, value); - } - } - - return true; - } else { - throw new RuntimeException("下发 无内容"); + Map keys_values = IntStream.range(0, Math.min(key.size(), value.size())) + .boxed() + .collect(Collectors.toMap(key::get, value::get)); + try { + //MQTT下发数据的格式是[ + // {"id":"opc_code.plc_code.device_code.item","v":value}, + // {"id":"opc_code.plc_code.device_code.item","v":value} + // ] + List> list = IntStream.range(0, key.size()) + .mapToObj(i -> new AbstractMap.SimpleEntry<>(key.get(i), value.get(i))) + .map(entry -> { + Map map = new HashMap<>(); + map.put("id", getId() + entry.getKey()); + map.put("v", entry.getValue()); + return map; + }) + .collect(Collectors.toList()); + mqttService.publishMessage(JSON.toJSONString(list)); + luceneExecuteLogService.deviceExecuteLog(new LuceneLogDto(this.getDevice().getDevice_code(), "下发电气信号 [" + JSON.toJSONString(keys_values) + "] 成功")); + } catch (Exception e) { + luceneExecuteLogService.deviceExecuteLog(new LuceneLogDto(this.getDevice().getDevice_code(), "下发电气信号 [" + JSON.toJSONString(keys_values) + "] 失败,原因:" + e.getMessage())); } } + /** + * 抽取统一下发电气信号前缀 + * + * @return + */ + public String getId() { + return this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() + "."; + } - public boolean controlByNewConn(ItemValue[] itemValues) { - if (itemValues != null && itemValues.length != 0) { - String this_items = JsonUtl.parseWithoutException(itemValues); - boolean need_write = false; - StringBuilder sb = new StringBuilder(); - ItemValue[] var5 = itemValues; - int var6 = itemValues.length; -// for (int var7 = 0; var7 < var6; ++var7) { -// ItemValue itemValue = var5[var7]; -// String code = itemValue.getItem_code(); -// Object udw_value = this.getUdwValue(code); -// Object write_value = itemValue.getItem_value(); -// sb.append(code); -// sb.append(":"); -// sb.append(JsonUtl.parseWithoutException(udw_value)); -// sb.append(";"); -// if (!need_write && !UnifiedDataAppService.isEquals(udw_value, write_value)) { -// need_write = true; -// } else { -// log.warn("下发信号点位{} 当前写入值:{} 与系统内存值:{} 相同,不再写入 ", code, write_value, udw_value ); -// } -// } - need_write = true; - if (need_write) { - Date date = new Date(); - /*if (StringUtl.isEqual(this_items, this.last_items) && date.getTime() - this.sendTime.getTime() < (long) WcsConfig.opc_write_repeat_check) { - log.trace("发送时间因为小于{}毫秒,而被无视", WcsConfig.opc_write_repeat_check); - return false; - }*/ + /** + * 下发多个信号key,需与value数量和顺序保持一致 + * + * @param keys + * @return + */ + public List getKeys(String... keys) { + return new ArrayList<>(Arrays.asList(keys)); + } - this.last_items = this_items; - this.sendTime = date; - OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerServiceImpl.class); - - opcServerService.writeIntegerByNewConn(this.getOpcServer(), itemValues); - - - UnifiedDataAccessor opcValueAccessor = this.getOpcValueAccessor(); - ItemValue[] var17 = itemValues; - int var18 = itemValues.length; - - for (int var19 = 0; var19 < var18; ++var19) { - ItemValue itemValue = var17[var19]; - String code = itemValue.getItem_code(); - Object value = itemValue.getItem_value(); - opcValueAccessor.setValue(code, value); - } - } - - return true; - } else { - throw new RuntimeException("下发 无内容"); - } + /** + * 下发多个电气信号值,需与key数量和顺序保持一致 + * + * @param values + * @return + */ + public List getValues(Object... values) { + return new ArrayList<>(Arrays.asList(values)); } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/OpcDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/OpcDeviceDriver.java index dfc7339..cf5a6d8 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/OpcDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/driver/OpcDeviceDriver.java @@ -2,7 +2,6 @@ package org.nl.acs.device_driver.driver; import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; @@ -12,8 +11,7 @@ import org.nl.acs.device.domain.DeviceExtra; import org.nl.acs.device.service.mapper.DeviceExtraMapper; import org.nl.acs.device_driver.DeviceDriver; import org.nl.acs.opc.OpcItemDto; -import org.nl.acs.storage_cell.service.mapper.StorageCellMapper; -import org.nl.acs.udw.UnifiedDataAccessor; +import org.nl.acs.udw.mqttUdw.ItemsDataAccessor; import org.nl.config.SpringContextHolder; import java.util.ArrayList; @@ -24,14 +22,16 @@ import java.util.Map; public interface OpcDeviceDriver extends DeviceDriver { /** * getOpcValueAccessor + * * @return */ - UnifiedDataAccessor getOpcValueAccessor(); + ItemsDataAccessor getOpcValueAccessor(); DeviceExtraMapper deviceExtraMapper = SpringContextHolder.getBean("deviceExtraMapper"); /** * getOpcItems + * * @return */ default List getOpcItems() { @@ -65,6 +65,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getExtraValue + * * @return */ default Map getExtraValue() { @@ -73,6 +74,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getOpcServer + * * @return */ default String getOpcServer() { @@ -81,6 +83,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getDevice + * * @return */ @Override @@ -88,6 +91,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getOpcPlc + * * @return */ default String getOpcPlc() { @@ -96,11 +100,12 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getIntegeregerValue + * * @param protocol * @return */ default Integer getIntegeregerValue(String protocol) { - if(ObjectUtil.isEmpty(this.getValue(protocol)) && "heartbeat".equals(protocol)){ + if (ObjectUtil.isEmpty(this.getValue(protocol)) && "heartbeat".equals(protocol)) { return null; } return (Integer) (ObjectUtil.isEmpty(this.getValue(protocol)) ? 0 : this.getValue(protocol)); @@ -108,6 +113,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getStringgerValue + * * @param protocol * @return */ @@ -117,6 +123,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getLongValue + * * @param protocol * @return */ @@ -126,6 +133,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getByteArrayValue + * * @param protocol * @return */ @@ -135,6 +143,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getIntegerArrayValue + * * @param protocol * @return */ @@ -154,6 +163,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getFloatValue + * * @param protocol * @return */ @@ -163,6 +173,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getIntegerValue + * * @param protocol * @return */ @@ -172,6 +183,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getShortValue + * * @param protocol * @return */ @@ -181,6 +193,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getIntegeregerArrayValue + * * @param protocol * @return */ @@ -190,6 +203,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getStringValue + * * @param protocol * @return */ @@ -199,6 +213,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getValue + * * @param protocol * @return */ @@ -208,6 +223,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getItem + * * @param item * @return */ @@ -217,6 +233,7 @@ public interface OpcDeviceDriver extends DeviceDriver { /** * getUdwValue + * * @param protocol * @return */ diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/one_conveyor/scanner_weight_conveyor/ConveyorWithScannerWeightDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/one_conveyor/scanner_weight_conveyor/ConveyorWithScannerWeightDeviceDriver.java index aced999..96bc3c0 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/one_conveyor/scanner_weight_conveyor/ConveyorWithScannerWeightDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/one_conveyor/scanner_weight_conveyor/ConveyorWithScannerWeightDeviceDriver.java @@ -528,27 +528,27 @@ public class ConveyorWithScannerWeightDeviceDriver extends AbstractOpcDeviceDriv public void writing(List list) { - Map itemMap = new HashMap(); - for (int i = 0; i < list.size(); i++) { - Object ob = list.get(i); - JSONObject json = (JSONObject) JSONObject.toJSON(ob); - if (!StrUtil.isEmpty(json.getString("value"))) { - String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() - + "." + json.getString("code"); - itemMap.put(to_param, json.getString("value")); - } - } - logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); - try { - this.checkcontrol(itemMap); - } catch (Exception e) { - e.printStackTrace(); - try { - this.checkcontrol(itemMap); - } catch (Exception e1) { - e1.printStackTrace(); - } - } +// Map itemMap = new HashMap(); +// for (int i = 0; i < list.size(); i++) { +// Object ob = list.get(i); +// JSONObject json = (JSONObject) JSONObject.toJSON(ob); +// if (!StrUtil.isEmpty(json.getString("value"))) { +// String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code() +// + "." + json.getString("code"); +// itemMap.put(to_param, json.getString("value")); +// } +// } +// logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e) { +// e.printStackTrace(); +// try { +// this.checkcontrol(itemMap); +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// } } public synchronized boolean finish_instruction() throws Exception { diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/rgv/RgvDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/rgv/RgvDeviceDriver.java index d2804ec..b18af18 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/rgv/RgvDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/rgv/RgvDeviceDriver.java @@ -321,7 +321,7 @@ public class RgvDeviceDriver extends AbstractOpcDeviceDriver implements DeviceDr } }); if (ObjectUtil.isNotEmpty(itemMap)) { - this.control(itemMap); + // this.control(itemMap); logServer.deviceExecuteLog(this.getDevice().getDevice_code(), "", "", "下发多个电气信号:" + itemMap); } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/stacker/standard_stacker/StandardStackerDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/stacker/standard_stacker/StandardStackerDeviceDriver.java index bdef248..272925e 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/stacker/standard_stacker/StandardStackerDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/stacker/standard_stacker/StandardStackerDeviceDriver.java @@ -1032,11 +1032,11 @@ public class StandardStackerDeviceDriver extends AbstractOpcDeviceDriver impleme } logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap); try { - this.checkcontrol(itemMap); + //this.checkcontrol(itemMap); } catch (Exception e) { e.printStackTrace(); try { - this.checkcontrol(itemMap); + // this.checkcontrol(itemMap); } catch (Exception e1) { e1.printStackTrace(); } @@ -1074,7 +1074,7 @@ public class StandardStackerDeviceDriver extends AbstractOpcDeviceDriver impleme } }); if (ObjectUtil.isNotEmpty(itemMap)) { - this.control(itemMap); + //this.control(itemMap); logServer.deviceExecuteLog(this.getDevice().getDevice_code(), "", "", "下发多个电气信号:" + itemMap); } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/two_conveyor/lamp_three_color/LampThreecolorDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/two_conveyor/lamp_three_color/LampThreecolorDeviceDriver.java index 562eafb..dac2fdc 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/two_conveyor/lamp_three_color/LampThreecolorDeviceDriver.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/two_conveyor/lamp_three_color/LampThreecolorDeviceDriver.java @@ -101,7 +101,7 @@ public class LampThreecolorDeviceDriver extends AbstractOpcDeviceDriver implemen Map itemMap = new HashMap(); itemMap.put(to_param, Integer.parseInt(value)); - this.control(itemMap); + //this.control(itemMap); logServer.deviceExecuteLog(device_code, "", "", "下发电气信号设备号:" + device_code + ",下发电气:" + to_param + ",下发电气值:" + value); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/ItemProtocol.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/ItemProtocol.java new file mode 100644 index 0000000..3f278e3 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/ItemProtocol.java @@ -0,0 +1,64 @@ +package org.nl.acs.device_driver.xx; + +import org.nl.acs.device.device_driver.standard_inspect.ItemDto; + +import org.nl.acs.device_driver.BaseTagsDataReader; + +import java.util.List; +import java.util.ArrayList; + +public enum ItemProtocol implements BaseTagsDataReader.KeyProvider { + HEARTBEAT("heartbeat", "心跳", "DB81.B10"), + MODE("mode", "工作模式", "DB81.B1"), + MOVE("move", "光电信号", "DB81.B2"), + ACTION("action", "动作信号", "DB81.B3"), + ERROR("error", "报警信号", "DB81.B4"), + NUMS("nums", "数量", "DB81.DBD8[3]"), + TO_COMMAND("toCommand", "下发作业命令", "DB71.W0"), + TO_TARGET("toTarget", "下发目标站", "DB71.W2"), + TO_TASK("toTask", "下发任务号", "DB71.D4"); + + private final String key; + private final String description; + private final String address; + + ItemProtocol(String key, String description, String address) { + this.key = key; + this.description = description; + this.address = address; + } + + @Override + public String getKey() { + return this.key; + } + + public String getDescription() { + return description; + } + + public String getAddress() { + return address; + } + + public static List getReadableItemDtos() { + List list = new ArrayList<>(); + for (ItemProtocol prop : values()) { + if (!prop.getKey().contains("to")) { + list.add(new ItemDto(prop.getKey(), prop.getDescription(), prop.getAddress())); + } + } + return list; + } + + public static List getWriteableItemDtos() { + List list = new ArrayList<>(); + for (ItemProtocol prop : values()) { + if (prop.getKey().contains("to")) { + list.add(new ItemDto(prop.getKey(), prop.getDescription(), prop.getAddress())); + } + } + return list; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxDefinition.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxDefinition.java new file mode 100644 index 0000000..76ef265 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxDefinition.java @@ -0,0 +1,56 @@ +package org.nl.acs.device_driver.xx; + +import org.nl.acs.device.device_driver.standard_inspect.ItemDto; +import org.nl.acs.device.domain.Device; +import org.nl.acs.device.enums.DeviceType; +import org.nl.acs.device_driver.DeviceDriver; +import org.nl.acs.device_driver.defination.OpcDeviceDriverDefination; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Service +public class XxDefinition implements OpcDeviceDriverDefination { + @Override + public String getDriverCode() { + return "xx_device_xx"; + } + + @Override + public String getDriverName() { + return "xxxxName"; + } + + @Override + public String getDriverDescription() { + return "xxxxName"; + } + + @Override + public DeviceDriver getDriverInstance(Device device) { + return (new XxxxDeviceDriver()).setDevice(device).setDriverDefination(this); + } + + @Override + public Class getDeviceDriverType() { + return XxxxDeviceDriver.class; + } + + @Override + public List getFitDeviceTypes() { + List types = new LinkedList(); + types.add(DeviceType.conveyor); + return types; + } + + @Override + public List getReadableItemDtos() { + return ItemProtocol.getReadableItemDtos(); + } + + @Override + public List getWriteableItemDtos() { + return ItemProtocol.getWriteableItemDtos(); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxxxDeviceDriver.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxxxDeviceDriver.java new file mode 100644 index 0000000..ac1c263 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/device_driver/xx/XxxxDeviceDriver.java @@ -0,0 +1,162 @@ +package org.nl.acs.device_driver.xx; + +import com.alibaba.fastjson.JSONObject; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.nl.acs.device.domain.Device; +import org.nl.acs.device_driver.*; +import org.nl.acs.device_driver.driver.*; +import org.nl.acs.monitor.DeviceStageMonitor; +import org.nl.config.SpringContextHolder; +import org.nl.acs.device_driver.BaseTagsDataReader; +import org.nl.config.lucene.service.LuceneExecuteLogService; +import org.nl.config.lucene.service.dto.LuceneLogDto; +import java.util.Date; + +@Slf4j +@Getter +@Setter +@RequiredArgsConstructor +public class XxxxDeviceDriver extends AbstractOpcDeviceDriver implements + DeviceDriver, + ExecutableDeviceDriver, + RouteableDeviceDriver, + DeviceStageMonitor, + StandardRequestMethod, + BaseTagsDataReader { + + private final LuceneExecuteLogService logService = SpringContextHolder.getBean(LuceneExecuteLogService.class); + + /** + * 心跳 + */ + private int heartbeat = 0; + private int lastHeartbeat = 0; + /** + * 工作模式 + */ + private Integer mode = 0; + private Integer lastMode = 0; + /** + * 光电信号 + */ + private byte move = 0; + private byte lastMove = 0; + /** + * 动作信号 + */ + private Byte action = 0; + private Byte lastAction = 0; + /** + * 报警信号 + */ + private long error = 0; + private long lastError = 0; + /** + * 数量 + */ + private int[] nums; + private int[] lastNums; + /** + * 下发作业命令 + */ + private float[] toCommand; + private float[] lastToCommand; + /** + * 下发目标站 + */ + private String[] toTarget; + private String[] lastToTarget; + /** + * 下发任务号 + */ + private Boolean toTask; + private Boolean lastToTask; + /** + * 当前设备编号 + */ + private String currentDeviceCode; + + /** + * 消息 + */ + private String message; + + /** + * 请求标记 + */ + boolean requireSuccess = false; + + /** + * 请求时间 + */ + private Date requireTime = new Date(); + + /** + * 请求间隔时间 + */ + private long requireTimeOut = 3000L; + + /** + * 设备异常标记 + */ + private boolean isError = false; + + @Override + public Device getDevice() { + return this.device; + } + + @Override + public & KeyProvider, T> T getOpcValue(E item, Class fieldClassType) { + return (T) this.getValue(item.getKey()); + } + + @Override + public void setLog(String key, Object newValue, Object oldValue) { + logService.deviceExecuteLog(new LuceneLogDto(this.currentDeviceCode, "自动线程读取信号:" + key + ",由" + oldValue + "->" + newValue)); + } + + @Override + public void execute() { + this.currentDeviceCode = this.getDeviceCode(); + this.loadAssignData(currentDeviceCode, ItemProtocol.class); + } + + @Override + public void executeLogic() { + if (Boolean.FALSE.equals(this.getOnline())) { + this.message = "设备离线"; + } else if (this.mode == 0) { + this.message = "设备未联机"; + } else if (this.error != 0) { + this.message = "设备报警"; + this.isError = true; + } else { + this.isError = false; + this.message = ""; + //编写业务逻辑方法 + } + } + + @Override + public JSONObject getDeviceStatusName() throws Exception { + JSONObject jo = new JSONObject(); + jo.put("device_code", this.currentDeviceCode); + jo.put("device_name", this.getDevice().getDevice_name()); + jo.put("driver_type", "xx_device_xx"); + jo.put("is_click", false); + jo.put("message", this.message); + jo.put("isOnline", this.online); + jo.put("isError", this.isError); + return jo; + } + + @Override + public void setDeviceStatus(JSONObject data) { + + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/log/service/impl/DeviceExecuteLogServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/log/service/impl/DeviceExecuteLogServiceImpl.java index de87529..027413e 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/log/service/impl/DeviceExecuteLogServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/log/service/impl/DeviceExecuteLogServiceImpl.java @@ -4,7 +4,6 @@ import cn.hutool.core.date.DateUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.nl.acs.log.service.DeviceExecuteLogService; -import org.nl.acs.opc.OpcUtl; import org.slf4j.MDC; import org.springframework.stereotype.Service; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java deleted file mode 100644 index a41cfd3..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcProtocolRunable.java +++ /dev/null @@ -1,461 +0,0 @@ -package org.nl.acs.opc; - -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import com.alibaba.fastjson.JSON; -import lombok.extern.slf4j.Slf4j; -import org.nl.acs.instruction.service.InstructionService; -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.common.enums.LogTypeEnum; -import org.nl.config.SpringContextHolder; -import org.nl.config.lucene.service.dto.LuceneLogDto; -import org.openscada.opc.lib.da.*; - -import java.util.*; - - -@Slf4j -public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerConnectionStateListener { - List protocols; - OpcServerManageDto OpcServer; - int error_num; - String message; - int maxResartNum; - private Server server; - private Group group; - boolean flag = false; - private int all_null; - private Map itemSearchCache; - - - public DeviceOpcProtocolRunable() { - this.error_num = 0; - this.all_null = 0; - this.message = null; - this.itemSearchCache = new HashMap(); - this.server = null; - } - - public List getProtocols() { - return this.protocols; - } - - public void setProtocols(List protocols) { - this.protocols = protocols; - } - - public OpcServerManageDto getOpcServer() { - return this.OpcServer; - } - - public void setOpcServer(OpcServerManageDto opcServer) { - this.OpcServer = opcServer; - } - - - private OpcItemDto getItem(String item) { - OpcItemDto x = (OpcItemDto) this.itemSearchCache.get(item); - if (x == null) { - Iterator var3 = this.protocols.iterator(); - - while (var3.hasNext()) { - OpcItemDto dto = (OpcItemDto) var3.next(); - if (StrUtil.equals(item, dto.getItem_code())) { - x = dto; - this.itemSearchCache.put(item, dto); - break; - } - } - } - - return x; - } - - - @Override - public void run() { - if (OpcConfig.opc_item_read_using_callback) { - this.runNew(); - } else { - this.runOld(); - } - } - - - private void runOld() { - OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService .class); - while (true) { - start: - try { - if (this.group != null) { - group.clear(); - group.remove(); - log.trace("清理group..."); - } - if (this.server != null) { - server.disconnect(); - log.trace("清理server..."); - } - -// group =opcServerService.getServer(this.getOpcServer().getOpc_code()); - this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain()); - this.server.addStateListener(this); - group = this.server.addGroup(); - List itemsString = new ArrayList(); - Iterator var3 = this.protocols.iterator(); - - while (var3.hasNext()) { - OpcItemDto protocol = (OpcItemDto) var3.next(); - String item = protocol.getItem_code(); - itemsString.add(item); - } - - Map itemsMap = new LinkedHashMap(); - boolean is_error = false; - StringBuilder err_message = new StringBuilder(); - Iterator var6 = itemsString.iterator(); - - while (var6.hasNext()) { - String string = (String) var6.next(); - - try { - Item item = group.addItem(string); - itemsMap.put(string, item); - log.trace("添加成功 {}", string); - } catch (Exception var26) { - err_message.append(string + ":" + var26.getMessage()); - if (!is_error) { - is_error = true; - } - } - } - - String tag; - if (is_error) { - tag = err_message.toString(); - log.warn("{}:{}", OpcConfig.resource_code, tag); - } - - if (!OpcStartTag.is_run) { - OpcStartTag.is_run = true; - } - - tag = ""; - if (log.isWarnEnabled()) { - tag = Thread.currentThread().getName(); - if (this.OpcServer != null) { - tag = tag + this.getOpcGroupID(); - } - } - - 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 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); - } - - time_out = true; - } else { - time_out = false; - } - - boolean valueAllNotNull = false; - Set 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; - } - - 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(!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); - } - - ThreadUtl.sleep((long) OpcConfig.synchronized_millisecond); - if (this.error_num != 0) { - this.error_num = 0; - this.message = null; - } - - if (!valueAllNotNull) { - int random = (new Random()).nextInt(10) + 1; - random *= 1000; - if (this.all_null < 3) { - if (log.isWarnEnabled()) { - log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,3); - } - - 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); - } - ThreadUtl.sleep((long) (5000)); - } - - ++this.all_null; - } else { - this.all_null = 0; - } -// break start; - - } - - log.warn("opc线程停止。。。"); - return; - } catch (Exception var27) { - if (this.server != null) { - try { - this.server.disconnect(); - } catch (Exception var25) { - } - } - - this.server = null; - if (!DeviceOpcSynchronizeAutoRun.isRun) { - log.warn("opc线程停止2。。。"); - return; - } - - String error_message = "设备信息同步异常"; - if (!StrUtil.equals(this.message, error_message)) { - log.warn(error_message, var27); - } - - ThreadUtl.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000)); - ++this.error_num; - if (this.error_num > 3 && !StrUtil.equals(this.message, error_message)) { - this.message = error_message; - } - } - } - } - - - - private void runNew() { - 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.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); - } - - accessor.bind(); - log.info("Async20Access bind {}", opcGroupId); - } - - 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(); - } - - accessor = null; - } - - if (this.server != null) { - try { - this.server.disconnect(); - } catch (Exception var6) { - } - - this.server = null; - } - - if (var8 instanceof InterruptedException) { - log.warn("OPC 同步线程(%s)被中断", opcGroupId); - return; - } - - 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(); - } - - ++this.error_num; - if (this.error_num > 3 && !StrUtil.equals(this.message, error_message)) { - this.message = error_message; - } - } - } - } - - - @Override - public void connectionStateChanged(boolean connected) { - if (!connected) { - this.server = null; - } - - log.warn("opc server {} {}", this.getOpcGroupID(), connected ? "connected" : "disconnected"); - } - - private String getOpcGroupID() { - String var10000 = this.OpcServer.getOpc_code(); - return var10000 + "(" + this.protocols.size() + " items)"; - } - - public static String formatDuring(long mss) { - long days = mss / 86400000L; - long hours = mss % 86400000L / 3600000L; - long minutes = mss % 3600000L / 60000L; - long seconds = mss % 60000L / 1000L; - return days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds "; - } - - - @Override - public void changed(Item item, ItemState itemState) { - String itemId = item.getId(); - - try { - Object value = OpcUtl.getValue(item, itemState); - UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key); - accessor_value.setValue(itemId, value); - -// if (value != null) { -// if (log.isTraceEnabled()) { -// log.trace("Item {} new value: {}, Timestamp: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime()}); -// } -// } else if (log.isInfoEnabled()) { -// log.info("Item {} new value: {}, Timestamp: {}, Quality: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime(), itemState.getQuality()}); -// } - log.trace("Item {} new value: {}, Timestamp: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime()}); - - OpcItemDto itemDto = this.getItem(itemId); -// if (Boolean.TRUE.equals(itemDto.getNeed_log())) { -// this.logItemChanged(itemId, accessor_value, value, itemDto); -// } - this.logItemChanged(itemId, accessor_value, value, itemDto); - - } catch (Exception var7) { - log.error(itemId, var7); - } - - } - - private void logItemChanged(String itemId, UnifiedDataAccessor accessor_value, Object value, OpcItemDto itemDto) { - Object his = accessor_value.getValue(itemId); - List 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 + ";"); - } -// log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value, sb}); - if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time")) { - // 存在上次点位值为null情况 则不记录日志 - 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(itemDto.getHis_item_value()), String.valueOf(itemDto.getItem_value())); - luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc()); - log.info("{}", JSON.toJSONString(luceneLogDto)); - } -// 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}); -// } - -// log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value}); - if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time")) { - 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(itemDto.getHis_item_value()), String.valueOf(itemDto.getItem_value())); - luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc()); - log.info("{}", JSON.toJSONString(luceneLogDto)); - } -// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{}", new Object[]{itemId, his, value}); - } - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcSynchronizeAutoRun.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcSynchronizeAutoRun.java deleted file mode 100644 index 65f5d3f..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/DeviceOpcSynchronizeAutoRun.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.nl.acs.opc; - -import cn.hutool.core.util.ObjectUtil; -import org.nl.acs.auto.run.AbstractAutoRunnable; -import org.nl.acs.opc.service.dto.OpcServerManageDto; -import org.nl.config.thread.TheadFactoryName; -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; - -/** - * OPC设备同步启动 - * @author 20220102CG\noblelift - */ -@Component -public class DeviceOpcSynchronizeAutoRun extends AbstractAutoRunnable { - - public static boolean isRun = false; - ExecutorService executorService = Executors.newCachedThreadPool(); - @Autowired - private DeviceAppService deviceAppService; - @Autowired - private OpcServerManageService opcServerManageService; - - @Override - public String getCode() { - return DeviceOpcSynchronizeAutoRun.class.getSimpleName(); - } - - @Override - public String getName() { - return "opc设备同步器"; - } - - @Override - public void autoRun() throws Exception { - { - isRun = true; - - Map servers = this.opcServerManageService.queryAllServerMap(); - Map>> pros; - do { - Thread.sleep(1000L); - pros = this.deviceAppService.findAllFormatProtocolFromDriver(); - } while (ObjectUtil.isEmpty(pros)); - Set keys = pros.keySet(); - Iterator var4 = keys.iterator(); - //代码执行一次 - while (var4.hasNext()) { - String key = (String) var4.next(); - List> list = (List) pros.get(key); - OpcServerManageDto opcServer = (OpcServerManageDto) servers.get(key); - Iterator var8 = list.iterator(); - while (var8.hasNext()) { - List groupProtols = (List) var8.next(); - DeviceOpcProtocolRunable runable = new DeviceOpcProtocolRunable(); - runable.setProtocols(groupProtols); - runable.setOpcServer(opcServer); - this.executorService.submit(runable); - } - } - - // 同步无光电设备信号 - //Map>> pros1 = this.deviceAppService.findAllFormatProtocolFromDriver(); - //List opcDrivers = this.deviceAppService.findDeviceDriver(DeviceDriver.class); - - while (true) { - Thread.sleep(3000L); - } - } - } - - @Override - public void after() { - isRun = false; - this.executorService.shutdownNow(); - this.executorService = Executors.newCachedThreadPool(); - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/JsonUtl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/JsonUtl.java deleted file mode 100644 index ccdb0da..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/JsonUtl.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.nl.acs.opc; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.databind.type.TypeFactory; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * @author 20220102CG\noblelift - */ -public class JsonUtl { - private static ObjectMapper objectMapper = null; - private static ObjectMapper objectMapperLog = null; - - private JsonUtl() { - } - - private static ObjectMapper init() { - ObjectMapper objectMapper = new ObjectMapper(); - SimpleModule simpleModule = new SimpleModule(); -// simpleModule.addSerializer(Enum.class, new EnumSerializer()); -// simpleModule.addSerializer(Date.class, new DateSerializer()); -// simpleModule.addDeserializer(Enum.class, new EnumDeserializer()); -// simpleModule.addDeserializer(Date.class, new DateDeserializers.DateDeserializer()); - objectMapper.registerModule(simpleModule); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - return objectMapper; - } - - public static ObjectMapper getInstance() { - if (objectMapper == null) { - Class var0 = JsonUtl.class; - synchronized (JsonUtl.class) { - if (objectMapper == null) { - objectMapper = init(); - } - } - } - - return objectMapper; - } - - public static ObjectMapper getInstanceLog() { - if (objectMapperLog == null) { - Class var0 = JsonUtl.class; - synchronized (JsonUtl.class) { - if (objectMapperLog == null) { - objectMapperLog = init(); - objectMapperLog.setSerializationInclusion(Include.NON_NULL); - } - } - } - - return objectMapperLog; - } - - public static ObjectMapper getObjectMapper() { - return getInstance(); - } - - public static String parse(Object object) throws RuntimeException { - try { - return getObjectMapper().writeValueAsString(object); - } catch (JsonProcessingException var2) { - throw new RuntimeException(var2); - } - } - - public static String parseWithoutException(Object object) { - try { - return parse(object); - } catch (Exception var2) { - return null; - } - } - - public static String parseLog(Object object) { - try { - return getInstanceLog().writeValueAsString(object); - } catch (Exception var2) { - return null; - } - } - - public static T format(String json, Class clazz) throws RuntimeException { - try { - return getObjectMapper().readValue(json, clazz); - } catch (IOException var3) { - throw new RuntimeException(var3); - } - } - - public static List formatList(String json, Class clazz) throws RuntimeException { - try { - JavaType type = getObjectMapper().getTypeFactory().constructParametricType(List.class, new Class[]{clazz}); - return (List) getObjectMapper().readValue(json, type); - } catch (IOException var3) { - throw new RuntimeException(var3); - } - } - - public static Map formatMap(String json, Class clazzKey, Class clazzValue) throws RuntimeException { - try { - JavaType type = getObjectMapper().getTypeFactory().constructParametricType(Map.class, new Class[]{clazzKey, clazzValue}); - return (Map) getObjectMapper().readValue(json, type); - } catch (IOException var4) { - throw new RuntimeException(var4); - } - } - - public static List> formatListTwo(String json, Class clazz) throws RuntimeException { - try { - TypeFactory typeFactory = getObjectMapper().getTypeFactory(); - JavaType type = typeFactory.constructParametrizedType(List.class, List.class, new Class[]{clazz}); - type = typeFactory.constructParametrizedType(List.class, List.class, new JavaType[]{type}); - return (List) getObjectMapper().readValue(json, type); - } catch (IOException var4) { - throw new RuntimeException(var4); - } - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/ObjectUtl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/ObjectUtl.java deleted file mode 100644 index fa4dbd1..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/ObjectUtl.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.nl.acs.opc; - - -import java.util.Arrays; -import java.util.Objects; - -/** - * @author 20220102CG\noblelift - */ -public class ObjectUtl { - private ObjectUtl() { - } - - public static boolean isEquals(Object a, Object b) { - if (a == null && b == null) { - return true; - } else if (a != null && b != null) { - if (a.getClass().isArray()) { - if (a instanceof boolean[]) { - return Arrays.equals((boolean[]) ((boolean[]) a), (boolean[]) ((boolean[]) b)); - } else if (a instanceof byte[]) { - return Arrays.equals((byte[]) ((byte[]) a), (byte[]) ((byte[]) b)); - } else if (a instanceof int[]) { - return Arrays.equals((int[]) ((int[]) a), (int[]) ((int[]) b)); - } else if (a instanceof long[]) { - return Arrays.equals((long[]) ((long[]) a), (long[]) ((long[]) b)); - } else if (a instanceof double[]) { - return Arrays.equals((double[]) ((double[]) a), (double[]) ((double[]) b)); - } else if (a instanceof short[]) { - return Arrays.equals((short[]) ((short[]) a), (short[]) ((short[]) b)); - } else if (a instanceof char[]) { - return Arrays.equals((char[]) ((char[]) a), (char[]) ((char[]) b)); - } else if (a instanceof float[]) { - return Arrays.equals((float[]) ((float[]) a), (float[]) ((float[]) b)); - } else if (a instanceof Object[]) { - return Arrays.equals((Object[]) ((Object[]) a), (Object[]) ((Object[]) b)); - } else { - throw new RuntimeException("未实现"); - } - } else { - return Objects.equals(a, b); - } - } else { - return false; - } - } - - public static boolean isTrue(Boolean boolean_) { - return boolean_ != null && isEquals(boolean_, true); - } - - public static boolean isTrue(Boolean targetBoolean, boolean defaultBoolean) { - return targetBoolean == null ? defaultBoolean : targetBoolean; - } - - public static boolean isFalse(Boolean boolean_) { - return boolean_ != null && isEquals(boolean_, false); - } - - - public static boolean isObject(Class clazz) { - if (clazz == null) { - return false; - } else if (clazz.getClass().isArray()) { - return false; - } else { - return Object.class.isAssignableFrom(clazz); - } - } -} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerService.java index 54ab3df..e0f0a7c 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerService.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerService.java @@ -1,52 +1,51 @@ -package org.nl.acs.opc; - -import org.nl.acs.device_driver.driver.ItemValue; -import org.openscada.opc.lib.da.Group; - -/** - * @author ldjun - * @version 1.0 - * @date 2023年02月01日 11:26 - * @desc desc - */ -public interface OpcServerService { - - /** - * 重新加载 - */ - void reload(); - - /** - * 获取服务器 - * @param var1 - * @return - */ - Group getServer(String var1); - - /** - * 获取服务器 - * @param var1 - * @return - */ - Group getServerByNewConn(String var1); - - /** - * 写入整数 - * @param var1 - * @param var2 - */ - void writeInteger(String var1, ItemValue... var2); - - /** - * 写入整数 - * @param var1 - * @param var2 - */ - void writeIntegerByNewConn(String var1, ItemValue... var2); - - /** - * 清除服务器 - * @param var1 - */ - void clearServer(String var1); -} +//package org.nl.acs.opc; +// +//import org.nl.acs.device_driver.driver.ItemValue; +// +///** +// * @author ldjun +// * @version 1.0 +// * @date 2023年02月01日 11:26 +// * @desc desc +// */ +//public interface OpcServerService { +// +// /** +// * 重新加载 +// */ +// void reload(); +// +// /** +// * 获取服务器 +// * @param var1 +// * @return +// */ +// Group getServer(String var1); +// +// /** +// * 获取服务器 +// * @param var1 +// * @return +// */ +// Group getServerByNewConn(String var1); +// +// /** +// * 写入整数 +// * @param var1 +// * @param var2 +// */ +// void writeInteger(String var1, ItemValue... var2); +// +// /** +// * 写入整数 +// * @param var1 +// * @param var2 +// */ +// void writeIntegerByNewConn(String var1, ItemValue... var2); +// +// /** +// * 清除服务器 +// * @param var1 +// */ +// void clearServer(String var1); +//} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerServiceImpl.java index 0629b1e..6ddc792 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerServiceImpl.java @@ -1,245 +1,245 @@ -package org.nl.acs.opc; - -import cn.hutool.core.util.StrUtil; -import org.jinterop.dcom.common.JIException; -import org.nl.acs.auto.initial.ApplicationAutoInitial; -import org.nl.acs.device_driver.driver.ItemValue; -import org.nl.acs.opc.service.dto.OpcServerManageDto; -import org.openscada.opc.lib.common.NotConnectedException; -import org.openscada.opc.lib.da.Group; -import org.openscada.opc.lib.da.Server; -import org.openscada.opc.lib.da.UnknownGroupException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.net.UnknownHostException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * @author ldjun - * @version 1.0 - * @date 2023年02月01日 11:27 - * @desc desc - */ -@Service -public class OpcServerServiceImpl implements OpcServerService, ApplicationAutoInitial { - - private static final Logger log = LoggerFactory.getLogger(OpcServerServiceImpl.class); - @Autowired - OpcServerManageService opcServerManageService; - Map opcServerManageDtos = new HashMap(); - Map servers = Collections.synchronizedMap(new HashMap()); - Map groups = Collections.synchronizedMap(new HashMap()); - - public OpcServerServiceImpl() { - } - - /** - * 加载opc服务,启动opc线程 - * - * @throws Exception - */ - @Override - public void autoInitial() throws Exception { - this.reload(); // 加载opc服务 - if (OpcConfig.auto_start_opc) { - Thread t = - new Thread(() -> { - Iterator var1 = OpcServerServiceImpl.this.opcServerManageDtos.values().iterator(); - - while (var1.hasNext()) { - OpcServerManageDto dto = (OpcServerManageDto) var1.next(); - - try { - OpcServerServiceImpl.this.getServer(dto.getOpc_code()); - OpcServerServiceImpl.log.info("加载opc server {}", dto.getOpc_code()); - } catch (Exception var4) { - OpcServerServiceImpl.log.warn("启动无法载入servers", var4); - } - } - }); - t.start(); - } - } - - @Override - public synchronized void reload() { - this.opcServerManageDtos = this.opcServerManageService.queryAllServerMap(); - this.opcServerManageDtos = Collections.synchronizedMap(this.opcServerManageDtos); - } - - @Override - public synchronized Group getServer(String code) { - synchronized (this.buildLock(code)) { - Group group = null; - group = (Group) this.groups.get(code); - if (group != null) { - label68: - { - Group var10000; - try { - if (!group.isActive()) { - break label68; - } - - var10000 = group; - } catch (JIException var14) { - log.error(code, var14); - break label68; - } - - return var10000; - } - } - - Server server = (Server) this.servers.get(code); - boolean needcreate = false; - String groupName = code; - if (server == null) { - needcreate = true; - } else { - try { - group = server.findGroup(groupName); - } catch (UnknownHostException | JIException | UnknownGroupException | NotConnectedException | - IllegalArgumentException var13) { - log.error(code, var13); - needcreate = true; - } - } - - if (needcreate) { - OpcServerManageDto dto = (OpcServerManageDto) this.opcServerManageDtos.get(code); - if (dto == null) { - throw new RuntimeException(code + "不存在"); - } - -// if (server!=null){ -// server.disconnect(); -// server=null; +//package org.nl.acs.opc; +// +//import cn.hutool.core.util.StrUtil; +//import org.jinterop.dcom.common.JIException; +//import org.nl.acs.auto.initial.ApplicationAutoInitial; +//import org.nl.acs.device_driver.driver.ItemValue; +//import org.nl.acs.opc.service.dto.OpcServerManageDto; +//import org.openscada.opc.lib.common.NotConnectedException; +//import org.openscada.opc.lib.da.Group; +//import org.openscada.opc.lib.da.Server; +//import org.openscada.opc.lib.da.UnknownGroupException; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.stereotype.Service; +// +//import java.net.UnknownHostException; +//import java.util.Collections; +//import java.util.HashMap; +//import java.util.Iterator; +//import java.util.Map; +// +///** +// * @author ldjun +// * @version 1.0 +// * @date 2023年02月01日 11:27 +// * @desc desc +// */ +//@Service +//public class OpcServerServiceImpl implements OpcServerService, ApplicationAutoInitial { +// +// private static final Logger log = LoggerFactory.getLogger(OpcServerServiceImpl.class); +// @Autowired +// OpcServerManageService opcServerManageService; +// Map opcServerManageDtos = new HashMap(); +// Map servers = Collections.synchronizedMap(new HashMap()); +// Map groups = Collections.synchronizedMap(new HashMap()); +// +// public OpcServerServiceImpl() { +// } +// +// /** +// * 加载opc服务,启动opc线程 +// * +// * @throws Exception +// */ +// @Override +// public void autoInitial() throws Exception { +// this.reload(); // 加载opc服务 +// if (OpcConfig.auto_start_opc) { +// Thread t = +// new Thread(() -> { +// Iterator var1 = OpcServerServiceImpl.this.opcServerManageDtos.values().iterator(); +// +// while (var1.hasNext()) { +// OpcServerManageDto dto = (OpcServerManageDto) var1.next(); +// +// try { +// OpcServerServiceImpl.this.getServer(dto.getOpc_code()); +// OpcServerServiceImpl.log.info("加载opc server {}", dto.getOpc_code()); +// } catch (Exception var4) { +// OpcServerServiceImpl.log.warn("启动无法载入servers", var4); +// } +// } +// }); +// t.start(); // } - - if (server == null) { - server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); - } - - try { - group = server.addGroup(groupName); - } catch (Exception var12) { - this.clearServer(code); - ThreadUtl.sleep(5000L); - log.warn("获取opc出错重新获取", code, var12); - server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); - try { - group = server.addGroup(groupName); - } catch (Exception var11) { - throw new RuntimeException(var12); - } - } - - this.servers.put(code, server); - this.groups.put(code, group); - } - - return group; - } - } - - @Override - public Group getServerByNewConn(String code) { - synchronized (this.buildLock(code)) { - - Server server = (Server) this.servers.get(code); - if (server != null) { - this.clearServer(code); - } - - OpcServerManageDto dto = (OpcServerManageDto) this.opcServerManageDtos.get(code); - if (dto == null) { - throw new RuntimeException(code + "不存在"); - } - -// if (server == null) { - server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); +// } +// +// @Override +// public synchronized void reload() { +// this.opcServerManageDtos = this.opcServerManageService.queryAllServerMap(); +// this.opcServerManageDtos = Collections.synchronizedMap(this.opcServerManageDtos); +// } +// +// @Override +// public synchronized Group getServer(String code) { +// synchronized (this.buildLock(code)) { +// Group group = null; +// group = (Group) this.groups.get(code); +// if (group != null) { +// label68: +// { +// Group var10000; +// try { +// if (!group.isActive()) { +// break label68; +// } +// +// var10000 = group; +// } catch (JIException var14) { +// log.error(code, var14); +// break label68; +// } +// +// return var10000; +// } +// } +// +// Server server = (Server) this.servers.get(code); +// boolean needcreate = false; +// String groupName = code; +// if (server == null) { +// needcreate = true; +// } else { +// try { +// group = server.findGroup(groupName); +// } catch (UnknownHostException | JIException | UnknownGroupException | NotConnectedException | +// IllegalArgumentException var13) { +// log.error(code, var13); +// needcreate = true; +// } +// } +// +// if (needcreate) { +// OpcServerManageDto dto = (OpcServerManageDto) this.opcServerManageDtos.get(code); +// if (dto == null) { +// throw new RuntimeException(code + "不存在"); +// } +// +//// if (server!=null){ +//// server.disconnect(); +//// server=null; +//// } +// +// if (server == null) { +// server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); +// } +// +// try { +// group = server.addGroup(groupName); +// } catch (Exception var12) { +// this.clearServer(code); +// ThreadUtl.sleep(5000L); +// log.warn("获取opc出错重新获取", code, var12); +// server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); +// try { +// group = server.addGroup(groupName); +// } catch (Exception var11) { +// throw new RuntimeException(var12); +// } +// } +// +// this.servers.put(code, server); +// this.groups.put(code, group); +// } +// +// return group; // } - String groupName = code; - Group group = null; - - try { - group = server.addGroup(groupName); - } catch (Exception var12) { - this.clearServer(code); - ThreadUtl.sleep(2000L); - log.warn("获取opc出错重新获取", code, var12); - server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); - try { - group = server.addGroup(groupName); - } catch (Exception var11) { - throw new RuntimeException(var12); - } - } - - this.servers.put(code, server); - this.groups.put(code, group); - return group; - } - } - - @Override - public synchronized void clearServer(String code) { - try { - Server server = (Server) this.servers.get(code); - if (server != null) { - server.disconnect(); - } - - } catch (Exception e) { - e.printStackTrace(); - log.error("清理server异常,", e.getMessage()); - } - - this.servers.remove(code); - this.groups.remove(code); - } - - @Override - public void writeInteger(String code, ItemValue... values) { - try { - Group group = this.getServer(code); - OpcUtl.writeValue(group, values); - } catch (Exception var4) { - this.clearServer(code); - log.warn("写入出错opc server {} 重新加载", code, var4); - ThreadUtl.sleep(5000L); - throw var4; - } - } - - @Override - public void writeIntegerByNewConn(String code, ItemValue... values) { - try { - Group group = this.getServerByNewConn(code); - OpcUtl.writeValue(group, values); - } catch (Exception var4) { - this.clearServer(code); - log.info("写入出错opc server {} 重新加载", code, var4); - ThreadUtl.sleep(1000L); - throw var4; - } - } - - private String buildLock(String key) { - if (StrUtil.isEmpty(key)) { - key = ""; - } - StringBuilder builder = new StringBuilder(); - builder.append("OpcServerService."); - builder.append(key); - String lock = builder.toString().intern(); - return lock; - } -} +// } +// +// @Override +// public Group getServerByNewConn(String code) { +// synchronized (this.buildLock(code)) { +// +// Server server = (Server) this.servers.get(code); +// if (server != null) { +// this.clearServer(code); +// } +// +// OpcServerManageDto dto = (OpcServerManageDto) this.opcServerManageDtos.get(code); +// if (dto == null) { +// throw new RuntimeException(code + "不存在"); +// } +// +//// if (server == null) { +// server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); +//// } +// String groupName = code; +// Group group = null; +// +// try { +// group = server.addGroup(groupName); +// } catch (Exception var12) { +// this.clearServer(code); +// ThreadUtl.sleep(2000L); +// log.warn("获取opc出错重新获取", code, var12); +// server = OpcServerUtl.getServerWithOutException(dto.getOpc_host(), StrUtil.trim(dto.getCls_id()), dto.getUser(), dto.getPassword(), StrUtil.trim(dto.getDomain())); +// try { +// group = server.addGroup(groupName); +// } catch (Exception var11) { +// throw new RuntimeException(var12); +// } +// } +// +// this.servers.put(code, server); +// this.groups.put(code, group); +// return group; +// } +// } +// +// @Override +// public synchronized void clearServer(String code) { +// try { +// Server server = (Server) this.servers.get(code); +// if (server != null) { +// server.disconnect(); +// } +// +// } catch (Exception e) { +// e.printStackTrace(); +// log.error("清理server异常,", e.getMessage()); +// } +// +// this.servers.remove(code); +// this.groups.remove(code); +// } +// +// @Override +// public void writeInteger(String code, ItemValue... values) { +// try { +// Group group = this.getServer(code); +// OpcUtl.writeValue(group, values); +// } catch (Exception var4) { +// this.clearServer(code); +// log.warn("写入出错opc server {} 重新加载", code, var4); +// ThreadUtl.sleep(5000L); +// throw var4; +// } +// } +// +// @Override +// public void writeIntegerByNewConn(String code, ItemValue... values) { +// try { +// Group group = this.getServerByNewConn(code); +// OpcUtl.writeValue(group, values); +// } catch (Exception var4) { +// this.clearServer(code); +// log.info("写入出错opc server {} 重新加载", code, var4); +// ThreadUtl.sleep(1000L); +// throw var4; +// } +// } +// +// private String buildLock(String key) { +// if (StrUtil.isEmpty(key)) { +// key = ""; +// } +// StringBuilder builder = new StringBuilder(); +// builder.append("OpcServerService."); +// builder.append(key); +// String lock = builder.toString().intern(); +// return lock; +// } +//} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerUtl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerUtl.java index 49dcca4..32692f2 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerUtl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcServerUtl.java @@ -1,24 +1,24 @@ -package org.nl.acs.opc; - -import cn.hutool.core.util.StrUtil; -import org.openscada.opc.lib.da.Server; - -/** - * @author 20220102CG\noblelift - */ -public class OpcServerUtl { - - public static synchronized Server getServerWithOutException(String host, String clsid, String user, String password, - String domain) { - if (!StrUtil.isEmpty(host) && !StrUtil.isEmpty(clsid) && !StrUtil.isEmpty(user)) { - if (domain == null) { - domain = ""; - } - return OpcUtl.getServer(host, clsid, user, password, domain); -// return OpcUtl.getAutoServer(host, clsid, user, password, domain); - } else { - return null; - } - } - -} +//package org.nl.acs.opc; +// +//import cn.hutool.core.util.StrUtil; +//import org.openscada.opc.lib.da.Server; +// +///** +// * @author 20220102CG\noblelift +// */ +//public class OpcServerUtl { +// +// public static synchronized Server getServerWithOutException(String host, String clsid, String user, String password, +// String domain) { +// if (!StrUtil.isEmpty(host) && !StrUtil.isEmpty(clsid) && !StrUtil.isEmpty(user)) { +// if (domain == null) { +// domain = ""; +// } +// return OpcUtl.getServer(host, clsid, user, password, domain); +//// return OpcUtl.getAutoServer(host, clsid, user, password, domain); +// } else { +// return null; +// } +// } +// +//} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcUtl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcUtl.java index c8248c9..1b44521 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcUtl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/OpcUtl.java @@ -1,293 +1,293 @@ -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.*; -import org.nl.acs.device_driver.driver.ItemValue; -import org.nl.common.exception.BadRequestException; - -import org.nl.config.language.LangProcess; -import org.openscada.opc.lib.common.ConnectionInformation; -import org.openscada.opc.lib.da.*; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; - -/** - * @author 20220102CG\noblelift - */ -@Slf4j -public class OpcUtl { - private static int timeout = 1 * 60 * 1000; - private static String key = "rpc.socketTimeout"; - - static { - checkTimeout(); - } - - public static void checkTimeout() { - if (Integer.getInteger(key, 0).intValue() != timeout) { - System.setProperty(key, String.valueOf(timeout)); - } - - } - - - public static void writeValue(Group group, WriteRequest... requests) throws BadRequestException { - try { - Map e = null; - try { - e = group.write(requests); - group.write(requests); - } catch (Exception e1) { - try { - e = group.write(requests); - } catch (Exception e2) { - e = group.write(requests); - } - } - - boolean is_success = true; - StringBuilder message = new StringBuilder(); - Iterator arg4 = e.keySet().iterator(); - - while (arg4.hasNext()) { - Item item = (Item) arg4.next(); - Integer integer = (Integer) e.get(item); - if (integer.intValue() != 0) { - if (is_success) { - is_success = false; - } - - message.append(item.getId()); - message.append(":error code:"); - message.append(integer); - message.append("; "); - } - } - - if (!is_success) { - // throw new BusinessException(message.toString()); - System.out.println("下发信号失败:" + message.toString()); - System.out.println("下发信号失败原因:" + message.toString()); - log.info("下发信号失败:" + message.toString()); - throw new BadRequestException(message.toString()); - } - } catch (JIException arg7) { - log.info("下发信号失败:" + arg7.getMessage()); - System.out.println("下发信号失败原因:" + arg7.getMessage()); - throw new BadRequestException(arg7.toString()); - } - } - - public static void writeValue(Group group, ItemValue... values) throws BadRequestException { - try { - if (values != null && values.length > 0) { - List ws = new ArrayList(); - ItemValue[] var3 = values; - int var4 = values.length; - - for (int var5 = 0; var5 < var4; ++var5) { - ItemValue value = var3[var5]; - Item item = group.addItem(value.getItem_code()); - ws.add(new WriteRequest(item, getVariant(value.getItem_value()))); - } - - writeValue(group, (WriteRequest[]) ws.toArray(new WriteRequest[0])); - } - - } catch (AddFailedException | JIException var8) { - throw new BadRequestException(var8.toString()); - } - } - - public static JIVariant getVariant(Object object) { - if (object instanceof Integer) { - return getIntegerVariant((Integer) object); - } else if (object instanceof String) { - return getStringVariant((String) object); - } else if (object instanceof byte[]) { - return getByteArrayVariant((byte[]) ((byte[]) object)); - } else if (object instanceof Byte[]) { - return getByteArrayVariant((Byte[]) ((Byte[]) object)); - } else if (object instanceof Boolean) { - return new JIVariant((Boolean) object); - } else if (object instanceof int[]) { - return getByteArrayVariantxx((int[]) ((int[]) object)); - } else if (object instanceof Integer[]) { - JIArray array = new JIArray((Integer) object, false); - JIVariant value = new JIVariant(array); - return value; - } else if (object instanceof JIVariant) { - return (JIVariant) object; - } else { - throw new BadRequestException(LangProcess.msg("error_checkTypes", "int,string,byte[]")); - } - } - - public static Object getValue(Item item, ItemState itemState) throws BadRequestException { - if (NumberUtil.compare(itemState.getQuality(), Short.valueOf(QualityTypeValue.OPC_QUALITY_GOOD)) != 0) { - if (item != null) { - log.debug("value is not good {} : {}", item.getId(), itemState.getQuality()); -// throw new BadRequestException("值不健康进行重连!"); - } else { - log.debug("value is not good {}", itemState.getQuality()); - } - - return null; - } else { - JIVariant value = itemState.getValue(); - return getValue(value, item.getId()); - } - } - - public static Object getValue(JIVariant jiVariant, String id) throws BadRequestException { - try { - Object e = jiVariant.getObject(); - if (e instanceof IJIUnsigned) { - return Integer.valueOf(((IJIUnsigned) e).getValue().intValue()); - } else if (e instanceof Boolean) { - return jiVariant.getObjectAsBoolean() ? Integer.valueOf(1) : Integer.valueOf(0); - } else if (e instanceof JIString) { - return ((JIString) e).getString(); - } else if (!(e instanceof JIArray)) { - if (e instanceof Integer) { - return jiVariant.getObject(); - } else if (e instanceof Short) { - return jiVariant.getObject(); - } else if (e instanceof Float) { - return jiVariant.getObject(); - } else { - System.err.println(id + "不明类型" + e.getClass()); - if (jiVariant.getType() == 0) { - System.err.println("因类型为emtpy 返回 null"); - return null; - } else if (jiVariant.getType() == 1) { - System.err.println("因类型为null 返回 null"); - return null; - } else { - return jiVariant.getObject(); - } - } - } else { - Class clazz = ((JIArray) e).getArrayClass(); - int[] r; - int i; - if (JIUnsignedByte.class.isAssignableFrom(clazz)) { - JIUnsignedByte[] arg7 = (JIUnsignedByte[]) ((JIUnsignedByte[]) ((JIArray) e).getArrayInstance()); - r = new int[arg7.length]; - - for (i = 0; i < arg7.length; ++i) { - r[i] = arg7[i].getValue().byteValue(); - } - - return r; - } else if (!JIUnsignedShort.class.isAssignableFrom(clazz)) { - System.err.println(id + "不明类型"); - if (jiVariant.getType() == 0) { - System.err.println("因类型为emtpy 返回 null"); - return null; - } else if (jiVariant.getType() == 1) { - System.err.println("因类型为null 返回 null"); - return null; - } else { - return ((JIArray) e).getArrayInstance(); - } - } else { - JIUnsignedShort[] array = (JIUnsignedShort[]) ((JIUnsignedShort[]) ((JIArray) e) - .getArrayInstance()); - r = new int[array.length]; - - for (i = 0; i < array.length; ++i) { - r[i] = array[i].getValue().intValue(); - } - - return r; - } - } - } catch (JIException e) { - throw new BadRequestException(e.getMessage()); - } - } - - - public static Server getServer(String host, String clsid, String user, String password, String domain) - throws BadRequestException { - checkTimeout(); - Server server = null; - - try { - server = new Server(getConnection(host, clsid, user, password, domain), - Executors.newSingleThreadScheduledExecutor()); - server.connect(); - return server; - } catch (Exception e) { - throw new BadRequestException(e.getMessage()); - } - } - - public static Server getAutoServer(String host, String clsid, String user, String password, String domain) throws BadRequestException { - checkTimeout(); - Server server = null; - server = new Server(getConnection(host, clsid, user, password, domain), Executors.newSingleThreadScheduledExecutor()); - AutoReconnectController autoReconnectController = new AutoReconnectController(server); - autoReconnectController.connect(); - return server; - } - - public static ConnectionInformation getConnection(String host, String clsid, String user, String password, - String domain) { - ConnectionInformation connection = new ConnectionInformation(); - connection.setHost(host); - connection.setClsid(clsid); - connection.setUser(user); - connection.setPassword(password); - connection.setDomain(domain); - return connection; - } - - public static JIVariant getByteArrayVariantxx(int[] bytes) { - Integer[] byte_Data = new Integer[bytes.length]; - - for (int i = 0; i < bytes.length; ++i) { - byte_Data[i] = bytes[i]; - } - - JIArray array = new JIArray(byte_Data, false); - JIVariant value = new JIVariant(array); - return value; - } - - public static JIVariant getIntegerVariant(Integer integer) { - return new JIVariant(integer); - } - - public static JIVariant getStringVariant(String string) { - return new JIVariant(string); - } - - public static JIVariant getByteArrayVariant(byte[] bytes) { - Byte[] byte_Data = new Byte[bytes.length]; - - for (int i = 0; i < bytes.length; ++i) { - byte_Data[i] = bytes[i]; - } - - JIArray array = new JIArray(byte_Data, false); - JIVariant value = new JIVariant(array); - return value; - } - - public static JIVariant getByteArrayVariant(Byte[] bytes) { - JIArray array = new JIArray(bytes, false); - JIVariant value = new JIVariant(array); - return value; - } - - -} - +//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.*; +//import org.nl.acs.device_driver.driver.ItemValue; +//import org.nl.common.exception.BadRequestException; +// +//import org.nl.config.language.LangProcess; +//import org.openscada.opc.lib.common.ConnectionInformation; +//import org.openscada.opc.lib.da.*; +// +//import java.util.ArrayList; +//import java.util.Iterator; +//import java.util.List; +//import java.util.Map; +//import java.util.concurrent.Executors; +// +///** +// * @author 20220102CG\noblelift +// */ +//@Slf4j +//public class OpcUtl { +// private static int timeout = 1 * 60 * 1000; +// private static String key = "rpc.socketTimeout"; +// +// static { +// checkTimeout(); +// } +// +// public static void checkTimeout() { +// if (Integer.getInteger(key, 0).intValue() != timeout) { +// System.setProperty(key, String.valueOf(timeout)); +// } +// +// } +// +// +// public static void writeValue(Group group, WriteRequest... requests) throws BadRequestException { +// try { +// Map e = null; +// try { +// e = group.write(requests); +// group.write(requests); +// } catch (Exception e1) { +// try { +// e = group.write(requests); +// } catch (Exception e2) { +// e = group.write(requests); +// } +// } +// +// boolean is_success = true; +// StringBuilder message = new StringBuilder(); +// Iterator arg4 = e.keySet().iterator(); +// +// while (arg4.hasNext()) { +// Item item = (Item) arg4.next(); +// Integer integer = (Integer) e.get(item); +// if (integer.intValue() != 0) { +// if (is_success) { +// is_success = false; +// } +// +// message.append(item.getId()); +// message.append(":error code:"); +// message.append(integer); +// message.append("; "); +// } +// } +// +// if (!is_success) { +// // throw new BusinessException(message.toString()); +// System.out.println("下发信号失败:" + message.toString()); +// System.out.println("下发信号失败原因:" + message.toString()); +// log.info("下发信号失败:" + message.toString()); +// throw new BadRequestException(message.toString()); +// } +// } catch (JIException arg7) { +// log.info("下发信号失败:" + arg7.getMessage()); +// System.out.println("下发信号失败原因:" + arg7.getMessage()); +// throw new BadRequestException(arg7.toString()); +// } +// } +// +// public static void writeValue(Group group, ItemValue... values) throws BadRequestException { +// try { +// if (values != null && values.length > 0) { +// List ws = new ArrayList(); +// ItemValue[] var3 = values; +// int var4 = values.length; +// +// for (int var5 = 0; var5 < var4; ++var5) { +// ItemValue value = var3[var5]; +// Item item = group.addItem(value.getItem_code()); +// ws.add(new WriteRequest(item, getVariant(value.getItem_value()))); +// } +// +// writeValue(group, (WriteRequest[]) ws.toArray(new WriteRequest[0])); +// } +// +// } catch (AddFailedException | JIException var8) { +// throw new BadRequestException(var8.toString()); +// } +// } +// +// public static JIVariant getVariant(Object object) { +// if (object instanceof Integer) { +// return getIntegerVariant((Integer) object); +// } else if (object instanceof String) { +// return getStringVariant((String) object); +// } else if (object instanceof byte[]) { +// return getByteArrayVariant((byte[]) ((byte[]) object)); +// } else if (object instanceof Byte[]) { +// return getByteArrayVariant((Byte[]) ((Byte[]) object)); +// } else if (object instanceof Boolean) { +// return new JIVariant((Boolean) object); +// } else if (object instanceof int[]) { +// return getByteArrayVariantxx((int[]) ((int[]) object)); +// } else if (object instanceof Integer[]) { +// JIArray array = new JIArray((Integer) object, false); +// JIVariant value = new JIVariant(array); +// return value; +// } else if (object instanceof JIVariant) { +// return (JIVariant) object; +// } else { +// throw new BadRequestException(LangProcess.msg("error_checkTypes", "int,string,byte[]")); +// } +// } +// +// public static Object getValue(Item item, ItemState itemState) throws BadRequestException { +// if (NumberUtil.compare(itemState.getQuality(), Short.valueOf(QualityTypeValue.OPC_QUALITY_GOOD)) != 0) { +// if (item != null) { +// log.debug("value is not good {} : {}", item.getId(), itemState.getQuality()); +//// throw new BadRequestException("值不健康进行重连!"); +// } else { +// log.debug("value is not good {}", itemState.getQuality()); +// } +// +// return null; +// } else { +// JIVariant value = itemState.getValue(); +// return getValue(value, item.getId()); +// } +// } +// +// public static Object getValue(JIVariant jiVariant, String id) throws BadRequestException { +// try { +// Object e = jiVariant.getObject(); +// if (e instanceof IJIUnsigned) { +// return Integer.valueOf(((IJIUnsigned) e).getValue().intValue()); +// } else if (e instanceof Boolean) { +// return jiVariant.getObjectAsBoolean() ? Integer.valueOf(1) : Integer.valueOf(0); +// } else if (e instanceof JIString) { +// return ((JIString) e).getString(); +// } else if (!(e instanceof JIArray)) { +// if (e instanceof Integer) { +// return jiVariant.getObject(); +// } else if (e instanceof Short) { +// return jiVariant.getObject(); +// } else if (e instanceof Float) { +// return jiVariant.getObject(); +// } else { +// System.err.println(id + "不明类型" + e.getClass()); +// if (jiVariant.getType() == 0) { +// System.err.println("因类型为emtpy 返回 null"); +// return null; +// } else if (jiVariant.getType() == 1) { +// System.err.println("因类型为null 返回 null"); +// return null; +// } else { +// return jiVariant.getObject(); +// } +// } +// } else { +// Class clazz = ((JIArray) e).getArrayClass(); +// int[] r; +// int i; +// if (JIUnsignedByte.class.isAssignableFrom(clazz)) { +// JIUnsignedByte[] arg7 = (JIUnsignedByte[]) ((JIUnsignedByte[]) ((JIArray) e).getArrayInstance()); +// r = new int[arg7.length]; +// +// for (i = 0; i < arg7.length; ++i) { +// r[i] = arg7[i].getValue().byteValue(); +// } +// +// return r; +// } else if (!JIUnsignedShort.class.isAssignableFrom(clazz)) { +// System.err.println(id + "不明类型"); +// if (jiVariant.getType() == 0) { +// System.err.println("因类型为emtpy 返回 null"); +// return null; +// } else if (jiVariant.getType() == 1) { +// System.err.println("因类型为null 返回 null"); +// return null; +// } else { +// return ((JIArray) e).getArrayInstance(); +// } +// } else { +// JIUnsignedShort[] array = (JIUnsignedShort[]) ((JIUnsignedShort[]) ((JIArray) e) +// .getArrayInstance()); +// r = new int[array.length]; +// +// for (i = 0; i < array.length; ++i) { +// r[i] = array[i].getValue().intValue(); +// } +// +// return r; +// } +// } +// } catch (JIException e) { +// throw new BadRequestException(e.getMessage()); +// } +// } +// +// +// public static Server getServer(String host, String clsid, String user, String password, String domain) +// throws BadRequestException { +// checkTimeout(); +// Server server = null; +// +// try { +// server = new Server(getConnection(host, clsid, user, password, domain), +// Executors.newSingleThreadScheduledExecutor()); +// server.connect(); +// return server; +// } catch (Exception e) { +// throw new BadRequestException(e.getMessage()); +// } +// } +// +// public static Server getAutoServer(String host, String clsid, String user, String password, String domain) throws BadRequestException { +// checkTimeout(); +// Server server = null; +// server = new Server(getConnection(host, clsid, user, password, domain), Executors.newSingleThreadScheduledExecutor()); +// AutoReconnectController autoReconnectController = new AutoReconnectController(server); +// autoReconnectController.connect(); +// return server; +// } +// +// public static ConnectionInformation getConnection(String host, String clsid, String user, String password, +// String domain) { +// ConnectionInformation connection = new ConnectionInformation(); +// connection.setHost(host); +// connection.setClsid(clsid); +// connection.setUser(user); +// connection.setPassword(password); +// connection.setDomain(domain); +// return connection; +// } +// +// public static JIVariant getByteArrayVariantxx(int[] bytes) { +// Integer[] byte_Data = new Integer[bytes.length]; +// +// for (int i = 0; i < bytes.length; ++i) { +// byte_Data[i] = bytes[i]; +// } +// +// JIArray array = new JIArray(byte_Data, false); +// JIVariant value = new JIVariant(array); +// return value; +// } +// +// public static JIVariant getIntegerVariant(Integer integer) { +// return new JIVariant(integer); +// } +// +// public static JIVariant getStringVariant(String string) { +// return new JIVariant(string); +// } +// +// public static JIVariant getByteArrayVariant(byte[] bytes) { +// Byte[] byte_Data = new Byte[bytes.length]; +// +// for (int i = 0; i < bytes.length; ++i) { +// byte_Data[i] = bytes[i]; +// } +// +// JIArray array = new JIArray(byte_Data, false); +// JIVariant value = new JIVariant(array); +// return value; +// } +// +// public static JIVariant getByteArrayVariant(Byte[] bytes) { +// JIArray array = new JIArray(bytes, false); +// JIVariant value = new JIVariant(array); +// return value; +// } +// +// +//} +// diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/domain/Opc.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/domain/Opc.java index a97d7e0..6661f7d 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/domain/Opc.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/domain/Opc.java @@ -33,63 +33,66 @@ import java.io.Serializable; public class Opc extends CommonModel implements Serializable { private static final long serialVersionUID = 1L; - + @TableId(type = IdType.ASSIGN_ID) private String opc_id; - + @NotBlank private String opc_code; - + @NotBlank private String opc_name; - + private String opc_host; - + @NotBlank + private String topic; + + private String user; - + @NotBlank private String password; - + private String prog_id; - + private String cls_id; - + private String domain; - + private String remark; - + @NotBlank private String is_active; - + @NotBlank private String is_delete; - + @NotBlank @TableField(fill = FieldFill.INSERT) private String create_by; - + @NotBlank @TableField(fill = FieldFill.INSERT) private String create_time; - + @TableField(fill = FieldFill.INSERT_UPDATE) private String update_by; - + @TableField(fill = FieldFill.INSERT_UPDATE) private String update_time; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/dto/OpcDto.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/dto/OpcDto.java index e7b8169..e87744e 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/dto/OpcDto.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/dto/OpcDto.java @@ -12,7 +12,6 @@ import java.util.Date; import java.sql.Timestamp; - /** * @author jiaolm * @date 2023-05-09 @@ -26,52 +25,55 @@ import java.sql.Timestamp; public class OpcDto implements Serializable { private static final long serialVersionUID = 1L; - + private String opc_id; - + private String opc_code; - + private String opc_name; - - private String opc_host; + private String opc_host; + + private String topic; + + private String user; - + private String password; - + private String prog_id; - + private String cls_id; - + private String domain; - + private String remark; - + private String is_active; - + private String is_delete; - + private String create_by; - + private String create_time; - + private String update_by; - + private String update_time; private String hasChildren; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/impl/OpcServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/impl/OpcServiceImpl.java index ac7f6c1..ca2437b 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/impl/OpcServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/opc/service/impl/OpcServiceImpl.java @@ -13,7 +13,6 @@ import lombok.extern.slf4j.Slf4j; import org.nl.acs.common.base.CommonFinalParam; import org.nl.acs.opc.domain.OpcPlc; import org.nl.acs.opc.service.mapper.OpcPlcMapper; -import org.nl.acs.utils.ReadUtil; import org.nl.acs.common.base.PageInfo; import org.nl.acs.common.base.QueryHelpMybatisPlus; import org.nl.acs.common.base.impl.CommonServiceImpl; @@ -285,12 +284,13 @@ public class OpcServiceImpl extends CommonServiceImpl implements @Override public HashMap getmeteal(Map whereJson) { - HashMap map = new HashMap<>(); - String host = (String) whereJson.get("opc_host"); - String user = (String) whereJson.get("user"); - String password = (String) whereJson.get("password"); - List> maps = ReadUtil.showAllOpcServer(host, user, password, ""); - return (HashMap) maps.get(0); +// HashMap map = new HashMap<>(); +// String host = (String) whereJson.get("opc_host"); +// String user = (String) whereJson.get("user"); +// String password = (String) whereJson.get("password"); +// List> maps = ReadUtil.showAllOpcServer(host, user, password, ""); +// return (HashMap) maps.get(0); + return null; } @Override diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/storage_cell/service/mapper/StorageCellMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/storage_cell/service/mapper/StorageCellMapper.java index 907c801..36e339d 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/storage_cell/service/mapper/StorageCellMapper.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/storage_cell/service/mapper/StorageCellMapper.java @@ -1,8 +1,8 @@ package org.nl.acs.storage_cell.service.mapper; +import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; import org.nl.acs.common.base.CommonMapper; import org.nl.acs.storage_cell.domain.StorageCell; import org.springframework.stereotype.Repository; @@ -19,7 +19,7 @@ public interface StorageCellMapper extends CommonMapper { * @param storage_code * @return */ - @Select("delete from acs_storage_cell where substring_index( storage_code,'-',1) = #{storage_code}") + @Delete("delete from acs_storage_cell where substring_index( storage_code,'-',1) = #{storage_code}") int deleteByStorageCode(@Param("storage_code") String storage_code); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsDataAccessor.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsDataAccessor.java new file mode 100644 index 0000000..06591f3 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsDataAccessor.java @@ -0,0 +1,14 @@ +package org.nl.acs.udw.mqttUdw; + +import java.util.List; + +/** + * @author onepiece + */ +public interface ItemsDataAccessor { + List getAllKey(); + + Object getValue(String key); + + void setValue(String key, Object value); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsProcessService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsProcessService.java new file mode 100644 index 0000000..5ed1f10 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/ItemsProcessService.java @@ -0,0 +1,34 @@ +package org.nl.acs.udw.mqttUdw; + +import org.nl.acs.udw.mqttUdw.service.ItemData; +import org.nl.acs.udw.mqttUdw.service.ItemUnit; + +import java.util.List; + +/** + * @author onepiece + */ +public interface ItemsProcessService { + /** + * 获取所有的key + * + * @return + */ + List getAllUnifiedKey(); + + /** + * 根据key获取数据单元 + * + * @param key + * @return + */ + ItemUnit getItemUnit(String key); + + ItemData getItemData(String var1, String var2); + + Object getValue(String var1, String var2); + + void setValue(String var1, String var2, Object var3); + + List getAllDataKey(String var1); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemDataAccessorFactory.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemDataAccessorFactory.java new file mode 100644 index 0000000..0d8e63d --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemDataAccessorFactory.java @@ -0,0 +1,18 @@ +package org.nl.acs.udw.mqttUdw.factory; + +import org.nl.acs.udw.mqttUdw.ItemsDataAccessor; +import org.nl.acs.udw.mqttUdw.service.ItemsDataAccessorImpl; + +/** + * @author onepiece + */ +public class ItemDataAccessorFactory { + + private static final ItemsDataAccessorImpl itemsDataAccessor = new ItemsDataAccessorImpl(); + + public static ItemsDataAccessor getItemsDataAccessor(String unified_key) { + itemsDataAccessor.setUnifiedKey(unified_key); + itemsDataAccessor.setItemsProcess(ItemsProcessServiceFactory.getItemsUnifyProcess()); + return itemsDataAccessor; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemsProcessServiceFactory.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemsProcessServiceFactory.java new file mode 100644 index 0000000..1f05a86 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/factory/ItemsProcessServiceFactory.java @@ -0,0 +1,17 @@ +package org.nl.acs.udw.mqttUdw.factory; + +import org.nl.acs.udw.mqttUdw.ItemsProcessService; +import org.nl.acs.udw.mqttUdw.service.ItemsProcessImpl; + +/** + * @author onepiece + */ +public class ItemsProcessServiceFactory { + + private static final ItemsProcessService itemsProcess = new ItemsProcessImpl(); + + + public static ItemsProcessService getItemsUnifyProcess() { + return itemsProcess; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemData.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemData.java new file mode 100644 index 0000000..78d3f90 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemData.java @@ -0,0 +1,28 @@ +package org.nl.acs.udw.mqttUdw.service; + +import lombok.Data; + +import java.util.Date; + +/** + * @author onepiece + */ +@Data +public class ItemData { + private Object value; + private Date last_modify_date; + + public ItemData() { + this.last_modify_date = new Date(); + } + + public ItemData(Object value) { + this.value = value; + this.last_modify_date = new Date(); + } + + public void changeValue(Object value) { + this.value = value; + this.last_modify_date = new Date(); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemUnit.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemUnit.java new file mode 100644 index 0000000..eb986e1 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemUnit.java @@ -0,0 +1,22 @@ +package org.nl.acs.udw.mqttUdw.service; + +import lombok.Data; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author onepiece + */ +@Data +public class ItemUnit { + private String unifiedKey; + private Map storage = new ConcurrentHashMap<>(); + private Map> history = new ConcurrentHashMap<>(); + + public ItemUnit(String unifiedKey) { + this.unifiedKey = unifiedKey; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsDataAccessorImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsDataAccessorImpl.java new file mode 100644 index 0000000..ce03739 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsDataAccessorImpl.java @@ -0,0 +1,39 @@ +package org.nl.acs.udw.mqttUdw.service; + +import org.nl.acs.udw.mqttUdw.ItemsDataAccessor; +import org.nl.acs.udw.mqttUdw.ItemsProcessService; + +import java.util.List; + +/** + * @author onepiece + */ +public class ItemsDataAccessorImpl implements ItemsDataAccessor { + + private String unified_key; + private ItemsProcessService itemsProcess; + + + public void setUnifiedKey(String unified_key) { + this.unified_key = unified_key; + } + + public void setItemsProcess(ItemsProcessService itemsProcess) { + this.itemsProcess = itemsProcess; + } + + @Override + public List getAllKey() { + return this.itemsProcess.getAllDataKey(this.unified_key); + } + + @Override + public Object getValue(String key) { + return this.itemsProcess.getValue(this.unified_key, key); + } + + @Override + public void setValue(String key, Object value) { + this.itemsProcess.setValue(this.unified_key, key, value); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsProcessImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsProcessImpl.java new file mode 100644 index 0000000..937ffc6 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/udw/mqttUdw/service/ItemsProcessImpl.java @@ -0,0 +1,127 @@ +package org.nl.acs.udw.mqttUdw.service; + +import lombok.extern.slf4j.Slf4j; +import org.nl.acs.udw.UdwConfig; +import org.nl.acs.udw.UnifiedDataAppService; +import org.nl.acs.udw.mqttUdw.ItemsProcessService; +import org.nl.common.exception.BadRequestException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author onepiece + */ +@Slf4j +public class ItemsProcessImpl implements ItemsProcessService { + private Map factory = new ConcurrentHashMap<>(); + + public ItemsProcessImpl() { + } + + + @Override + public List getAllUnifiedKey() { + return new ArrayList(this.factory.keySet()); + } + + @Override + public ItemUnit getItemUnit(String unified_key) { + ItemUnit itemUnit = this.factory.get(unified_key); + return itemUnit == null ? null : itemUnit; + } + + @Override + public List getAllDataKey(String unified_key) { + ItemUnit itemUnit = (ItemUnit) this.factory.get(unified_key); + if (itemUnit == null) { + return new ArrayList(); + } else { + Map storage = itemUnit.getStorage(); + return new ArrayList(storage.keySet()); + } + } + + @Override + public ItemData getItemData(String unified_key, String key) { + ItemUnit itemUnit = this.getItemUnit(unified_key); + if (itemUnit == null) { + return null; + } else { + Map storage = itemUnit.getStorage(); + return (ItemData) storage.get(key); + } + } + + @Override + public Object getValue(String unified_key, String key) { + ItemData itemData = this.getItemData(unified_key, key); + return itemData == null ? null : itemData.getValue(); + } + + + @Override + public void setValue(String unified_key, String key, Object value) { + this.setValue(unified_key, key, value, false, true); + } + + + public synchronized void setValue(String unified_key, String key, Object value, boolean save, boolean is_log) { + if (unified_key == null) { + throw new BadRequestException(""); + //throw new BusinessException(SystemMessage.cant_be_empty, new Object[]{"unified_key"}); + } else if (key == null) { + throw new BadRequestException(""); + //throw new BusinessException(SystemMessage.cant_be_empty, new Object[]{"key"}); + } else { + if (!this.factory.containsKey(unified_key)) { + this.factory.put(unified_key, new ItemUnit(unified_key)); + } + + ItemUnit itemUnit = (ItemUnit) this.factory.get(unified_key); + Map storage = itemUnit.getStorage(); + if (!storage.containsKey(key)) { + storage.put(key, new ItemData()); + } + + ItemData itemData = (ItemData) storage.get(key); + if (!UnifiedDataAppService.isEquals(itemData.getValue(), value)) { + Map> history = itemUnit.getHistory(); + List historyItemDatas = (List) history.get(key); + if (historyItemDatas == null) { + history.put(key, new ArrayList()); + } + + ItemData historyData = new ItemData(); + historyData.setLast_modify_date(itemData.getLast_modify_date()); + historyData.setValue(itemData.getValue()); + + while (((List) history.get(key)).size() > UdwConfig.max_history_length) { + ((List) history.get(key)).remove(UdwConfig.max_history_length); + } + + ((List) history.get(key)).add(0, historyData); + Object oldvalue = itemData.getValue(); + itemData.changeValue(value); + if (save) { + /*PersistenceService persistenceService = PersistenceServiceFactory.getPersistenceService(); + persistenceService.saveData(unified_key, key, StringUtl.getString(value)); + if (is_log) { + this.businessLogger.setResource(unified_key, unified_key); + this.businessLogger.setMaterial(key, key); + this.businessLogger.setContainer(StringUtl.getString(value)); + this.businessLogger.log("统一数据源中: unit: {}, key: {}, 值: {} 更改为 {}。", new Object[]{unified_key, key, oldvalue, value}); + }*/ + } + + if (is_log && key != null && !key.endsWith("heartbeat") && !key.endsWith("distancex") && !key.endsWith("distancey") && !key.endsWith("Xwz") && !key.endsWith("Ywz") && !key.endsWith("Zwz")) { + log.trace("统一数据源中: unit: {}, key: {}, 值: {} 更改为 {}。", new Object[]{unified_key, key, oldvalue, value}); + } + } + + } + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/ReadUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/ReadUtil.java index 604d613..1f91b58 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/ReadUtil.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/acs/utils/ReadUtil.java @@ -1,162 +1,162 @@ -package org.nl.acs.utils; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; -import lombok.extern.slf4j.Slf4j; -import org.jinterop.dcom.common.JIException; -import org.jinterop.dcom.core.JIVariant; -import org.nl.acs.device.device_driver.standard_inspect.ItemDto; -import org.nl.acs.device.device_driver.standard_inspect.ItemProtocol; -import org.nl.acs.opc.OpcUtl; -import org.nl.acs.opc.domain.Opc; -import org.nl.acs.opc.service.mapper.OpcMapper; -import org.nl.common.exception.BadRequestException; -import org.nl.config.SpringContextHolder; -import org.nl.config.language.LangProcess; -import org.openscada.opc.dcom.list.ClassDetails; -import org.openscada.opc.lib.common.AlreadyConnectedException; -import org.openscada.opc.lib.common.ConnectionInformation; -import org.openscada.opc.lib.da.*; -import org.openscada.opc.lib.list.Categories; -import org.openscada.opc.lib.list.Category; -import org.openscada.opc.lib.list.ServerList; - -import java.net.UnknownHostException; -import java.util.*; -import java.util.concurrent.Executors; - -/** - * @author 20220102CG\noblelift - */ -@Slf4j -public class ReadUtil { - - static OpcMapper opcMapper = SpringContextHolder.getBean("opcMapper"); - - public static Server getServer(String opc_id) { - //OPC表【acs_opc】 -// JSONObject opcObj = WQLObject.getWQLObject("acs_opc").query("opc_id = '" + opc_id + "'").uniqueResult(0); - - Opc opc = new LambdaQueryChainWrapper<>(opcMapper) - .eq(Opc::getOpc_id, opc_id) - .one(); - //RD1.RD1.1028 - // 连接信息 - ConnectionInformation ci = new ConnectionInformation(); - ci.setHost(opc.getOpc_host()); - ci.setDomain(opc.getDomain()); - ci.setUser(opc.getUser()); - ci.setPassword(opc.getPassword()); - ci.setClsid(opc.getCls_id()); - final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor()); - try { - server.connect(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } catch (JIException e) { - e.printStackTrace(); - } catch (AlreadyConnectedException e) { - e.printStackTrace(); - } - return server; - } - - public static void write(Map strings, Server server) { - try { - //Group group = this.opcServerService.getServer(opcServiceCode); - Group group = server.addGroup(); - Iterator it = strings.keySet().iterator(); - while (it.hasNext()) { - String key = (String) it.next(); - Item byteItem = group.addItem(key); - Object o = strings.get(key); - if (o == null || "".equals(o)) { - break; - } - WriteRequest write1 = new WriteRequest(byteItem, new JIVariant(o.toString())); - List list = new ArrayList(); - list.add(write1); - OpcUtl.writeValue(group, (WriteRequest[]) list.toArray(new WriteRequest[0])); - } - server.disconnect(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public static JSONArray getReadableItemDtos() { - List list = ItemProtocol.getReadableItemDtos(); - JSONArray array = JSONArray.parseArray(JSON.toJSONString(list)); - - return array; - - } - - public static JSONArray getWriteableItemDtos() { - List list = ItemProtocol.getWriteableItemDtos(); - JSONArray array = JSONArray.parseArray(JSON.toJSONString(list)); - return array; - - } - - public static Map read(List itemString, Server server) { - HashMap map = new HashMap(); - try { - Group group = server.addGroup(); - Map items = new LinkedHashMap(); - Iterator is = itemString.iterator(); - - while (is.hasNext()) { - String string = (String) is.next(); - try { - items.put(string, group.addItem(string)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - Map itemStatus = group.read(true, (Item[]) items.values().toArray(new Item[0])); - Set keySet = itemStatus.keySet(); - Iterator it = keySet.iterator(); - - while (it.hasNext()) { - Item key = (Item) it.next(); - Object value = OpcUtl.getValue(key, (ItemState) itemStatus.get(key)); - map.put(key.getId(), value); - } - server.disconnect(); - - } catch (Exception e) { - e.printStackTrace(); - } - - return map; - } - - public static List> showAllOpcServer(String host, String user, String password, String domain) throws BadRequestException { - try { - List> listResult = new ArrayList(); - ServerList serverList = new ServerList(host, user, password, domain); - Collection classDetails = serverList.listServersWithDetails(new Category[]{Categories.OPCDAServer10, Categories.OPCDAServer20, Categories.OPCDAServer30}, new Category[0]); - Iterator var7 = classDetails.iterator(); - - while (var7.hasNext()) { - ClassDetails details = (ClassDetails) var7.next(); - Map result = new LinkedHashMap(); - result.put("classId", details.getClsId()); - result.put("progId", details.getProgId()); - result.put("description", details.getDescription()); - listResult.add(result); - } - - return listResult; - } catch (UnknownHostException | JIException | IllegalArgumentException e) { - log.error("连接异常{}", e, e.getMessage()); - throw new BadRequestException(LangProcess.msg("login_pwdWrong")); - } - } - -} +//package org.nl.acs.utils; +// +//import com.alibaba.fastjson.JSON; +//import com.alibaba.fastjson.JSONArray; +//import com.alibaba.fastjson.JSONObject; +//import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; +//import lombok.extern.slf4j.Slf4j; +//import org.jinterop.dcom.common.JIException; +//import org.jinterop.dcom.core.JIVariant; +//import org.nl.acs.device.device_driver.standard_inspect.ItemDto; +//import org.nl.acs.device.device_driver.standard_inspect.ItemProtocol; +//import org.nl.acs.opc.OpcUtl; +//import org.nl.acs.opc.domain.Opc; +//import org.nl.acs.opc.service.mapper.OpcMapper; +//import org.nl.common.exception.BadRequestException; +//import org.nl.config.SpringContextHolder; +//import org.nl.config.language.LangProcess; +//import org.openscada.opc.dcom.list.ClassDetails; +//import org.openscada.opc.lib.common.AlreadyConnectedException; +//import org.openscada.opc.lib.common.ConnectionInformation; +//import org.openscada.opc.lib.da.*; +//import org.openscada.opc.lib.list.Categories; +//import org.openscada.opc.lib.list.Category; +//import org.openscada.opc.lib.list.ServerList; +// +//import java.net.UnknownHostException; +//import java.util.*; +//import java.util.concurrent.Executors; +// +///** +// * @author 20220102CG\noblelift +// */ +//@Slf4j +//public class ReadUtil { +// +// static OpcMapper opcMapper = SpringContextHolder.getBean("opcMapper"); +// +// public static Server getServer(String opc_id) { +// //OPC表【acs_opc】 +//// JSONObject opcObj = WQLObject.getWQLObject("acs_opc").query("opc_id = '" + opc_id + "'").uniqueResult(0); +// +// Opc opc = new LambdaQueryChainWrapper<>(opcMapper) +// .eq(Opc::getOpc_id, opc_id) +// .one(); +// //RD1.RD1.1028 +// // 连接信息 +// ConnectionInformation ci = new ConnectionInformation(); +// ci.setHost(opc.getOpc_host()); +// ci.setDomain(opc.getDomain()); +// ci.setUser(opc.getUser()); +// ci.setPassword(opc.getPassword()); +// ci.setClsid(opc.getCls_id()); +// final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor()); +// try { +// server.connect(); +// } catch (UnknownHostException e) { +// e.printStackTrace(); +// } catch (JIException e) { +// e.printStackTrace(); +// } catch (AlreadyConnectedException e) { +// e.printStackTrace(); +// } +// return server; +// } +// +// public static void write(Map strings, Server server) { +// try { +// //Group group = this.opcServerService.getServer(opcServiceCode); +// Group group = server.addGroup(); +// Iterator it = strings.keySet().iterator(); +// while (it.hasNext()) { +// String key = (String) it.next(); +// Item byteItem = group.addItem(key); +// Object o = strings.get(key); +// if (o == null || "".equals(o)) { +// break; +// } +// WriteRequest write1 = new WriteRequest(byteItem, new JIVariant(o.toString())); +// List list = new ArrayList(); +// list.add(write1); +// OpcUtl.writeValue(group, (WriteRequest[]) list.toArray(new WriteRequest[0])); +// } +// server.disconnect(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// +// } +// +// public static JSONArray getReadableItemDtos() { +// List list = ItemProtocol.getReadableItemDtos(); +// JSONArray array = JSONArray.parseArray(JSON.toJSONString(list)); +// +// return array; +// +// } +// +// public static JSONArray getWriteableItemDtos() { +// List list = ItemProtocol.getWriteableItemDtos(); +// JSONArray array = JSONArray.parseArray(JSON.toJSONString(list)); +// return array; +// +// } +// +// public static Map read(List itemString, Server server) { +// HashMap map = new HashMap(); +// try { +// Group group = server.addGroup(); +// Map items = new LinkedHashMap(); +// Iterator is = itemString.iterator(); +// +// while (is.hasNext()) { +// String string = (String) is.next(); +// try { +// items.put(string, group.addItem(string)); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// Map itemStatus = group.read(true, (Item[]) items.values().toArray(new Item[0])); +// Set keySet = itemStatus.keySet(); +// Iterator it = keySet.iterator(); +// +// while (it.hasNext()) { +// Item key = (Item) it.next(); +// Object value = OpcUtl.getValue(key, (ItemState) itemStatus.get(key)); +// map.put(key.getId(), value); +// } +// server.disconnect(); +// +// } catch (Exception e) { +// e.printStackTrace(); +// } +// +// return map; +// } +// +// public static List> showAllOpcServer(String host, String user, String password, String domain) throws BadRequestException { +// try { +// List> listResult = new ArrayList(); +// ServerList serverList = new ServerList(host, user, password, domain); +// Collection classDetails = serverList.listServersWithDetails(new Category[]{Categories.OPCDAServer10, Categories.OPCDAServer20, Categories.OPCDAServer30}, new Category[0]); +// Iterator var7 = classDetails.iterator(); +// +// while (var7.hasNext()) { +// ClassDetails details = (ClassDetails) var7.next(); +// Map result = new LinkedHashMap(); +// result.put("classId", details.getClsId()); +// result.put("progId", details.getProgId()); +// result.put("description", details.getDescription()); +// listResult.add(result); +// } +// +// return listResult; +// } catch (UnknownHostException | JIException | IllegalArgumentException e) { +// log.error("连接异常{}", e, e.getMessage()); +// throw new BadRequestException(LangProcess.msg("login_pwdWrong")); +// } +// } +// +//} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/RedisConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/RedisConfig.java index e0785bb..bad900a 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/RedisConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/RedisConfig.java @@ -37,6 +37,7 @@ import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; @@ -91,6 +92,25 @@ public class RedisConfig extends CachingConfigurerSupport { return template; } + @SuppressWarnings("all") + @Bean(name = "redisTemplateHash") + @ConditionalOnMissingBean(name = "redisTemplateHash") + public RedisTemplate redisTemplateHash(RedisConnectionFactory redisConnectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(redisConnectionFactory); + + // 设置key和hashKey的序列化方式 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + + // 设置value和hashValue的序列化方式 + template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); + template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); + + template.afterPropertiesSet(); + return template; + } + /** * 自定义缓存key生成策略,默认将使用该策略 */ diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/ExcelTemplateCreator.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/ExcelTemplateCreator.java new file mode 100644 index 0000000..59a8b5d --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/ExcelTemplateCreator.java @@ -0,0 +1,172 @@ +package org.nl.config.driver; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.nl.acs.device.enums.DeviceType; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Arrays; + +/** + * @Description TODO + * @Author Gengby + * @Date 2024/4/7 + */ +public class ExcelTemplateCreator { + + public static void createExcelTemplate(HttpServletResponse response) { + try (Workbook workbook = new XSSFWorkbook()) { + CellStyle headerCellStyle = workbook.createCellStyle(); + Font headerFont = workbook.createFont(); + headerFont.setBold(true); + headerCellStyle.setFont(headerFont); + headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + headerCellStyle.setAlignment(HorizontalAlignment.CENTER); + headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + headerCellStyle.setBorderBottom(BorderStyle.THIN); + headerCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + headerCellStyle.setBorderLeft(BorderStyle.THIN); + headerCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + headerCellStyle.setBorderRight(BorderStyle.THIN); + headerCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); + headerCellStyle.setBorderTop(BorderStyle.THIN); + headerCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); + + CellStyle unlockedCellStyle = workbook.createCellStyle(); + unlockedCellStyle.setLocked(false); + unlockedCellStyle.setAlignment(HorizontalAlignment.CENTER); + unlockedCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + unlockedCellStyle.setBorderBottom(BorderStyle.THIN); + unlockedCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); + unlockedCellStyle.setBorderLeft(BorderStyle.THIN); + unlockedCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); + unlockedCellStyle.setBorderRight(BorderStyle.THIN); + unlockedCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); + unlockedCellStyle.setBorderTop(BorderStyle.THIN); + unlockedCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); + + String[] deviceTypes = Arrays.stream(DeviceType.values()) + .map(Enum::name) + .toArray(String[]::new); + + Sheet sheet1 = workbook.createSheet("driver_class"); + sheet1.setDefaultColumnWidth(30); + sheet1.setColumnWidth(1, 70 * 256); + + DataValidationHelper validationHelper = sheet1.getDataValidationHelper(); + DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(deviceTypes); + CellRangeAddressList addressList = new CellRangeAddressList(6, 6, 1, 1); + DataValidation dataValidation = validationHelper.createValidation(constraint, addressList); + dataValidation.setShowErrorBox(true); + sheet1.addValidationData(dataValidation); + + String[] headers1 = {"packagePath", "definitionClassName", "definitionDriverCode", + "definitionDriverName", "definitionDriverDescription", "deviceDriverClassName", "deviceType"}; + for (int i = 0; i < headers1.length; i++) { + Row row = sheet1.createRow(i); + row.setHeightInPoints(30); + Cell cell = row.createCell(0); + cell.setCellValue(headers1[i]); + cell.setCellStyle(headerCellStyle); + Cell dataCell = row.createCell(1); + dataCell.setCellStyle(unlockedCellStyle); + if ("packagePath".equals(headers1[i])) { + dataCell.setCellValue("org.nl.acs.device_driver.xx"); + } else if ("definitionClassName".equals(headers1[i])) { + dataCell.setCellValue("XxDefinition"); + } else if ("definitionDriverCode".equals(headers1[i])) { + dataCell.setCellValue("xx_device_xx"); + } else if ("definitionDriverName".equals(headers1[i])) { + dataCell.setCellValue("xxxxName"); + } else if ("definitionDriverDescription".equals(headers1[i])) { + dataCell.setCellValue("xxxxName"); + } else if ("deviceDriverClassName".equals(headers1[i])) { + dataCell.setCellValue("XxxxDeviceDriver"); + } else if ("deviceType".equals(headers1[i])) { + dataCell.setCellValue("conveyor"); + } + } + sheet1.protectSheet(""); + + Sheet sheet2 = workbook.createSheet("ItemProtocol"); + for (int i = 0; i < 4; i++) { + sheet2.setColumnWidth(i, 30 * 256); + } + CellStyle sheet2UnlockedCellStyle = workbook.createCellStyle(); + sheet2UnlockedCellStyle.setLocked(false); + sheet2UnlockedCellStyle.setAlignment(HorizontalAlignment.CENTER); + sheet2UnlockedCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + + sheet2.setDefaultRowHeightInPoints(30); + + // 下拉列表的选项 + String[] fieldTypes = {"int", "Integer", "byte", "Byte", "short", "Short", + "long", "Long", "float", "Float", "double", "Double", + "boolean", "Boolean", "String", + "int[]", "Integer[]", "byte[]", "Byte[]", "short[]", "Short[]", + "long[]", "Long[]", "float[]", "Float[]", "double[]", "Double[]", + "boolean[]", "Boolean[]", "String[]"}; + + DataValidationHelper sheet2ValidationHelper = sheet2.getDataValidationHelper(); + DataValidationConstraint sheet2constraint = sheet2ValidationHelper.createExplicitListConstraint(fieldTypes); + CellRangeAddressList sheet2addressList = new CellRangeAddressList(1, 100, 3, 3); + DataValidation sheet2dataValidation = sheet2ValidationHelper.createValidation(sheet2constraint, sheet2addressList); + sheet2dataValidation.setShowErrorBox(true); + sheet2.addValidationData(sheet2dataValidation); + + String[] headers2 = {"key", "description", "address", "fieldType"}; + Row headerRowSheet2 = sheet2.createRow(0); + headerRowSheet2.setHeightInPoints(30); + + for (int i = 0; i < headers2.length; i++) { + Cell cell = headerRowSheet2.createCell(i); + cell.setCellValue(headers2[i]); + cell.setCellStyle(headerCellStyle); + } + + for (int j = 1; j <= 100; j++) { + Row dataRow = sheet2.createRow(j); + dataRow.setHeightInPoints(30); + for (int i = 0; i < headers2.length; i++) { + Cell cell = dataRow.createCell(i); + cell.setCellStyle(sheet2UnlockedCellStyle); + if (j == 1) { + switch (headers2[i]) { + case "key": + cell.setCellValue("heartbeat"); + break; + case "description": + cell.setCellValue("心跳"); + break; + case "address": + cell.setCellValue("DB600.B1"); + break; + case "fieldType": + cell.setCellValue("int"); + break; + default: + break; + } + } + } + } + + sheet2.protectSheet(""); + //response为HttpServletResponse对象 + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); + //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 + response.setHeader("Content-Disposition", "attachment;filename=file.xlsx"); + + // 将Excel文件内容写入响应的输出流 + try (OutputStream out = response.getOutputStream()) { + workbook.write(out); + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/GeneratorDriverTemplate.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/GeneratorDriverTemplate.java new file mode 100644 index 0000000..dcb6756 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/driver/GeneratorDriverTemplate.java @@ -0,0 +1,385 @@ +package org.nl.config.driver; + +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; + +/** + * @Description TODO + * @Author Gengby + * @Date 2024/4/2 + */ +public class GeneratorDriverTemplate { + + private static final List FIELDS = Arrays.asList("boolean", "Boolean", "int[]", "Integer[]", "byte[]", "Byte[]", "short[]", "Short[]", "long[]", "Long[]", "float[]", "Float[]", "double[]", "Double[]", "char[]", "Character[]", "boolean[]", "Boolean[]", "String[]"); + + public static void generateClass(MultipartFile file) { + if (file.isEmpty()) { + throw new IllegalArgumentException("上传的文件为空!"); + } + + try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) { + Sheet configSheet = workbook.getSheetAt(0); + Map config = parseConfig(configSheet); + Sheet enumSheet = workbook.getSheetAt(1); + + String itemProtocol = buildItemProtocol(enumSheet, config); + String deviceDriver = buildDeviceDriver(config, parseDriverField(enumSheet)); + String definition = buildStationDefinition(config); + + String basePath = "nlsso-server/src/main/java"; + String packagePath = config.get("packagePath").replace('.', '/'); + String outputPath = basePath + "/" + packagePath; + + writeJavaFile(outputPath, "ItemProtocol.java", itemProtocol); + writeJavaFile(outputPath, config.get("deviceDriverClassName") + ".java", deviceDriver); + writeJavaFile(outputPath, config.get("definitionClassName") + ".java", definition); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void writeJavaFile(String outputPath, String fileName, String content) throws IOException { + Files.createDirectories(Paths.get(outputPath)); + Files.write(Paths.get(outputPath, fileName), content.getBytes()); + } + + public static String buildDeviceDriver(Map config, Map> driverFields) { + StringBuilder classBuilder = new StringBuilder(); + classBuilder.append("package " + config.get("packagePath") + ";\n\n") + .append("import com.alibaba.fastjson.JSONObject;\n") + .append("import lombok.Getter;\n") + .append("import lombok.RequiredArgsConstructor;\n") + .append("import lombok.Setter;\n") + .append("import lombok.extern.slf4j.Slf4j;\n") + .append("import org.nl.acs.device.domain.Device;\n") + .append("import org.nl.acs.device_driver.*;\n") + .append("import org.nl.acs.device_driver.driver.*;\n") + .append("import org.nl.acs.monitor.DeviceStageMonitor;\n") + .append("import org.nl.config.SpringContextHolder;\n") + .append("import org.nl.acs.device_driver.BaseTagsDataReader;\n") + .append("import org.nl.config.lucene.service.LuceneExecuteLogService;\n") + .append("import org.nl.config.lucene.service.dto.LuceneLogDto;\n") + .append("import java.util.Date;\n\n") + .append("@Slf4j\n") + .append("@Getter\n") + .append("@Setter\n") + .append("@RequiredArgsConstructor\n") + .append("public class " + config.get("deviceDriverClassName") + " extends AbstractOpcDeviceDriver implements\n") + .append(" DeviceDriver,\n") + .append(" ExecutableDeviceDriver,\n") + .append(" RouteableDeviceDriver,\n") + .append(" DeviceStageMonitor,\n") + .append(" StandardRequestMethod,\n") + .append(" BaseTagsDataReader {\n\n") + .append(" private final LuceneExecuteLogService logService = SpringContextHolder.getBean(LuceneExecuteLogService.class);\n\n"); + driverFields.forEach((filedName, value) -> + classBuilder.append(" /**\n") + .append(" * ").append(value.get("description")).append("\n") + .append(" */\n") + .append(" private ").append(value.get("fieldType")).append(" ").append(convertToCamelCase(filedName)).append(FIELDS.contains(value.get("fieldType")) ? "" : " = ").append(value.get("fieldType").equals("String") ? "" : FIELDS.contains(value.get("fieldType")) ? "" : 0).append(";\n") + .append(" private ").append(value.get("fieldType")).append(" ").append("last").append(capitalizeFirstLetter(convertToCamelCase(filedName))).append(FIELDS.contains(value.get("fieldType")) ? "" : " = ").append(value.get("fieldType").equals("String") ? "" : FIELDS.contains(value.get("fieldType")) ? "" : 0).append(";\n") + ); + classBuilder.append(" /**\n") + .append(" * 当前设备编号\n") + .append(" */\n") + .append(" private String currentDeviceCode;\n\n") + .append(" /**\n") + .append(" * 消息\n") + .append(" */\n") + .append(" private String message;\n\n") + .append(" /**\n") + .append(" * 请求标记\n") + .append(" */\n") + .append(" boolean requireSuccess = false;\n\n") + .append(" /**\n") + .append(" * 请求时间\n") + .append(" */\n") + .append(" private Date requireTime = new Date();\n\n") + .append(" /**\n") + .append(" * 请求间隔时间\n") + .append(" */\n") + .append(" private long requireTimeOut = 3000L;\n\n") + .append(driverFields.containsKey("error") ? " /**\n" : "") + .append(driverFields.containsKey("error") ? " * 设备异常标记\n" : "") + .append(driverFields.containsKey("error") ? " */\n" : "") + .append(driverFields.containsKey("error") ? " private boolean isError = false;\n\n" : "") + .append(" @Override\n") + .append(" public Device getDevice() {\n") + .append(" return this.device;\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public & KeyProvider, T> T getOpcValue(E item, Class fieldClassType) {\n") + .append(" return (T) this.getValue(item.getKey());\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public void setLog(String key, Object newValue, Object oldValue) {\n") + .append(" logService.deviceExecuteLog(new LuceneLogDto(this.currentDeviceCode, \"自动线程读取信号:\" + key + \",由\" + oldValue + \"->\" + newValue));\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public void execute() {\n") + .append(" this.currentDeviceCode = this.getDeviceCode();\n") + .append(" this.loadAssignData(currentDeviceCode, ItemProtocol.class);\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public void executeLogic() {\n") + .append(" if (Boolean.FALSE.equals(this.getOnline())) {\n") + .append(" this.message = \"设备离线\";\n") + .append(driverFields.containsKey("mode") ? " } else if (this.mode == 0) {\n" : "") + .append(driverFields.containsKey("mode") ? " this.message = \"设备未联机\";\n" : "") + .append(driverFields.containsKey("error") ? " } else if (this.error != 0) {\n" : "") + .append(driverFields.containsKey("error") ? " this.message = \"设备报警\";\n" : "") + .append(driverFields.containsKey("error") ? " this.isError = true;\n" : "") + .append(" } else {\n") + .append(driverFields.containsKey("error") ? " this.isError = false;\n" : "") + .append(" this.message = \"\";\n") + .append(" //编写业务逻辑方法\n") + .append(" }\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public JSONObject getDeviceStatusName() throws Exception {\n") + .append(" JSONObject jo = new JSONObject();\n") + .append(" jo.put(\"device_code\", this.currentDeviceCode);\n") + .append(" jo.put(\"device_name\", this.getDevice().getDevice_name());\n") + .append(" jo.put(\"driver_type\", \"" + config.get("definitionDriverCode") + "\");\n") + .append(" jo.put(\"is_click\", false);\n") + .append(" jo.put(\"message\", this.message);\n") + .append(" jo.put(\"isOnline\", this.online);\n") + .append(driverFields.containsKey("error") ? " jo.put(\"isError\", this.isError);\n" : "") + .append(" return jo;\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public void setDeviceStatus(JSONObject data) {\n") + .append(" \n") + .append(" }\n\n") + .append("}\n"); + return classBuilder.toString(); + } + + public static String buildStationDefinition(Map config) { + StringBuilder classBuilder = new StringBuilder(); + + classBuilder.append("package ").append(config.get("packagePath")).append(";\n\n") + .append("import org.nl.acs.device.device_driver.standard_inspect.ItemDto;\n") + .append("import org.nl.acs.device.domain.Device;\n") + .append("import org.nl.acs.device.enums.DeviceType;\n") + .append("import org.nl.acs.device_driver.DeviceDriver;\n") + .append("import org.nl.acs.device_driver.defination.OpcDeviceDriverDefination;\n") + .append("import org.springframework.stereotype.Service;\n\n") + .append("import java.util.LinkedList;\n") + .append("import java.util.List;\n\n") + .append("@Service\n") + .append("public class ").append(config.get("definitionClassName")).append(" implements OpcDeviceDriverDefination {\n") + .append(" @Override\n") + .append(" public String getDriverCode() {\n") + .append(" return \"").append(config.get("definitionDriverCode")).append("\";\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public String getDriverName() {\n") + .append(" return \"").append(config.get("definitionDriverName")).append("\";\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public String getDriverDescription() {\n") + .append(" return \"").append(config.get("definitionDriverDescription")).append("\";\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public DeviceDriver getDriverInstance(Device device) {\n") + .append(" return (new ").append(config.get("deviceDriverClassName")).append("()).setDevice(device).setDriverDefination(this);\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public Class getDeviceDriverType() {\n") + .append(" return ").append(config.get("deviceDriverClassName")).append(".class;\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public List getFitDeviceTypes() {\n") + .append(" List types = new LinkedList();\n") + .append(" types.add(DeviceType.").append(config.get("deviceType")).append(");\n") + .append(" return types;\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public List getReadableItemDtos() {\n") + .append(" return ItemProtocol.getReadableItemDtos();\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public List getWriteableItemDtos() {\n") + .append(" return ItemProtocol.getWriteableItemDtos();\n") + .append(" }\n") + .append("}\n"); + + return classBuilder.toString(); + + } + + public static String buildItemProtocol(Sheet sheet, Map config) { + StringBuilder enumClassContent = new StringBuilder(); + enumClassContent.append("package " + config.get("packagePath") + ";\n\n") + .append("import org.nl.acs.device.device_driver.standard_inspect.ItemDto;\n\n") + .append("import org.nl.acs.device_driver.BaseTagsDataReader;\n\n") + .append("import java.util.List;\n") + .append("import java.util.ArrayList;\n\n") + .append("public enum ItemProtocol implements BaseTagsDataReader.KeyProvider {\n"); + Iterator iterator = sheet.rowIterator(); + while (iterator.hasNext()) { + Row currentRow = iterator.next(); + if (currentRow.getRowNum() == 0) { + continue; + } + // 检查第一个单元格是否为空 + Cell firstCell = currentRow.getCell(0); + if (firstCell == null || firstCell.getCellType() == CellType.BLANK) { + break; + } + + String key = currentRow.getCell(0).getStringCellValue(); + String description = currentRow.getCell(1).getStringCellValue(); + String address = currentRow.getCell(2).getStringCellValue(); + + enumClassContent.append(" ") + .append((convertToUpperCaseSnakeCase(key))) + .append("(\"") + .append(convertToCamelCase(key)) + .append("\", \"") + .append(description) + .append("\", \"") + .append(address) + .append("\"), \n"); + } + + if (enumClassContent.lastIndexOf(", \n") > 0) { + enumClassContent.delete(enumClassContent.lastIndexOf(", \n"), enumClassContent.length()); + } + + enumClassContent.append(";\n\n") + .append(" private final String key;\n") + .append(" private final String description;\n") + .append(" private final String address;\n\n") + .append(" ItemProtocol(String key, String description, String address) {\n") + .append(" this.key = key;\n") + .append(" this.description = description;\n") + .append(" this.address = address;\n") + .append(" }\n\n") + .append(" @Override\n") + .append(" public String getKey() {\n") + .append(" return this.key;\n") + .append(" }\n\n") + .append(" public String getDescription() {\n") + .append(" return description;\n") + .append(" }\n\n") + .append(" public String getAddress() {\n") + .append(" return address;\n") + .append(" }\n\n") + .append(" public static List getReadableItemDtos() {\n") + .append(" List list = new ArrayList<>();\n") + .append(" for (ItemProtocol prop : values()) {\n") + .append(" if (!prop.getKey().contains(\"to\")) {\n") + .append(" list.add(new ItemDto(prop.getKey(), prop.getDescription(), prop.getAddress()));\n") + .append(" }\n") + .append(" }\n") + .append(" return list;\n") + .append(" }\n\n") + .append(" public static List getWriteableItemDtos() {\n") + .append(" List list = new ArrayList<>();\n") + .append(" for (ItemProtocol prop : values()) {\n") + .append(" if (prop.getKey().contains(\"to\")) {\n") + .append(" list.add(new ItemDto(prop.getKey(), prop.getDescription(), prop.getAddress()));\n") + .append(" }\n") + .append(" }\n") + .append(" return list;\n") + .append(" }\n\n") + .append("}\n"); + + return enumClassContent.toString(); + } + + private static Map parseConfig(Sheet sheet) { + Map config = new HashMap<>(); + for (Row row : sheet) { + Cell keyCell = row.getCell(0); + Cell valueCell = row.getCell(1); + if (keyCell != null && valueCell != null) { + config.put(keyCell.getStringCellValue().trim(), valueCell.getStringCellValue().trim()); + } else { + break; + } + } + return config; + } + + private static Map> parseDriverField(Sheet sheet) { + Map> map = new LinkedHashMap<>(); + for (Row row : sheet) { + if (row.getRowNum() == 0) { + continue; + } + Cell firstCell = row.getCell(0); + if (firstCell == null || firstCell.getCellType() == CellType.BLANK) { + break; + } + Cell keyCell = row.getCell(0); + Cell descriptionCell = row.getCell(1); + Cell fieldTypeCell = row.getCell(3); + if (keyCell != null && descriptionCell != null && fieldTypeCell != null) { + String key = keyCell.getStringCellValue().trim(); + String description = descriptionCell.getStringCellValue().trim(); + String fieldType = fieldTypeCell.getStringCellValue().trim(); + Map son = new HashMap<>(); + son.put("description", description); + son.put("fieldType", fieldType); + map.put(key, son); + } + } + return map; + } + + + private static String convertToUpperCaseSnakeCase(String fieldName) { + if (fieldName.contains("_")) { + return fieldName.toUpperCase(); + } else { + return fieldName + .replaceAll("(\\B[A-Z])", "_$1") + .toUpperCase(); + } + } + + private static String convertToCamelCase(String fieldName) { + if (fieldName.contains("_")) { + StringBuilder camelCaseString = new StringBuilder(); + String[] parts = fieldName.split("_"); + camelCaseString.append(parts[0]); + for (int i = 1; i < parts.length; i++) { + camelCaseString.append(parts[i].substring(0, 1).toUpperCase()) + .append(parts[i].substring(1)); + } + + return camelCaseString.toString(); + } + return fieldName; + } + + private static String capitalizeFirstLetter(String filedName) { + if (filedName == null || filedName.isEmpty()) { + return filedName; + } + + if (filedName.contains("_")) { + StringBuilder stringBuilder = new StringBuilder(); + String[] parts = filedName.split("_"); + for (int i = 0; i < parts.length; i++) { + if (!parts[i].isEmpty()) { + stringBuilder.append(parts[i].substring(0, 1).toUpperCase()) + .append(parts[i].substring(1)); + } + } + filedName = stringBuilder.toString(); + } + return filedName.substring(0, 1).toUpperCase() + filedName.substring(1); + } + +} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/ItemUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/ItemUtil.java new file mode 100644 index 0000000..68266e6 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/ItemUtil.java @@ -0,0 +1,43 @@ +package org.nl.config.mqtt2; + +import org.nl.acs.opc.DeviceAppService; +import org.nl.config.mqtt2.msg.Item; + +import java.util.List; + +/** + * @Description TODO + * @Author Gengby + * @Date 2024/3/18 + */ +public class ItemUtil { + + /** + * 心跳item名称 + */ + private static final String HEARTBEAT = "heartbeat"; + + /** + * 获取指定符合索引 + * + * @param text itemId + * @param character 指定符合 + * @param n 第几个富豪 + * @return 索引 + */ + public static int nthIndexOf(String text, String character, int n) { + int position = -1; + do { + position = text.indexOf(character, position + 1); + } while (n-- > 1 && position != -1); + return position; + } + + public static boolean hasHeartbeat(String itemId) { + return itemId.contains(HEARTBEAT); + } + + public static void setIsOnline(DeviceAppService deviceAppService, String deviceCode, List items) { + } + +} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/MqttService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/MqttService.java new file mode 100644 index 0000000..fb05a8a --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/MqttService.java @@ -0,0 +1,347 @@ +package org.nl.config.mqtt2; + +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.hivemq.client.mqtt.MqttClient; +import com.hivemq.client.mqtt.MqttGlobalPublishFilter; +import com.hivemq.client.mqtt.datatypes.MqttQos; +import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient; +import io.micrometer.core.instrument.util.NamedThreadFactory; +import lombok.extern.slf4j.Slf4j; +import org.nl.acs.device.domain.Device; +import org.nl.acs.device_driver.driver.AbstractDeviceDriver; +import org.nl.acs.opc.DeviceAppService; +import org.nl.acs.opc.OpcConfig; +import org.nl.acs.opc.service.OpcService; +import org.nl.acs.opc.service.dto.OpcDto; +import org.nl.acs.opc.service.dto.OpcQueryParam; +import org.nl.acs.udw.mqttUdw.ItemsDataAccessor; +import org.nl.acs.udw.mqttUdw.factory.ItemDataAccessorFactory; +import org.nl.config.lucene.service.LuceneExecuteLogService; +import org.nl.config.lucene.service.dto.LuceneLogDto; +import org.nl.config.mqtt2.config.MqttConfig; +import org.nl.config.mqtt2.msg.Item; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.*; +import java.util.stream.Collectors; + +/** + * @author onepiece + */ +@Component +@ConditionalOnProperty(name = "spring.mqtt.active", havingValue = "true") +@ConditionalOnBean({LuceneExecuteLogService.class, DeviceAppService.class, RedisTemplate.class}) +@Slf4j +public class MqttService { + + @Autowired(required = false) + @Qualifier("redisTemplateHash") + private RedisTemplate redisTemplateHash; + @Autowired + private MqttConfig mqttConfig; + @Autowired + private LuceneExecuteLogService logService; + @Autowired + private OpcService opcService; + @Autowired + private DeviceAppService deviceAppService; + + + private Mqtt3AsyncClient mqttClient; + + /** + * 根据topic存储订阅消息 + */ + private final Map> topicMap = new ConcurrentHashMap<>(); + + /** + * 存储设备点位信息 + */ + private static final ItemsDataAccessor ACCESSOR_VALUE = ItemDataAccessorFactory.getItemsDataAccessor(OpcConfig.udw_opc_value_key); + + /** + * 发布TOPIC + */ + private static final String PUBLISH_TOPIC = "publishTopic"; + + /** + * 重连延迟时间,单位:毫秒 + */ + private static final long RECONNECT_DELAY = 5000L; + + /** + * 最大重连延迟时间,单位:毫秒 + */ + private static final long MAX_RECONNECT_DELAY = 60000L; + + /** + * 存储Redis数据Key + */ + private static final String KEY = "opc:items"; + + /** + * 心跳item名称 + */ + private static final String HEARTBEAT = "heartbeat"; + + /** + * 线程池核心线程数量 + */ + private static final int CORE_POOL_SIZE = 1; + + /** + * 线程池最大线程数量 + */ + private static final int MAX_POOL_SIZE = 10; + + /** + * 非核心线程存活时间 + */ + private static final int KEEP_ALIVE_TIME = 10; + + /** + * 用来存储等待执行任务的阻塞队列的大小 + */ + private static final int WORK_QUEUE_SIZE = 100; + + /** + * 队列 + */ + private static final Queue MSG_QUEUE = new LinkedBlockingQueue<>(); + + /** + * 线程工厂 + */ + private final ThreadFactory threadFactory = new NamedThreadFactory("MqttThreadFactory"); + + /** + * 线程池 + */ + private final ThreadPoolExecutor threadPool = new ThreadPoolExecutor( + CORE_POOL_SIZE, + MAX_POOL_SIZE, + KEEP_ALIVE_TIME, + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(WORK_QUEUE_SIZE), + threadFactory, + (r, executor) -> MSG_QUEUE.add(r) + ); + + + @PostConstruct + public void init() { + initTopicMap(); + loadItems(); + initMqttClient(); + run(); + } + + + /** + * 初始化topicMap + *

+ */ + private void initTopicMap() { + List opcDtos = opcService.queryAll(new OpcQueryParam()); + threadPool.setCorePoolSize(opcDtos.size() + 1); + threadPool.setMaximumPoolSize(opcDtos.size() + 10); + opcDtos.forEach(opcDto -> topicMap.put(opcDto.getTopic() == null ? "" : opcDto.getTopic(), new LinkedBlockingQueue<>())); + } + + /** + * 初始化MQTT客户端 + */ + private void initMqttClient() { + mqttClient = MqttClient.builder() + .useMqttVersion3() + .identifier(mqttConfig.getClientId()) + .serverHost(mqttConfig.getUrl()) + .addDisconnectedListener((context -> { + Throwable cause = context.getCause(); + log.error("mqtt client disconnected , {}", cause.getMessage()); + //MqttClientReconnector reconnect = context.getReconnector(); + //reconnect.reconnect(true); + //reconnect.delay(RECONNECT_DELAY, TimeUnit.MILLISECONDS); + })) + .automaticReconnect() + .initialDelay(RECONNECT_DELAY, TimeUnit.MILLISECONDS) + .maxDelay(MAX_RECONNECT_DELAY, TimeUnit.MILLISECONDS) + .applyAutomaticReconnect() + .buildAsync(); + + mqttClient.connectWith() + .simpleAuth() + .username(mqttConfig.getUsername()) + .password(mqttConfig.getPassword().getBytes()) + .applySimpleAuth() + .cleanSession(mqttConfig.getCleanSession()) + .send() + .thenAccept(connAck -> { + log.info("mqtt client connection success."); + subscribeToTopics(Arrays.asList(mqttConfig.getTopics())); + }) + .exceptionally(throwable -> { + log.error("mqtt client connection failed: " + throwable.getMessage(), throwable); + return null; + }); + + mqttClient.publishes(MqttGlobalPublishFilter.ALL, publish -> { + String topic = publish.getTopic().toString(); + String payload = new String(publish.getPayloadAsBytes(), StandardCharsets.UTF_8); + messageArrived(topic, payload); + }); + } + + private void subscribeToTopics(List topics) { + topics.forEach(topic -> mqttClient.subscribeWith() + .topicFilter(topic) + .qos(MqttQos.EXACTLY_ONCE) + .send() + .whenComplete((subAck, throwable) -> { + if (throwable != null) { + log.error("mqtt subscript failed Topic {}, error reason {} ", topic, throwable.getMessage()); + } else { + log.info("mqtt subscript success Topic {}", topic); + } + })); + } + + private void messageArrived(String topic, String payload) { + //接收到消息:先放队列,根据不同topic处理不同处理dd逻辑 + if (topicMap.containsKey(topic)) { + topicMap.get(topic).add(payload); + System.out.println("接收到消息---" + topic + "内容:" + payload); + } else { + log.info("topic---{} does not exist", topic); + } + } + + public CompletableFuture publishMessage(String payload) { + return mqttClient.publishWith() + .topic(PUBLISH_TOPIC) + .payload(payload.getBytes(StandardCharsets.UTF_8)) + .qos(MqttQos.EXACTLY_ONCE) + .send() + .thenAccept(pubAck -> { + log.info("mqtt client publish success Topic {} , Payload: {}", PUBLISH_TOPIC, payload); + }) + .exceptionally(throwable -> { + log.error("mqtt client publish Topic {} ,Payload {} , failed reason {}", PUBLISH_TOPIC, payload, throwable.getMessage()); + return null; + }); + } + + /** + * 为每个Topic初始化线程 + */ + private void run() { + topicMap.forEach((topic, values) -> threadPool.execute(() -> { + log.info("mqtt create Topic thread:{}", topic); + while (true) { + try { + execute(topic, values.take()); + } catch (Exception e) { + log.error("mqtt execute handler failed Topic {} , reason {}", topic, e.getMessage()); + } + } + })); + } + + /** + * 针对topic的消息处理逻辑 + * + * @param topic + * @param body + */ + private void execute(String topic, String body) { + JSONObject msg = JSONObject.parseObject(body); + JSONArray msgValues = msg.getJSONArray("values"); + List itemList = msgValues.toJavaList(Item.class); + Map> groupItems = itemList.stream().collect(Collectors.groupingBy(item -> item.getId().substring(0, ItemUtil.nthIndexOf(item.getId(), ".", 3)))); + groupItems.forEach((itemId, items) -> updateDeviceStatus(itemId.substring(ItemUtil.nthIndexOf(itemId, ".", 2) + 1), items)); + System.out.println("线程名称:'" + Thread.currentThread() + "',接收到消息" + topic + "-" + body + "-"); + } + + /** + * 更新设备数据信息 + * + * @param deviceCode + * @param items + */ + public void updateDeviceStatus(String deviceCode, List items) { + setOnline(deviceCode, items); + setValue(deviceCode, items); + } + + /** + * 更新设备在线状态 + * + * @param deviceCode + * @param items + */ + public void setOnline(String deviceCode, List items) { + Optional heartbeatPresent = items.stream() + .filter(item -> item.getId().contains(HEARTBEAT)) + .map(Item::isQ) + .findFirst(); + heartbeatPresent.ifPresent(q -> { + Device device = deviceAppService.findDeviceByCode(deviceCode); + if (device != null && device.getDeviceDriver() instanceof AbstractDeviceDriver) { + AbstractDeviceDriver deviceDriver = (AbstractDeviceDriver) device.getDeviceDriver(); + if (!Objects.equals(deviceDriver.getOnline(), q)) { + deviceDriver.setOnline(q); + log.info("device : {}, online status: {} ", deviceCode, q); + } + } + }); + } + + /** + * 更新内存中的信号值 + * + * @param deviceCode + * @param values + */ + private void setValue(String deviceCode, List values) { + values.forEach(item -> { + if (!ObjectUtil.equals(item.getV(), ACCESSOR_VALUE.getValue(item.getId()))) { + logService.deviceExecuteLog(new LuceneLogDto(deviceCode, "MQTT上报,信号:" + item.getId() + ",由" + ACCESSOR_VALUE.getValue(item.getId()) + "->" + item.getV() + ",信号健康值:" + item.isQ())); + ACCESSOR_VALUE.setValue(item.getId(), item.getV()); + } + }); + } + + + @PreDestroy + public void cleanup() { + if (mqttClient != null) { + mqttClient.disconnect().thenAccept(disconnectAck -> log.info("Application Close, So MQTT client disconnected.")); + } + unloadItems(); + threadPool.shutdown(); + } + + private void loadItems() { + Map entries = redisTemplateHash.opsForHash().entries(KEY); + entries.forEach((key, value) -> ACCESSOR_VALUE.setValue((String) key, value)); + redisTemplateHash.delete(KEY); + } + + private void unloadItems() { + List allKey = ACCESSOR_VALUE.getAllKey(); + Map map = new HashMap<>(); + allKey.forEach(key -> map.put(key, ACCESSOR_VALUE.getValue(key))); + redisTemplateHash.opsForHash().putAll(KEY, map); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/config/MqttConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/config/MqttConfig.java new file mode 100644 index 0000000..28d295a --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/config/MqttConfig.java @@ -0,0 +1,40 @@ +package org.nl.config.mqtt2.config; + +import lombok.Data; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + + +/* + * @author ZZQ + * @Date 2024/1/31 14:07 + */ +@Configuration +@ConfigurationProperties(prefix = "spring.mqtt") +@ConditionalOnProperty(name = "spring.mqtt.active", havingValue = "true") +@Data +public class MqttConfig { + + private String username; + + private String password; + + private String url; + + private Boolean cleanSession; + + private String clientId; + + private String[] topics; + + private int[] qoss; + + private int timeout; + + private int keepalive; + + private MqttConnectOptions option; + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/msg/Item.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/msg/Item.java new file mode 100644 index 0000000..1b7ed2f --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mqtt2/msg/Item.java @@ -0,0 +1,16 @@ +package org.nl.config.mqtt2.msg; + +import lombok.Data; + +/** + * @Description TODO + * @Author Gengby + * @Date 2024/3/5 + */ +@Data +public class Item { + private String id; + private T v; + private boolean q; + private long t; +} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/resources/config/application-dev2.yml b/nladmin-system/nlsso-server/src/main/resources/config/application-dev2.yml new file mode 100644 index 0000000..ea89675 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/resources/config/application-dev2.yml @@ -0,0 +1,195 @@ +server: + port: 8011 +#配置数据源 +spring: + messages: + basename: language/login/login,language/error/error,language/buss/buss + datasource: + 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:zjhs_acs}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&allowPublicKeyRetrieval=true + username: ${DB_USER:root} + password: ${DB_PWD:password} + # 初始连接数 + initial-size: 5 + # 最小连接数 + min-idle: 15 + # 最大连接数 + max-active: 30 + # 超时时间(以秒数为单位) + remove-abandoned-timeout: 180 + # 获取连接超时时间 + max-wait: 3000 + # 连接有效性检测时间 + time-between-eviction-runs-millis: 60000 + # 连接在池中最小生存的时间 + min-evictable-idle-time-millis: 300000 + # 连接在池中最大生存的时间 + max-evictable-idle-time-millis: 900000 + # 指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除 + test-while-idle: true + # 指明是否在从池中取出连接前进行检验,如果检验失败, 则从池中去除连接并尝试取出另一个 + test-on-borrow: true + # 是否在归还到池中前进行检验 + test-on-return: false + # 检测连接是否有效 + validation-query: select 1 + # 配置监控统计 + webStatFilter: + enabled: true + stat-view-servlet: + enabled: true + url-pattern: /druid/* + reset-enable: false + filter: + stat: + enabled: true + # 记录慢SQL + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + flyway: + # 是否启用flyway + enabled: true + # 编码格式,默认UTF-8 + encoding: UTF-8 + # 迁移sql脚本文件存放路径,默认db/migration + locations: classpath:db/migration + # 迁移sql脚本文件名称的前缀,默认V + sql-migration-prefix: V + # 迁移sql脚本文件名称的分隔符,默认2个下划线__ + sql-migration-separator: __ + # 迁移sql脚本文件名称的后缀 + sql-migration-suffixes: .sql + # 迁移时是否进行校验,默认true + validate-on-migrate: true + # 当迁移发现数据库非空且存在没有元数据的表时,自动执行基准迁移,新建schema_version表 + baseline-on-migrate: true + redis: + #数据库索引 + database: ${REDIS_DB:2} + host: ${REDIS_HOST:127.0.0.1} + port: ${REDIS_PORT:6379} + # password: ${REDIS_PWD:} + mqtt: + active: true + username: root + password: 123456 + cleanSession: true + url: 10.211.55.3 + clientId: hs_mqtt21 + topics: + - A/# + qoss: + - 2 + timeout: 30 + keepalive: 15 + +# 登录相关配置 +login: + # 登录缓存 + cache-enable: true + # 是否限制单用户登录 + single-login: false + # 验证码 + login-code: + # 验证码类型配置 查看 LoginProperties 类 + code-type: arithmetic + # 登录图形验证码有效时间/分钟 + expiration: 2 + # 验证码高度 + width: 111 + # 验证码宽度 + heigth: 36 + # 内容长度 + length: 2 + # 字体名称,为空则使用默认字体 + font-name: + # 字体大小 + font-size: 25 + +#是否允许生成代码,生产环境设置为false +generator: + enabled: true + +# IP 本地解析 +ip: + local-parsing: true + +# 文件存储路径 +file: + mac: + path: ~/file/ + avatar: ~/avatar/ + linux: + path: /home/eladmin/file/ + avatar: /home/eladmin/avatar/ + windows: + path: C:\eladmin\file\ + avatar: C:\eladmin\avatar\ + # 文件大小 /M + maxSize: 100 + avatarMaxSize: 5 +logging: + file: + path: /Users/onepiece/myFile/acs_logs + config: classpath:logback-spring.xml +lucene: + index: + path: /lucene + +# Sa-Token配置 +sa-token: + # token 名称 (同时也是cookie名称) + token-name: Authorization + # token 有效期,单位s 默认30天, -1代表永不过期 + timeout: 2592000 + # token 临时有效期 (指定时间内无操作就视为token过期) 单位: 秒 + activity-timeout: -1 + # 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录) + is-concurrent: true + # 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token) + is-share: false + # token风格 + token-style: random-128 + # 是否输出操作日志 + is-log: false + jwt-secret-key: opsjajisdnnca0sdkksdfaaasdfwwq + # token 前缀 + token-prefix: Bearer + sso: + # Ticket有效期 (单位: 秒),默认五分钟 + ticket-timeout: 300 + # 所有允许的授权回调地址 + allow-url: "*" + # 是否打开单点注销功能 + is-slo: true + + # ------- SSO-模式三相关配置 (下面的配置在SSO模式三并且 is-slo=true 时打开) + # 是否打开模式三 + isHttp: true + # 接口调用秘钥(用于SSO模式三的单点注销功能) + secretkey: kQwIOrYvnXmSDkwEiFngrKidMcdrgKor + # ---- 除了以上配置项,你还需要为 Sa-Token 配置http请求处理器(文档有步骤说明) + is-read-cookie: true + is-print: false + # 未登录 StpUtil.getTokenSession() 设置值,获取值 @SaIgnore 得忽略接口 + token-session-check-login: false + alone-redis: + # Redis数据库索引(默认为0) + database: 2 + # Redis服务器地址 + host: 127.0.0.1 + # Redis服务器连接端口 + port: 6379 + # Redis服务器连接密码(默认为空) + password: + # 连接超时时间 + timeout: 10s + +agvToAcs: + addr: http://localhost diff --git a/nladmin-system/nlsso-server/src/main/resources/config/application-prod.yml b/nladmin-system/nlsso-server/src/main/resources/config/application-prod.yml index a3bb23c..0b9e617 100644 --- a/nladmin-system/nlsso-server/src/main/resources/config/application-prod.yml +++ b/nladmin-system/nlsso-server/src/main/resources/config/application-prod.yml @@ -69,6 +69,19 @@ spring: address: redis://127.0.0.1:6379 idleConnectionTimeout: 10000 timeout: 3000 + mqtt: + active: true + username: root + password: 123456 + url: 10.211.55.3 + clientId: hs_mqtt21 + cleanSession: false + topics: + - A/# + qoss: + - 2 + timeout: 30 + keepalive: 15 # 登录相关配置 login: # 登录缓存 diff --git a/nladmin-system/nlsso-server/src/main/resources/config/application.yml b/nladmin-system/nlsso-server/src/main/resources/config/application.yml index 4aaae10..ca54e48 100644 --- a/nladmin-system/nlsso-server/src/main/resources/config/application.yml +++ b/nladmin-system/nlsso-server/src/main/resources/config/application.yml @@ -2,11 +2,12 @@ server: tomcat: relaxed-query-chars: [ '|','{','}','[',']' ] #字符问题:https://blog.csdn.net/CanYue_Yi/article/details/109182577 relaxed-path-chars: [ '|','{','}','[',']' ] #字符问题: https://blog.csdn.net/weixin_41996632/article/details/90715118 + max-http-header-size: 65536 spring: freemarker: check-template-location: false profiles: - active: dev + active: dev2 jackson: time-zone: GMT+8 data: @@ -147,3 +148,6 @@ mybatis-plus: lucene: index: path: C:\acs\lucene\index + + + diff --git a/nladmin-system/nlsso-server/src/main/resources/logback-spring.xml b/nladmin-system/nlsso-server/src/main/resources/logback-spring.xml index b18097f..96f35c7 100644 --- a/nladmin-system/nlsso-server/src/main/resources/logback-spring.xml +++ b/nladmin-system/nlsso-server/src/main/resources/logback-spring.xml @@ -96,7 +96,7 @@ https://juejin.cn/post/6844903775631572999 - + @@ -124,6 +124,9 @@ https://juejin.cn/post/6844903775631572999 + + + diff --git a/nladmin-ui/src/api/acs/device/device.js b/nladmin-ui/src/api/acs/device/device.js index ef698b6..500deff 100644 --- a/nladmin-ui/src/api/acs/device/device.js +++ b/nladmin-ui/src/api/acs/device/device.js @@ -51,12 +51,14 @@ export function selectDeviceListOne() { method: 'get' }) } + export function selectDeviceListTwo() { return request({ url: 'api/device/selectListTwo', method: 'get' }) } + export function selectDeviceListThree() { return request({ url: 'api/device/selectListThree', @@ -157,6 +159,14 @@ export function excelImport(data) { }) } +export function uploadDriver(data) { + return request({ + url: 'api/device/uploadDriver', + method: 'post', + data + }) +} + export function selectListByType() { return request({ url: 'api/device//type/stacker', @@ -164,6 +174,36 @@ export function selectListByType() { }) } -export default { add, edit, del, selectDeviceList, selectDeviceListByRegion, callAgv, responseAgv, selectDeviceDevicerInfo, autoCreateTask, - changeDeviceStatus, cleanTask, queryStorageExtra, selectConDeviceList, saveBarcode, selectDeviceListOne, selectDeviceListTwo, selectDeviceListThree, - addMaterial, cleanMaterial, reload, excelImport, selectListByType } +export function getAllDriverCode() { + return request({ + url: 'api/device/getAllDriverCode', + method: 'get' + }) +} + +export default { + add, + edit, + del, + selectDeviceList, + selectDeviceListByRegion, + callAgv, + responseAgv, + selectDeviceDevicerInfo, + autoCreateTask, + changeDeviceStatus, + cleanTask, + queryStorageExtra, + selectConDeviceList, + saveBarcode, + selectDeviceListOne, + selectDeviceListTwo, + selectDeviceListThree, + addMaterial, + cleanMaterial, + reload, + excelImport, + selectListByType, + getAllDriverCode, + uploadDriver +} diff --git a/nladmin-ui/src/i18n/langs/en.js b/nladmin-ui/src/i18n/langs/en.js index 3d7a57a..e2b17ff 100644 --- a/nladmin-ui/src/i18n/langs/en.js +++ b/nladmin-ui/src/i18n/langs/en.js @@ -89,6 +89,7 @@ export default { 'stop': 'Stop', 'firing': 'Firing', 'import': 'Import', + 'export': 'Export', 'driver_configuration': 'Driver Configuration', 'create_time': 'Create Time', 'update_time': 'Update Time', diff --git a/nladmin-ui/src/i18n/langs/in.js b/nladmin-ui/src/i18n/langs/in.js index 462b10b..5c4caf1 100644 --- a/nladmin-ui/src/i18n/langs/in.js +++ b/nladmin-ui/src/i18n/langs/in.js @@ -89,6 +89,7 @@ export default { 'stop': 'Berhenti', 'firing': 'Start Up', 'import': 'Mengimpor', + 'export': 'eksport', 'driver_configuration': 'Konfigurasi Driver', 'create_time': 'Buat Waktu', 'update_time': 'Untuk Memperbarui Waktu', diff --git a/nladmin-ui/src/i18n/langs/opc/en.js b/nladmin-ui/src/i18n/langs/opc/en.js index 30b670f..4848d03 100644 --- a/nladmin-ui/src/i18n/langs/opc/en.js +++ b/nladmin-ui/src/i18n/langs/opc/en.js @@ -10,6 +10,7 @@ export default { 'opc_code': 'OPC Code', 'opc_name': 'OPC Name', 'opc_address': 'OPC Address', + 'topic': 'topic', 'program_id': 'Program ID', 'registry_id': 'Registry ID', 'remark': 'Remark', diff --git a/nladmin-ui/src/i18n/langs/opc/in.js b/nladmin-ui/src/i18n/langs/opc/in.js index 163ce36..0dc0239 100644 --- a/nladmin-ui/src/i18n/langs/opc/in.js +++ b/nladmin-ui/src/i18n/langs/opc/in.js @@ -10,6 +10,7 @@ export default { 'opc_code': 'Opc Kode', 'opc_name': 'Opc Nama', 'opc_address': 'Opc Alamat', + 'topic': 'topik', 'program_id': 'Program Id', 'registry_id': 'Pendaftaran ID', 'remark': 'Informasi', diff --git a/nladmin-ui/src/i18n/langs/opc/zh.js b/nladmin-ui/src/i18n/langs/opc/zh.js index 4356cfd..7e27e43 100644 --- a/nladmin-ui/src/i18n/langs/opc/zh.js +++ b/nladmin-ui/src/i18n/langs/opc/zh.js @@ -10,6 +10,7 @@ export default { 'opc_code': 'OPC编码', 'opc_name': 'OPC名称', 'opc_address': 'OPC地址', + 'topic': '订阅信息', 'program_id': '程序ID', 'registry_id': '注册表ID', 'remark': '备注', diff --git a/nladmin-ui/src/i18n/langs/zh-CN.js b/nladmin-ui/src/i18n/langs/zh-CN.js index 9c43943..1fd6c5f 100644 --- a/nladmin-ui/src/i18n/langs/zh-CN.js +++ b/nladmin-ui/src/i18n/langs/zh-CN.js @@ -89,6 +89,7 @@ export default { 'stop': '停止', 'firing': '启动', 'import': '导入', + 'export': '导出', 'driver_configuration': '驱动配置', 'create_time': '创建时间', 'update_time': '更新时间', diff --git a/nladmin-ui/src/views/acs/device/generation/UploadDialog.vue b/nladmin-ui/src/views/acs/device/generation/UploadDialog.vue new file mode 100644 index 0000000..be047aa --- /dev/null +++ b/nladmin-ui/src/views/acs/device/generation/UploadDialog.vue @@ -0,0 +1,116 @@ + + + + diff --git a/nladmin-ui/src/views/acs/device/generation/index.vue b/nladmin-ui/src/views/acs/device/generation/index.vue new file mode 100644 index 0000000..9c44719 --- /dev/null +++ b/nladmin-ui/src/views/acs/device/generation/index.vue @@ -0,0 +1,130 @@ + + + + + diff --git a/nladmin-ui/src/views/acs/device/opc/index.vue b/nladmin-ui/src/views/acs/device/opc/index.vue index c5d7477..0e5c334 100644 --- a/nladmin-ui/src/views/acs/device/opc/index.vue +++ b/nladmin-ui/src/views/acs/device/opc/index.vue @@ -47,12 +47,18 @@ + + + - {{ $t('opc.dialog.detail') }} + {{ + $t('opc.dialog.detail') + }} + @@ -74,7 +80,10 @@

@@ -116,21 +125,76 @@ > - - - - - - - - - - + + + + + + + + + + + @@ -156,6 +220,7 @@ const defaultForm = { opc_code: null, opc_name: null, opc_host: null, + topic: null, user: null, password: null, prog_id: null,