Browse Source

优化PLC及MQTT连接

zhifei 1 year ago
parent
commit
485fec15fa

+ 4 - 4
ruoyi-admin/src/main/resources/application-prod.yml

@@ -69,11 +69,11 @@ init-task:
 
 modbus:
     tcp-master:
-        fourth: # 充电机(三向车)
-            open: false
-            host: 192.168.42.208
+        fourth: # 充电机
+            open: true
+            host: 192.168.62.106
             port: 8899
-        fifth: # 充电机(迷你堆垛)
+        fifth: # 充电机
             open: false
             host: 192.168.42.209
             port: 8899

+ 89 - 0
ruoyi-admin/src/main/resources/application-test.yml

@@ -0,0 +1,89 @@
+# 数据源配置
+spring:
+    datasource:
+        type: com.alibaba.druid.pool.DruidDataSource
+        driverClassName: com.mysql.cj.jdbc.Driver
+        druid:
+            # 主库数据源
+            master:
+                url: jdbc:mysql://61.169.55.84:3306/warewms-tianao?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
+                username: warewms
+                password: warewms123
+            # 从库数据源
+            slave:
+                # 从数据源开关/默认关闭
+                enabled: false
+                url:
+                username:
+                password:
+            # 初始连接数
+            initialSize: 5
+            # 最小连接池数量
+            minIdle: 10
+            # 最大连接池数量
+            maxActive: 50
+            # 配置获取连接等待超时的时间
+            maxWait: 60000
+            # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
+            timeBetweenEvictionRunsMillis: 60000
+            # 配置一个连接在池中最小生存的时间,单位是毫秒
+            minEvictableIdleTimeMillis: 300000
+            # 配置一个连接在池中最大生存的时间,单位是毫秒
+            maxEvictableIdleTimeMillis: 900000
+            # 配置检测连接是否有效
+            validationQuery: SELECT 1 FROM DUAL
+            testWhileIdle: true
+            testOnBorrow: false
+            testOnReturn: false
+            webStatFilter:
+                enabled: true
+            statViewServlet:
+                enabled: true
+                # 设置白名单,不填则允许所有访问
+                allow:
+                url-pattern: /druid/*
+                # 控制台管理用户名和密码
+                login-username: ruoyi
+                login-password: 123456
+            filter:
+                stat:
+                    enabled: true
+                    # 慢SQL记录
+                    log-slow-sql: true
+                    slow-sql-millis: 1000
+                    merge-sql: true
+                wall:
+                    config:
+                        multi-statement-allow: true
+
+# 日志配置
+logging:
+    level:
+        com.ruoyi: info
+        org.springframework: info
+
+# 是否开启服务
+init-task:
+    autosend: false # 自动下发任务
+    aciservice: false # ndc通讯
+
+modbus:
+    tcp-master:
+        fourth: # 充电机(三向车)
+            open: false
+            host: 192.168.42.208
+            port: 8899
+        fifth: # 充电机(迷你堆垛)
+            open: false
+            host: 192.168.42.209
+            port: 8899
+
+# plc连接配置
+plc:
+    plcList[0]:
+        ip: 192.168.60.151
+        enable: false
+        name: conveyorBeltsPlc
+        ePlcType: S1200
+        heartbeat: DB1054.0.0
+        confirmTheStatus: DB1055.0.0

+ 8 - 1
ruoyi-admin/src/test/java/com/ruoyi/admin/test/base/WarehouseTest.java

@@ -1260,7 +1260,7 @@ public class WarehouseTest {
 
     @Test
     public void updateTSVlue() throws IOException {
-        File file = new File("C:\\Users\\charl\\Desktop\\tianao\\C区库位对照_240117_1705478614020.json");
+        File file = new File("C:\\Users\\charl\\Desktop\\tianao\\C区库位对照_240117_1705650672857.json");
         InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
         StringBuffer stringBuffer = new StringBuffer();
         char[] chars = new char[1];
@@ -1354,6 +1354,13 @@ public class WarehouseTest {
         }
     }
 
+    public static void main(String[] args) {
+        System.out.println(String.format("%04X",1));
+        System.out.println(String.format("%04X",80309));
+        System.out.println("87CD0008000A0001006D0006000B01010002");
+        System.out.println("87CD0008000C00010071000663010001%04X");
+
+    }
 
     @Test
     public void testNDC(){

+ 1 - 1
ruoyi-system/src/main/java/com/ruoyi/system/init/PlcConnectServiceRunner.java

@@ -104,7 +104,7 @@ public class PlcConnectServiceRunner implements CommandLineRunner {
                             return true;
                         }
                     }catch (Exception e){
-                        log.info("plc:{},ip:{},Retry connection failed,meg:{}",plcConfig.getName(),plcConfig.getIp(),e.getMessage());
+                        log.info("plc:{},ip:{},Retry connection failed,meg:",plcConfig.getName(),plcConfig.getIp(),e);
                         return false;
                     }
                     return false;

+ 73 - 19
ruoyi-system/src/main/java/com/ruoyi/system/init/PublishAGVInfo.java

@@ -1,5 +1,9 @@
 package com.ruoyi.system.init;
 
+import com.github.rholder.retry.Retryer;
+import com.github.rholder.retry.RetryerBuilder;
+import com.github.rholder.retry.StopStrategies;
+import com.github.rholder.retry.WaitStrategies;
 import com.ruoyi.system.config.MQTTConfig;
 import lombok.extern.slf4j.Slf4j;
 import org.eclipse.paho.client.mqttv3.MqttClient;
@@ -9,8 +13,12 @@ import org.eclipse.paho.client.mqttv3.MqttMessage;
 import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 import org.springframework.boot.CommandLineRunner;
 import org.springframework.core.annotation.Order;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.stereotype.Component;
 
+import javax.annotation.Resource;
+import java.util.concurrent.TimeUnit;
+
 /**
  * mqtt发布AGV实时坐标
  */
@@ -19,22 +27,27 @@ import org.springframework.stereotype.Component;
 @Slf4j
 public class PublishAGVInfo implements CommandLineRunner {
 
-    private final String topic="position";
+    private final String topic = "position";
 
-    private int  qos = 1;
+    private int qos = 1;
 
-    private  MemoryPersistence persistence = new MemoryPersistence();
+    private MemoryPersistence persistence = new MemoryPersistence();
 
     private MQTTConfig mqttConfig = new MQTTConfig();
 
     private MqttClient sampleClient;
 
+    @Resource
+    ThreadPoolTaskExecutor threadPoolTaskExecutor;
+
+    private boolean isConnect = false;
+
     @Override
     public void run(String... args) throws Exception {
-//        initConnect();
+        initConnect();
     }
 
-    private void initConnect(){
+    private void initConnect() {
         try {
             // 创建客户端
             sampleClient = new MqttClient(mqttConfig.getHOST(), mqttConfig.getClientId(), persistence);
@@ -48,37 +61,78 @@ public class PublishAGVInfo implements CommandLineRunner {
             // 建立连接
             sampleClient.connect(connOpts);
             log.info("MQTT 连接完成!");
+            isConnect = true;
         } catch (MqttException me) {
-            log.error("An exception occurred when initializing the MQTT connection,msg:{}",me.getMessage());
+            retry();
+            log.error("An exception occurred when initializing the MQTT connection,msg", me);
         }
     }
 
-    public void closeConnection(){
+    public void closeConnection() {
         try {
             // 断开连接
             sampleClient.disconnect();
             // 关闭客户端
             sampleClient.close();
-        }catch (MqttException me){
-            log.error("An exception occurred when the connection about MQTT was closed,msg:{}",me.getMessage());
+        } catch (MqttException me) {
+            log.error("An exception occurred when the connection about MQTT was closed,msg:", me);
         }
 
     }
 
+    public void retry() {
+        threadPoolTaskExecutor.execute(() -> {
+            Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
+                    .retryIfResult(Boolean.FALSE::equals)
+                    .retryIfExceptionOfType(Exception.class)
+                    .withStopStrategy(StopStrategies.neverStop())
+                    .withWaitStrategy(WaitStrategies.fixedWait(7, TimeUnit.SECONDS))
+                    .build();
+            try {
+                retryer.call(() -> {
+                    try {
+                    // 创建客户端
+                    sampleClient = new MqttClient(mqttConfig.getHOST(), mqttConfig.getClientId(), persistence);
+                    // 创建链接参数
+                    MqttConnectOptions connOpts = new MqttConnectOptions();
+                    // 在重新启动和重新连接时记住状态
+                    connOpts.setCleanSession(false);
+                    // 设置连接的用户名
+                    connOpts.setUserName(mqttConfig.getUserName());
+                    connOpts.setPassword(mqttConfig.getPassword().toCharArray());
+                    // 建立连接
+                    sampleClient.connect(connOpts);
+                    log.info("MQTT 连接完成!");
+                    isConnect = true;
+                    return true;
+                    } catch (MqttException me) {
+                        log.error("An exception occurred when initializing the MQTT connection,msg:", me);
+                        return false;
+                    }
+                });
+            } catch (Exception e) {
+                log.error("An exception occurred during the retry ,msg:", e);
+            }
+        });
+    }
 
-
-    public void publishMessage(String content){
+    public void publishMessage(String content) {
+        if (!isConnect){
+            log.error("The MQTT connection is disconnected!");
+            return;
+        }
         try {
-        // 创建消息
-        MqttMessage message = new MqttMessage(content.getBytes());
-        // 设置消息的服务质量
-        message.setQos(qos);
-        // 发布消息
-        sampleClient.publish(topic, message);
-        }catch (MqttException me){
+            // 创建消息
+            MqttMessage message = new MqttMessage(content.getBytes());
+            // 设置消息的服务质量
+            message.setQos(qos);
+            // 发布消息
+            sampleClient.publish(topic, message);
+        } catch (MqttException me) {
+            isConnect = false;
             closeConnection();
             initConnect();
-            log.error("An exception occurred in the release information,msg:{}",me.getMessage());
+            log.error("An exception occurred in the release information,msg:",me );
         }
     }
 }

+ 1 - 1
warewms-hard/src/main/java/com/ruoyi/hard/modbus/tcp/ChargingMachineClient.java

@@ -59,7 +59,7 @@ public class ChargingMachineClient {
      * 机器编号
      */
     public enum MACHINE_NO {
-        A("1",1),
+        A("8106",1),
         B("2",2);
 
         private String value;