From 560303799978bd141dc1e9553b7607012591fb42 Mon Sep 17 00:00:00 2001
From: 严智鑫 <test>
Date: 星期二, 17 六月 2025 17:02:53 +0800
Subject: [PATCH] 1.json文件优化  增加配置项:【1.触发点;2.逻辑线程时间间隔】 2.优化处理代码 【1.去除多余日志输出点;2.两个设备json文件进行根据codeId进行关联;3.调整代码先后顺序】 3.json文件路径提出jar包外,可在设备表上配置上配置路径。因原方式修改地址json 后需重新打包,实际调试中传递jar包比较浪费时间

---
 ShangHaiMesParent/moduleService/plcConnectModule/src/main/java/com/mes/connect/Thread/MachineThread.java |  148 +++++++++++++++++--------------------------------
 1 files changed, 52 insertions(+), 96 deletions(-)

diff --git a/ShangHaiMesParent/moduleService/plcConnectModule/src/main/java/com/mes/connect/Thread/MachineThread.java b/ShangHaiMesParent/moduleService/plcConnectModule/src/main/java/com/mes/connect/Thread/MachineThread.java
index aa1cdc0..b1da536 100644
--- a/ShangHaiMesParent/moduleService/plcConnectModule/src/main/java/com/mes/connect/Thread/MachineThread.java
+++ b/ShangHaiMesParent/moduleService/plcConnectModule/src/main/java/com/mes/connect/Thread/MachineThread.java
@@ -24,10 +24,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.stream.Collectors;
 
@@ -55,6 +52,24 @@
         this.api = api;
         this.logicConfig = JsonConversion.jsonToObjectByJackson(ReadFile.readJson(machine.getLogicFile()).toString(), LogicConfig.class);
         this.plcParameters = JsonConversion.jsonToObjectByJackson(ReadFile.readJson(machine.getMachineFile()).toString(), PlcParameters.class);
+        this.logicConfig.getLogics();
+        this.plcParameters.Initialization();
+        for (LogicItem logicItem : logicConfig.getLogics()) {
+            if (logicItem.getLogicInterval()==0){
+                //榛樿1000姣
+                logicItem.setLogicInterval(1000);
+            }
+            for (Logic logic : logicItem.getLogic()) {
+                logic.setAddress(this.plcParameters.getMap().get(logic.getCodeId()).getAddress());
+                logic.setPlcDataType(this.plcParameters.getMap().get(logic.getCodeId()).getPlcDataType());
+            }
+            for (ReturnValue returnValue : logicItem.getReturnValue()) {
+                returnValue.setAddress(this.plcParameters.getMap().get(returnValue.getCodeId()).getAddress());
+                returnValue.setPlcDataType(this.plcParameters.getMap().get(returnValue.getCodeId()).getPlcDataType());
+            }
+        }
+
+
         switch (machine.getProtocolType().getName()) {
             case "ModbusTcp":
                 client = new ModbusTcpClient(machine.getIp(), machine.getPort(), 1);
@@ -72,54 +87,23 @@
                 log.error("鏃犳晥鐨勫崗璁被鍨�: {}", protocolType);
                 throw new IllegalArgumentException("鏃犳晥鐨勫崗璁被鍨�: " + protocolType);
         }
-        if (client != null) {
-            client.connect();
-            boolean connected = client.isConnected();
-            if (!connected) {
-                log.error("杩炴帴PLC澶辫触: {}", machine.getIp());
-            }
-        }
     }
 
     @Override
     public void run() {
-        log.info("MachineThread鍚姩锛岃澶嘔P: {}", machine.getIp());
-        if (client == null || !client.isConnected()) {
-            log.error("PLC瀹㈡埛绔湭杩炴帴锛岀嚎绋嬮��鍑�");
-            return;
-        }
-
-        plcParameters.Initialization();
-
-        try {
-            // 鍒濆鍖栬鍙朠LC鍙傛暟
-            readPlcParameter();
-        } catch (Exception e) {
-            log.error("鍒濆鍖栬鍙朠LC鍙傛暟澶辫触: {}", e.getMessage(), e);
-            return;
-        }
-        // 涓烘瘡涓�昏緫椤瑰垱寤哄苟鍚姩瀛愮嚎绋�
-        //startLogicThread(logicConfig.getLogics().get(0));
-        for (LogicItem logicItem : logicConfig.getLogics()) {
-            startLogicThread(logicItem);
-            //startLogicThread(logicConfig.getLogics().get(0));
-        }
-
         // 涓荤嚎绋嬫寔缁繍琛岋紝瀹氭湡璇诲彇PLC鍙傛暟骞剁洃鎺ц繛鎺ョ姸鎬�
         while (running) {
             try {
-                // 璇诲彇PLC鍙傛暟锛屼负閫昏緫澶勭悊鎻愪緵鏈�鏂版暟鎹�
-                readPlcParameter();
-
                 // 妫�鏌LC杩炴帴鐘舵��
                 if (!client.isConnected()) {
-                    log.warn("PLC杩炴帴鏂紑锛屽皾璇曢噸鏂拌繛鎺�");
+                    log.info("PLC灏濊瘯杩炴帴... 璁惧IP: {}", machine.getIp());
                     tryReconnect();
                 }
-
-                // 妫�鏌ラ�昏緫绾跨▼鐘舵�侊紝閲嶅惎宸茬粓姝㈢殑绾跨▼
+                // 璇诲彇PLC鍙傛暟锛屼负閫昏緫澶勭悊鎻愪緵鏈�鏂版暟鎹�
+                this.readPlcParameter();
+                plcParameters.Initialization();
+                // 妫�鏌ラ�昏緫绾跨▼鐘舵�侊紝寮�鍚�/閲嶅惎 绾跨▼
                 checkLogicThreadsStatus();
-
                 // 绛夊緟涓嬩竴涓墽琛屽懆鏈�
                 Thread.sleep(mainThreadInterval);
             } catch (InterruptedException e) {
@@ -140,7 +124,6 @@
                 }
             }
         }
-
         // 绾跨▼閫�鍑哄墠鍏抽棴鎵�鏈夎祫婧�
         shutdown();
         log.info("MachineThread宸查��鍑猴紝璁惧IP: {}", machine.getIp());
@@ -148,28 +131,22 @@
 
     // 涓烘寚瀹氶�昏緫椤瑰垱寤哄苟鍚姩瀛愮嚎绋�
     private void startLogicThread(LogicItem logicItem) {
-        String logicId = logicItem.getName(); // 鍋囪姣忎釜LogicItem鏈夊敮涓�ID
+        String logicId = this.machine.getId()+" - "+this.machine.getName()+" - "+ logicItem.getName(); // 鍋囪姣忎釜LogicItem鏈夊敮涓�ID
         if (logicThreads.containsKey(logicId) && logicThreads.get(logicId).isAlive()) {
-            log.warn("閫昏緫椤圭嚎绋嬪凡鍦ㄨ繍琛�: {}", logicId);
             return;
         }
-
         // 璁剧疆杩愯鏍囧織
         logicRunningFlags.put(logicId, true);
-
         // 鍒涘缓骞跺惎鍔ㄧ嚎绋�
         Thread thread = new Thread(() -> {
             log.info("閫昏緫椤圭嚎绋嬪惎鍔�: {}", logicId);
-
             // 閫昏緫椤瑰瓙绾跨▼鎸佺画杩愯鐨勫惊鐜�
             while (logicRunningFlags.getOrDefault(logicId, false)) {
                 try {
                     // 鎵ц瀹為檯涓氬姟閫昏緫
                     basicsLogic(logicItem);
-
                     // 鏍规嵁閫昏緫椤圭殑鎵ц棰戠巼璁剧疆绛夊緟鏃堕棿锛岄粯璁�1000ms
-                    int logicInterval = 1000;
-                    Thread.sleep(logicInterval);
+                    Thread.sleep(logicItem.getLogicInterval());
                 } catch (InterruptedException e) {
                     log.info("閫昏緫椤圭嚎绋嬭涓柇锛屽噯澶囬��鍑�: {}", logicId);
                     logicRunningFlags.put(logicId, false);
@@ -186,31 +163,23 @@
                     }
                 }
             }
-
-            log.info("閫昏緫椤圭嚎绋嬪凡閫�鍑�: {}", logicId);
         });
-
         // 璁剧疆绾跨▼鍚嶇О
-        thread.setName("Logic-" + logicId);
-
+        thread.setName(logicId);
         // 瀛樺偍绾跨▼寮曠敤
         logicThreads.put(logicId, thread);
-
         // 鍚姩绾跨▼
         thread.start();
-        log.info("宸插惎鍔ㄩ�昏緫椤圭嚎绋�: {}", logicId);
+        //log.info("宸插惎鍔ㄩ�昏緫椤圭嚎绋�: {}", logicId);
     }
 
     // 妫�鏌ラ�昏緫绾跨▼鐘舵�侊紝閲嶅惎宸茬粓姝㈢殑绾跨▼
     private void checkLogicThreadsStatus() {
         for (LogicItem logicItem : logicConfig.getLogics()) {
-            String logicId = logicItem.getName();
+            String logicId = this.machine.getId()+" - "+this.machine.getName()+" - "+ logicItem.getName();
             Thread thread = logicThreads.get(logicId);
-
             // 濡傛灉绾跨▼涓嶅瓨鍦ㄦ垨宸茬粓姝笖杩愯鏍囧織涓簍rue锛屽垯閲嶅惎绾跨▼
-            if ((thread == null || !thread.isAlive()) &&
-                    logicRunningFlags.getOrDefault(logicId, false)) {
-                log.warn("閫昏緫椤圭嚎绋嬪凡缁堟锛屽噯澶囬噸鍚�: {}", logicId);
+            if ((thread == null || !thread.isAlive()) &&!logicRunningFlags.getOrDefault(logicId, false)) {
                 startLogicThread(logicItem);
             }
         }
@@ -220,9 +189,9 @@
     private void tryReconnect() {
         if (client != null) {
             try {
-                log.info("灏濊瘯閲嶆柊杩炴帴PLC: {}", machine.getIp());
                 client.disconnect();
                 Thread.sleep(2000);
+                client.connect();
                 boolean reconnected = client.isConnected();
                 if (reconnected) {
                     log.info("PLC閲嶆柊杩炴帴鎴愬姛: {}", machine.getIp());
@@ -238,7 +207,6 @@
     // 鍏抽棴绾跨▼鍓嶇殑娓呯悊宸ヤ綔
     public void shutdown() {
         running = false;
-
         // 鍋滄鎵�鏈夐�昏緫绾跨▼
         for (String logicId : logicRunningFlags.keySet()) {
             logicRunningFlags.put(logicId, false);
@@ -247,7 +215,6 @@
                 thread.interrupt();
             }
         }
-
         // 绛夊緟鎵�鏈夐�昏緫绾跨▼缁撴潫
         for (String logicId : logicThreads.keySet()) {
             Thread thread = logicThreads.get(logicId);
@@ -292,37 +259,24 @@
                 }
             }
             if (isEqual){
-                List<String> result=new ArrayList<>();
+                log.info("婊¤冻鏉′欢:{}",logicItem.getName());
                 //3.鏌ヨ姝ら�昏緫涓嬮渶瑕佽繑鍥炵粰PLC鐨勬暟鎹� result鍙帴鏀�  HTTP鎺ュ彛,瑙嗗浘,瀛樺偍杩囩▼ 绛�  濡備笅
-                try{
-                    String connectType=logicItem.getConnectType();
-                    String connectAddress=logicItem.getConnectAddress();
-                    Map map=new HashMap();
-                    switch (connectType) {
-                        case "Http":
-                            map.put("method","POST");
-                            map.put("plcParameter",plcParameters);
-                            result= api.httpApi(connectAddress,map);
-                            log.info("鎺ュ彛杩斿洖鍐呭锛歿}",result);
-                            break;
-                        case "View": // 瑙嗗浘/琛�
-                            result= api.viewApi(connectAddress,map);
-                            break;
-                        case "Procedure": // 瀛樺偍杩囩▼
-                            //result= api.procedureAPI(connectAddress,plcParameter);
-                            break;
-                        default:
-                            log.warn("涓嶆敮鎸佺殑杩炴帴绫诲瀷: {}", connectType);
-                            return; // 涓嶆敮鎸佺殑鏂瑰紡
+                List<String> resultWrite=null;
+                if (logicItem.getApiConfigBefore()!=null){
+                    ApiConfig apiConfig=logicItem.getApiConfigBefore();
+                    resultWrite=api.callApi(apiConfig,plcParameters);
+                    log.info("ApiConfigBefore  澶栫疆鎺ュ彛[{}:{}]杩斿洖鐨勫唴瀹�:{}",apiConfig.getType(),apiConfig.getAddress(),resultWrite);
+                }
+                //鍐欏叆PLC杩斿洖鍊兼垚鍔熸椂璋冪敤鎺ュ彛
+                if (basicsResult(resultWrite,logicItem.getReturnValue())){
+                    ApiConfig apiConfig=logicItem.getApiConfigAfter();
+                    if (logicItem.getApiConfigAfter()!=null){
+                        List<String> result=api.callApi(apiConfig,plcParameters);
+                        log.info("ApiConfigAfter  澶栫疆鎺ュ彛[{}:{}]杩斿洖鐨勫唴瀹�:{}",apiConfig.getType(),apiConfig.getAddress(),result);
                     }
+                }
 
-                }catch (Exception e){
-                    log.error("璋冪敤鎺ュ彛澶辫触: {}", e.getMessage(), e);
-                }
-                //4.杩斿洖PLC鍐呭
-                if (result != null&&!result.isEmpty()) {
-                    basicsResult(result,logicItem.getReturnValue());
-                }
+
             }
         }  catch (Exception e) {
             log.error("鎵цbasicsLogic澶辫触: {}", e.getMessage(), e);
@@ -344,20 +298,22 @@
             if (values!=null && !values.equals("")){
                 //杩橀渶澧炴坊  涓嶅悓绫诲瀷璋冪敤涓嶅悓鏂规硶
                 switch (itemReturnValue.getPlcDataType()) {
-                    case "int":
+                    case "Word":
                         client.writeRegister(itemReturnValue.getAddress(),(int)Double.parseDouble(values));
                         break;
-                    case "string":
+                    case "String":
                         client.writeString(itemReturnValue.getAddress(),values);
                         break;
-                    case "float":
+                    case "Float":
                         client.writeFloat(itemReturnValue.getAddress(),Float.valueOf(values));
+                        break;
+                    case "bit":
+                        client.writeBit(itemReturnValue.getAddress(),Boolean.valueOf(values));
                         break;
                     default:
                         log.error("涓嶆敮鎸佺殑鏁版嵁绫诲瀷: {}", itemReturnValue.getPlcDataType());
                         return false;
                 }
-
             }
         }
         return true;

--
Gitblit v1.8.0