diff --git a/app/src/main/java/com/example/bpa/helper/MQTT.java b/app/src/main/java/com/example/bpa/helper/MQTT.java index 5c3d652..dd20ae7 100644 --- a/app/src/main/java/com/example/bpa/helper/MQTT.java +++ b/app/src/main/java/com/example/bpa/helper/MQTT.java @@ -18,6 +18,10 @@ import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.LineNumberReader; + /** * mqtt帮助类 */ @@ -105,9 +109,72 @@ public class MQTT { } }); - ConnMqttBroken(true); + + new Thread(new Runnable() { + @Override + public void run() { + try { + boolean status = false; + while (!status) { + try { + //status为0则代表通,为1则代表不通。 + status =ping2(Ip,1,1); + Thread.sleep(1000); + } catch (InterruptedException e) { + MessageLog.ShowInfo("MQTT " + Ip + " 网络验证失败"); + } catch (Exception e) { + MessageLog.ShowInfo("MQTT " + Ip+ " 网络验证失败"); + } + } + ConnMqttBroken(true); + } catch (Exception e) { + + } + } + }).start(); + } + /** + * Ping PLC地址是否通畅 + * @param address + * @param pingTimes ping的次数 + * @param timeOut 超时时间 10 + * @return + */ + public static boolean ping2(String address, int pingTimes, int timeOut) { + Process process = null; + try { + process = Runtime.getRuntime().exec( "ping " + "-c " + pingTimes + " -w " + timeOut+ " "+address); + InputStreamReader r = new InputStreamReader(process.getInputStream()); + + LineNumberReader returnData = new LineNumberReader(r); + + String returnMsg=""; + + String line = ""; + while ((line = returnData.readLine()) != null) { + + System.out.println(line); + + returnMsg += line; + + } + + if(returnMsg.indexOf("100% packet loss")!=-1){ + System.out.println("与 " +address +" 连接不畅通."); + return false; + } else{ + + System.out.println("与 " +address +" 连接畅通."); + return true; + } + } catch (IOException e) { + e.printStackTrace(); + } + return false; + + } /** * 连接 或者断开MQTT * @param bloConn