From be95e839f40eb3ddf64706b60cba6dfcf4fad5e5 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期五, 03 四月 2020 14:31:44 +0800
Subject: [PATCH] 2020-04-03 1.去掉登录前ping百度域名的网络监测。

---
 Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs |  430 +++++++++++++++++++++++++++++++++++++++--------------
 1 files changed, 316 insertions(+), 114 deletions(-)

diff --git a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
index 997458f..0d6fb64 100644
--- a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
+++ b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
@@ -21,6 +21,7 @@
         static string checkGatewayTopicBase64 = "";
         static RemoteMACInfo CurRemoteMACInfo = null;
         static MqttInfo mMqttInfo = null;
+        public static bool IsGatewayOnline = true;
 
         /// <summary>
         /// 鎵嬫満鏍囪瘑
@@ -44,6 +45,7 @@
         static MqttCommon ()
         {
             InitMqtt ();
+            InitCheckGateway ();
         }
 
         /// <summary>
@@ -54,11 +56,13 @@
         {
             new System.Threading.Thread (async () => {
                 while (true) {
-                    System.Threading.Thread.Sleep (100);
-                    if (!CommonPage.IsRemote) continue;
+                    try {
+                        System.Threading.Thread.Sleep (100);
+                        if (!CommonPage.IsRemote) continue;
 
-                    await StartCloudMqtt ();
-                    await CheckingSubscribeTopics ();
+                        await StartCloudMqtt ();
+                        await CheckingSubscribeTopics ();
+                    } catch { }
 
                 }
             }) { IsBackground = true }.Start ();
@@ -97,7 +101,15 @@
                         QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                     };
 
-                    var topicFilters = new TopicFilter [] { topicFilterCommon, topicFilterGateWayInfoChange, topicFilterNotifySqueeze };
+                    //缃戝叧鎺夌嚎涓婚
+                    var topicFilterNotifyGateWayOffline = new TopicFilter () {
+                        Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyGateWayOffline",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    
+
+                    var topicFilters = new TopicFilter [] { topicFilterCommon, topicFilterGateWayInfoChange, topicFilterNotifySqueeze, topicFilterNotifyGateWayOffline };
                     var result = await RemoteMqttClient.SubscribeAsync (topicFilters);
                     if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2) {
                         isSubscribeTopicSuccess = true;
@@ -110,21 +122,26 @@
 
 
 
-        /// <summary>
-        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
         /// </summary>
-        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient (string s = "")
-        {
-            try {
-                if (remoteIsConnected) {
-                    remoteIsConnected = false;
-                    System.Console.WriteLine ($"============>MqttRemote涓诲姩鏂紑_{s}");
-                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
+        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient (string s = "")
+        {
+            try {
+                if (remoteIsConnected) {
+                    remoteIsConnected = false;
+                    Utlis.WriteLine ($"============>MqttRemote涓诲姩鏂紑_{s}");
+                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                     await RemoteMqttClient.DisconnectAsync ();
-                }
+                    if (CommonPage.IsRemote) {
+                        Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
+                    }
+                    Utlis.WriteLine ($"============>MqttRemoteDisConnectRemoteMqttClient");
+
+                }
             } catch (Exception e) {
-                System.Console.WriteLine ($"============>MqttRemote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
-            }
+                Utlis.WriteLine ($"============>MqttRemote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
         }
         static DateTime dateTime = DateTime.MinValue;
 
@@ -172,68 +189,39 @@
                                     }
                                     var aesDecryptTopic = e.ApplicationMessage.Topic;
                                     var aesDecryptPayload = e.ApplicationMessage.Payload;
-                                    //Console.WriteLine ("Topic={0}", aesDecryptTopic);
+                                    //Utlis.WriteLine ("Topic={0}", aesDecryptTopic);
 
                                     //if (aesDecryptTopic == $"NotifyBusGateWayInfoChagne/{CurRemoteMACInfo.md5_mac_string}") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
                                     //2020-01-11 淇敼璁㈤槄涓婚鍦板潃
                                     if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey                                                                                                                     //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
                                         await ReceiveNotifyBusGateWayInfoChange ();
+                                    } else if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyGateWayOffline") {//缃戝叧鎺夌嚎                                                                                                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
+                                        ReceiveNotifyGateWayOffline ();
                                     } else if (aesDecryptTopic == $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze") {//璁㈤槄鎸や笅绾块棶棰�
                                         await ReceiveNotifySqueezeAsync (aesDecryptPayload);
                                     }else if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/CheckGateway") {
-                                        MainPage.WiFiStatus = "CrabtreeAdd/CloudUnlink.png";
-                                        // = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
-                                        var ss = CommonPage.MyEncodingUTF8.GetString (aesDecryptPayload);
-                                        var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack> (ss);
-                                        if (obj == null) {
-                                            return;
-                                        }
-                                        switch (obj.StateCode) {
-                                        case "HDLUdpDataForwardServerMqttClientNoOnLine":
-                                        case "NoOnline":
-                                        case "NetworkAnomaly"://涓嶅湪绾�
-                                            MainPage.AddTip ("Gateway offline");
-                                            //Application.RunOnMainThread (() => {
-                                            //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                                            //});
-                                            break;
-                                        case "NoRecord"://MAC涓嶆纭�
-                                            MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.MACError));
-                                            //Application.RunOnMainThread (() => {
-                                            //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                                            //});
-                                            break;
-                                        case "Success":
-                                            MainPage.AddTip (UserConfig.Instance.CurrentRegion.Name + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
-                                            MainPage.WiFiStatus = "CrabtreeAdd/CloudLink.png";
-                                            break;
-                                        default:
-                                            MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkLoser));
-                                            //Application.RunOnMainThread (() => {
-                                            //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                                            //});
-                                            break;
-                                        }
-                                        Application.RunOnMainThread (() => {
-                                            UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
-                                        });
+                                        ReceiveCheckGatewayTopic ();
                                     } else {
+                                        SetGatewayOnlineResetCheck ();
+
                                         if (!string.IsNullOrEmpty (mqttEncryptKey)) {
                                             aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey);
                                         }
 
+                                        var packet = new Packet ();
+                                        packet.IsLocal = false;
+                                        packet.Bytes = aesDecryptPayload;
+                                        packet.Manager ();
+
                                     }
-                                    var packet = new Packet ();
-                                    packet.IsLocal = false;
-                                    packet.Bytes = aesDecryptPayload;
-                                    packet.Manager ();
+                                   
                                 } catch { }
                             });
                         }
 
                         if (RemoteMqttClient.DisconnectedHandler == null) {
                             RemoteMqttClient.UseDisconnectedHandler (async (e) => {
-                                System.Console.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑");
+                                Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑");
                                 isSubscribeTopicSuccess = false;
                                 await DisConnectRemoteMqttClient ("StartRemoteMqtt.DisconnectedHandler");
                                 //await StartRemoteMqtt();
@@ -250,20 +238,38 @@
                         }
                         if (RemoteMqttClient.ConnectedHandler == null) {
                             RemoteMqttClient.UseConnectedHandler (async (e) => {
+                                IfNeedReadAllDeviceStatus = true;
 
-                                Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
-                                System.Console.WriteLine ($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
+                                Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
                                 if (CommonPage.IsRemote) {
                                     Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
                                 }
 
                                 if (CurRemoteMACInfo != null) {
-                                    if (CurRemoteMACInfo.isValid == "InValid") {
+                                    IsGatewayOnline = CurRemoteMACInfo.isValid != "InValid";
+                                    if (!IsGatewayOnline) {
+                                        //缃戝叧涓嶅湪绾�
+                                        if (CommonPage.IsRemote) {
+                                            Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
+                                        }
                                         MainPage.AddTip ("Remote failed,gateway offline");
                                     } else {
+                                        //缃戝叧鍦ㄧ嚎
+
+                                        //閲嶆柊涓�娆℃墍鏈夎澶囩姸鎬�
+                                        IfNeedReadAllDeviceStatus = false;
+                                        Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
+                                        //
                                         MqttRemoteSend (new byte [] { 0 }, 3);
                                     }
+
+                                    //if (CurRemoteMACInfo.isValid == "InValid") {
+                                    //    MainPage.AddTip ("Remote failed,gateway offline");
+                                    //} else {
+                                    //    MqttRemoteSend (new byte [] { 0 }, 3);
+                                    //}
                                 }
+
 
                             });
                         }
@@ -298,7 +304,7 @@
                                         await MQTTConnectAsync ();
 
                                     } else {
-                                        System.Console.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧");
+                                        Utlis.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧");
                                     }
 
                                 }
@@ -328,7 +334,7 @@
                         }
 
                 } catch (Exception ex) {
-                    System.Console.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
+                    Utlis.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
                 } finally {
                     //鏈�缁堣閲婃斁杩炴帴鐘舵��
                     remoteMqttIsConnecting = false;
@@ -361,6 +367,7 @@
                 await DisConnectRemoteMqttClient ("StartRemoteMqtt");
                 await RemoteMqttClient.ConnectAsync (options1);
                 remoteIsConnected = true;
+                IsDisConnectingWithSendCatch = false;
                 //await MqttRemoteSend (new byte [] { 0 }, 1);
                 //await MqttRemoteSend (new byte [] { 0 }, 2);
                 //await MqttRemoteSend (new byte [] { 0 }, 4);
@@ -368,67 +375,112 @@
             }
         }
 
-     
+
+        ///// <summary>
+        ///// 
+        ///// </summary>
+        ///// <param name="message">闄勫姞鏁版嵁鍖�</param>
+        ///// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁;3=璁㈤槄缃戝叧鏄惁鍦ㄧ嚎涓婚  4=璁㈤槄鎸や笅绾夸富棰� </param>
+        ///// <returns></returns>
+        //public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
+        //{
+        //    try {
+        //        if (!remoteIsConnected) {
+        //            Utlis.WriteLine ($"============>Mqtt 鏈繛鎺� 鍙栨秷鍙戦��");
+        //            return;
+        //        }
+
+        //        var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid;
+        //        switch (optionType) {
+        //        case 0:
+        //            var messageSend = message;
+        //            if (string.IsNullOrEmpty (mqttEncryptKey)) {
+        //                topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
+        //            } else {
+        //                topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/NewON";
+        //                messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
+        //            }
+        //            //base64鍔犲瘑
+        //            var m = new MqttApplicationMessage { Topic = topicName, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
+        //            //if (remoteIsConnected) {
+        //            try {
+        //                RemoteMqttClient.PublishAsync (m);
+        //            } catch (Exception e) {
+        //                //await DisConnectRemoteMqttClient (e.Message);
+        //                //await StartCloudMqtt ();
+        //                //if (remoteIsConnected) {
+        //                //    RemoteMqttClient.PublishAsync (m);
+        //                //}
+        //            }
+        //            //}
+        //            break;
+        //        case 3:
+        //            topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
+
+        //            var m1 = new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
+
+        //            try {
+        //                Utlis.WriteLine ("CheckGateway");
+        //                RemoteMqttClient.PublishAsync (m1);
+        //            } catch (Exception e) {
+        //                Utlis.WriteLine ($"CheckGateway Fail:{e.Message}");
+        //                //await DisConnectRemoteMqttClient (e.Message);
+        //                //await StartCloudMqtt ();
+        //            }
+        //            break;
+        //        }
+
+
+        //    } catch (Exception e) {
+
+        //    }
+        //}
+
         /// <summary>
         /// 
         /// </summary>
         /// <param name="message">闄勫姞鏁版嵁鍖�</param>
-        /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁;3=璁㈤槄缃戝叧鏄惁鍦ㄧ嚎涓婚  4=璁㈤槄鎸や笅绾夸富棰� </param>
+        /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁</param>
         /// <returns></returns>
         public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
         {
             try {
-                if (!remoteIsConnected) {
-                    System.Console.WriteLine ($"============>Mqtt 鏈繛鎺� 鍙栨秷鍙戦��");
-                    return;
-                }
+                //if (!remoteIsConnected) {
+                //    Utlis.WriteLine ($"============>Mqtt 鏈繛鎺� 鍙栨秷鍙戦��");
+                //    return;
+                //}
 
-                var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid;
+                string topicName;
                 switch (optionType) {
                 case 0:
-                    var messageSend = message;
-                    if (string.IsNullOrEmpty (mqttEncryptKey)) {
-                        topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
-                    } else {
-                        topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/NewON";
-                        messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
+                    topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/ON";
+                    if (!string.IsNullOrEmpty (mqttEncryptKey)) {
+                        message = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
                     }
-                    //base64鍔犲瘑
-                    var m = new MqttApplicationMessage { Topic = topicName, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
-                    //if (remoteIsConnected) {
-                    try {
-                         RemoteMqttClient.PublishAsync (m);
-                    } catch (Exception e) {
-                        //await DisConnectRemoteMqttClient (e.Message);
-                        //await StartCloudMqtt ();
-                        //if (remoteIsConnected) {
-                        //    RemoteMqttClient.PublishAsync (m);
-                        //}
-                    }
-                    //}
+                    await RemoteMqttClient.PublishAsync (new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                     break;
                 case 3:
                     topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
-
-                    var m1 = new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
-
-                    try {
-                        Console.WriteLine ("CheckGateway");
-                         RemoteMqttClient.PublishAsync (m1);
-                    } catch (Exception e) {
-                        Console.WriteLine ($"CheckGateway Fail:{e.Message}");
-                        //await DisConnectRemoteMqttClient (e.Message);
-                        //await StartCloudMqtt ();
-                    }
+                    //Utlis.WriteLine ("CheckGateway");
+                    await RemoteMqttClient.PublishAsync (new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                     break;
                 }
-
-
             } catch (Exception e) {
+                // Utlis.WriteLine ($"============>Mqtt MqttRemoteSend catch");
+                 if (!IsDisConnectingWithSendCatch) {
+                    IsDisConnectingWithSendCatch = true;
+                    await DisConnectRemoteMqttClient ("MqttRemoteSendCatch");
+                }
 
             }
         }
 
+        /// <summary>
+        /// SendCatch 鍚庢墽琛屼竴娆℃柇寮�鎿嶄綔
+        /// </summary>
+        static bool IsDisConnectingWithSendCatch = false;
+
+     
 
         /// <summary>
         /// 鍒嗕韩浣忓畢 鑾峰彇褰撳墠浣忓畢缃戝叧淇℃伅骞朵笖杩炴帴MQTT 鎴栬�呭埛鏂�  
@@ -472,7 +524,7 @@
 
 
                     } else {
-                        System.Console.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧");
+                        Utlis.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧");
                     }
                 } else {
                     var mGatewayRes = infoResult.PageData.Find ((obj) => obj.GatewayUniqueId == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId);
@@ -488,12 +540,28 @@
 
            
         }
-
+        /// <summary>
+        /// 鏄惁闇�瑕佽鍙栦竴娆℃墍鏈夎澶囩姸鎬�
+        /// </summary>
+        static bool IfNeedReadAllDeviceStatus = true;
         /// <summary>
         /// 鏀跺埌缃戝叧涓婄嚎娑堟伅
         /// </summary>
         static async Task ReceiveNotifyBusGateWayInfoChange ()
         {
+            Utlis.WriteLine ("============>Mqtt 缃戝叧涓婄嚎");
+            SetGatewayOnlineResetCheck ();
+            if (CommonPage.IsRemote) {
+
+//#if DEBUG
+                MainPage.AddTip ("Gateway login online");
+//#endif
+                if (IfNeedReadAllDeviceStatus) {
+                    IfNeedReadAllDeviceStatus = false;
+                    Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
+                }
+            }
+
             //褰撳墠浣忓畢涓嶆槸鍒嗕韩鏉�
             if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
 
@@ -513,13 +581,146 @@
             }
 
         }
+        /// <summary>
+        /// 鏀跺埌缃戝叧鎺夌嚎淇℃伅
+        /// </summary>
+        static void ReceiveNotifyGateWayOffline ()
+        {
+            Utlis.WriteLine ("============>Mqtt GateWayOffline");
+            IsGatewayOnline = false;
+            if (CommonPage.IsRemote) {
+                Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
+                MainPage.AddTip ("Remote failed,gateway offline");
+                //if (MainPage.WiFiStatus != "CrabtreeAdd/CloudUnlink.png") {
+                //    Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
+                //}
+
+            }
+        }
+
+      
+        static int CheckGatewayCount = 0;
+        static DateTime mCheckGatewayTime;
+
+        /// <summary>
+        /// 璁剧疆缃戝叧鍦ㄧ嚎鏍囧織锛屽苟閲嶇疆CheckGateway鍙傛暟
+        /// </summary>
+        static void SetGatewayOnlineResetCheck ()
+        {
+            IsGatewayOnline = true;
+            mCheckGatewayTime = DateTime.Now;
+            CheckGatewayCount = 0;
+            if (CommonPage.IsRemote) {
+                if (MainPage.WiFiStatus != "CrabtreeAdd/CloudLink.png") {
+                    Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
+                }
+            }
+        }
+
+        //static void TipGatewayOffline () {
+
+        //}
+
+        /// <summary>
+        /// 瀹氭椂妫�娴嬬綉鍏虫槸鍚﹀湪绾�
+        /// 1.绾跨▼浼戠湢闂撮殧5s
+        /// 2.鍙戦�丆heckGateway闂撮殧涓�9S锛屾敹鍒颁富棰樺埛鏂拌鏃堕棿锛岄噸缃彂閫佹鏁�
+        /// 3.鍙戦�佹鏁板埌杈�3娆′互涓婏紝鍒欏垽瀹氱綉鍏充负绂荤嚎鐘舵��
+        /// </summary>
+        /// <returns></returns>
+        static void InitCheckGateway ()
+        {
+            new System.Threading.Thread (async () => {
+                while (true) {
+                    try {
+
+                        if (CommonPage.IsRemote && remoteIsConnected) {
+                            if (CheckGatewayCount >= 3) {
+                                //杩炵画3娆℃病鍥炲锛屽垽瀹氱綉鍏宠秴鏃�
+                                if (MainPage.WiFiStatus == "CrabtreeAdd/CloudLink.png") {
+                                    IsGatewayOnline = false;
+                                    Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
+                                    MainPage.AddTip ("Gateway offline!");
+                                }
+                            }
+
+                            if (mCheckGatewayTime.AddSeconds (10).Ticks <= System.DateTime.Now.Ticks) {
+                                mCheckGatewayTime = DateTime.Now;
+                                //CheckGateway
+                                MqttRemoteSend (new byte [] { }, 3);
+                                CheckGatewayCount++;
+#if DEBUG
+                                Utlis.WriteLine ("CheckGateway");
+#endif
+
+
+                            }
+                        }
+
+                        System.Threading.Thread.Sleep (5500);
+                    } catch { }
+
+                }
+            }) { IsBackground = true }.Start ();
+        }
+
+       
+        /// <summary>
+        /// 鏀跺埌CheckGateway涓婚
+        /// </summary>
+        static void ReceiveCheckGatewayTopic () {
+            //Utlis.WriteLine ("============>Mqtt CheckGateway缃戝叧鍥炲");
+            SetGatewayOnlineResetCheck ();
+          
+
+
+            //鏃х綉鍏虫柟娉�
+            //MainPage.WiFiStatus = "CrabtreeAdd/CloudUnlink.png";
+            //// = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
+            //var ss = CommonPage.MyEncodingUTF8.GetString (aesDecryptPayload);
+            //var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack> (ss);
+            //if (obj == null) {
+            //    return;
+            //}
+            //switch (obj.StateCode) {
+            //case "HDLUdpDataForwardServerMqttClientNoOnLine":
+            //case "NoOnline":
+            //case "NetworkAnomaly"://涓嶅湪绾�
+            //    MainPage.AddTip ("Gateway offline");
+            //    //Application.RunOnMainThread (() => {
+            //    //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
+            //    //});
+            //    break;
+            //case "NoRecord"://MAC涓嶆纭�
+            //    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.MACError));
+            //    //Application.RunOnMainThread (() => {
+            //    //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
+            //    //});
+            //    break;
+            //case "Success":
+            //    MainPage.AddTip (UserConfig.Instance.CurrentRegion.Name + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+            //    MainPage.WiFiStatus = "CrabtreeAdd/CloudLink.png";
+            //    break;
+            //default:
+            //    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkLoser));
+            //    //Application.RunOnMainThread (() => {
+            //    //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
+            //    //});
+            //    break;
+            //}
+            //Application.RunOnMainThread (() => {
+            //    UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
+            //});
+        }
+        
+
 
         /// <summary>
         /// 鏀跺埌鎸や笅绾挎帹閫�
         /// </summary>
         static async Task ReceiveNotifySqueezeAsync (byte [] mes)
         {
-            Console.WriteLine ($"============>MqttNotifySqueeze: {ErrorCode.LoginInAnotherDevice}");
+            Utlis.WriteLine ($"============>MqttNotifySqueeze: {ErrorCode.LoginInAnotherDevice}");
             var mMes = CommonPage.MyEncodingUTF8.GetString (mes);
             if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
 
@@ -540,6 +741,7 @@
             MainPage.ShowAlertOnMainThread (ErrorCode.LoginInAnotherDevice);
 
             Application.RunOnMainThread (() => {
+               
                 MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
                 UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
                 new AccountLogin ().Show ();
@@ -796,7 +998,7 @@
                     RemoteMqttClient = null;
                 }
                 CommonPage.IsRemote = false;
-                Console.WriteLine ("Close Mqtt!!!");
+                Utlis.WriteLine ("Close Mqtt!!!");
             } catch { }
         }
 
@@ -886,7 +1088,7 @@
                                         webPush.DeleteToken_Push (UserConfig.Instance.tokenID);
                                     });
                                 } catch (Exception ex) {
-                                    Console.WriteLine (ex.Message);
+                                    Utlis.WriteLine (ex.Message);
                                 } finally {
                                     Application.RunOnMainThread (() => {
                                         Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.LinkStatusTipColor;
@@ -952,7 +1154,7 @@
                         });
 
                         RemoteMqttClient.UseDisconnectedHandler (e => {
-                            //Console.WriteLine ("RemoteMqttClient UseDisconnectedHandler");
+                            //Utlis.WriteLine ("RemoteMqttClient UseDisconnectedHandler");
                             if (thisShowTip) {
                                 if (CommonPage.IsRemote) {
                                     //MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteConnectionDisconnected));
@@ -966,7 +1168,7 @@
                             }
                         });
                         RemoteMqttClient.UseConnectedHandler (async e => {
-                            //Console.WriteLine ("RemoteMqttClient IsRemote");
+                            //Utlis.WriteLine ("RemoteMqttClient IsRemote");
                             await MqttCheckGateway ();
                         });
                     }
@@ -979,14 +1181,14 @@
                             MainPage.Loading.Hide ();
                             Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
                         });
-                        System.Console.WriteLine ($"閲嶆柊杩炴帴杩滅▼閫氳澶辫触锛屽洜涓鸿幏鍙栨柊鐨凨EY澶辫触");
+                        Utlis.WriteLine ($"閲嶆柊杩炴帴杩滅▼閫氳澶辫触锛屽洜涓鸿幏鍙栨柊鐨凨EY澶辫触");
                         return;
                     }
                     //var messgae = System.Text.Encoding.UTF8.GetString (tempResult);
 
                     var responsePack = tempResult.ResponseData;// Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (messgae);
                     //if (responsePack == null || responsePack ["ResponseData"] == null) {
-                    //    Console.WriteLine ("鏂紑鍚庨噸鏂伴摼鎺ラ渶瑕侀噸鏂扮櫥褰曡幏鍙栬繛鎺ョ殑瀵嗙爜澶辫触");
+                    //    Utlis.WriteLine ("鏂紑鍚庨噸鏂伴摼鎺ラ渶瑕侀噸鏂扮櫥褰曡幏鍙栬繛鎺ョ殑瀵嗙爜澶辫触");
                     //    return;
                     //}
                     var dictrionaryResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (tempResult.ResponseData.ToString ());
@@ -1014,7 +1216,7 @@
                     await Close ();
                     await RemoteMqttClient.ConnectAsync (options);
                 } catch (Exception ex) {
-                    System.Console.WriteLine ("============>" + ex.Message);
+                    Utlis.WriteLine ("============>" + ex.Message);
                     Application.RunOnMainThread (() => {
                         MainPage.Loading.Hide ();
                         isConnecting = false.ToString ();
@@ -1108,7 +1310,7 @@
                     return;
                 }
                 var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/CheckGateway/" + UserConfig.Instance.GatewayMAC.Replace (".", "");
-                Console.WriteLine ("MqttCheckGateway : " + topicName);
+                Utlis.WriteLine ("MqttCheckGateway : " + topicName);
                 //base64鍔犲瘑涓婚
                 var topicNameBase64 = Shared.Securitys.EncryptionService.AesEncryptTopic (topicName, mqttEncryptKey);
 

--
Gitblit v1.8.0