tom пре 5 месеци
родитељ
комит
b689f2f0ad
1 измењених фајлова са 21 додато и 10 уклоњено
  1. 21 10
      ruoyi-sim/src/main/java/com/ruoyi/sim/service/impl/IotService.java

+ 21 - 10
ruoyi-sim/src/main/java/com/ruoyi/sim/service/my/IotService.java → ruoyi-sim/src/main/java/com/ruoyi/sim/service/impl/IotService.java

@@ -1,15 +1,18 @@
-package com.ruoyi.sim.service.my;
+package com.ruoyi.sim.service.impl;
 
+import com.ruoyi.sim.config.SimConfig;
 import org.slf4j.LoggerFactory;
 import org.slf4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.net.InetAddress;
 import java.net.Socket;
 
-import static com.ruoyi.sim.service.my.IotService.Const.*;
+import static com.ruoyi.sim.service.impl.IotService.Const.*;
 
 /**
  * 硬件通信
@@ -55,7 +58,10 @@ public class IotService {
 
     private static final Logger logger = LoggerFactory.getLogger(IotService.class);
 
-    private Socket socket = null;
+    private Socket cachedSocket = null;
+
+    @Autowired
+    private SimConfig sc;
 
     /**
      * 检查所有模拟器状态
@@ -171,11 +177,11 @@ public class IotService {
         logger.info(sendMsg);
         String receiveMsg = null;
         try {
-            if (socket == null) {
-                socket = new Socket(IP, PORT);
+            if (cachedSocket == null) {
+                cachedSocket = new Socket(IP, PORT);
             }
-            InputStream is = socket.getInputStream();
-            OutputStream os = socket.getOutputStream();
+            InputStream is = cachedSocket.getInputStream();
+            OutputStream os = cachedSocket.getOutputStream();
             os.write(hexStrToByteArrs(sendMsg));
             byte[] buffer = new byte[1024];
             int length = is.read(buffer);
@@ -197,13 +203,13 @@ public class IotService {
      */
     public void close() {
         try {
-            if (socket != null) {
-                socket.close();
+            if (cachedSocket != null) {
+                cachedSocket.close();
             }
         } catch (IOException e) {
             throw new RuntimeException(e);
         } finally {
-            socket = null;
+            cachedSocket = null;
         }
     }
 
@@ -224,4 +230,9 @@ public class IotService {
         }
         return bytes;
     }
+
+    public boolean isReachable(String ipV4) throws IOException {
+        InetAddress ia = InetAddress.getByName(ipV4);
+        return ia.isReachable(sc.getGatewayReachableTimeout());
+    }
 }