From 5a5a2b696866f947b6025d26c3302e8ffef46435 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期一, 11 一月 2021 16:11:20 +0800
Subject: [PATCH] 2021-01-11 1.更新MQTT连接和本地搜索网关方法。2.子账号相关接口完善

---
 Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideSettingGateway.cs | 1081 ++++++++++++++++++++++++++++++++++++++++++++++----------
 1 files changed, 884 insertions(+), 197 deletions(-)

diff --git a/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideSettingGateway.cs b/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideSettingGateway.cs
index 27797e3..2f278d8 100644
--- a/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideSettingGateway.cs
+++ b/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideSettingGateway.cs
@@ -6,6 +6,9 @@
 {
     public class GuideSettingGateway : FrameLayout
     {
+       
+        static byte TYPEStandardMQTT = 5;
+        static byte TYPEHdlMQTT = 4;
         static GuideSettingGateway curView;
         static GatewayBase gatewayDeicve;
         static VerticalScrolViewLayout bodyView;
@@ -13,7 +16,8 @@
         static Loading myLoading;
         bool isReBind = false;
         static List<Common> addedCommon;
-        public GuideSettingGateway(GatewayBase gd)
+        static bool needRefresh;
+        public GuideSettingGateway (GatewayBase gd)
         {
             gatewayDeicve = gd as GatewayBase;
             addedCommon = new List<Common> ();
@@ -21,17 +25,26 @@
             curView = this;
             myLoading = new Loading ();
 
-//#if __IOS__
-            myLoading.LodingBackgroundColor = 0x00999999;
-//#else
-//            myLoading.LodingBackgroundColor = SkinStyle.Current.ViewColor;
-//#endif
+            myLoading.TextColor = 0xFFA9A9A9;
+            myLoading.LodingBackgroundColor = SkinStyle.Current.MainColor;
+
+            //#if __IOS__
+            //myLoading.LodingBackgroundColor = 0x20999999;
+            //#else
+            //            myLoading.LodingBackgroundColor = SkinStyle.Current.ViewColor;
+            //#endif
             btnCloseLoading = new Button ();
             btnCloseLoading.MouseUpEventHandler += (sender, e) => {
-                Application.RunOnMainThread(()=>{
+                Application.RunOnMainThread (() => {
                     myLoading.Hide ();
                     btnCloseLoading.RemoveFromParent ();
                     WirelessConfig (new byte [] { 1 });//close
+                    //2020-07-02 鍏抽棴鑷姩鎼滅储绾跨▼
+                    StopSearchDeviceThead ();
+                    if (needRefresh) {
+                        needRefresh = false;
+                        SearchDeviceList ();
+                    }
                 });
             };
 
@@ -42,6 +55,7 @@
             curView = null;
             addedCommon.Clear ();
             BackgroundColor = SkinStyle.Current.MainColor;
+            //StopSearchDeviceThead ();
             base.RemoveFromParent ();
         }
 
@@ -86,10 +100,10 @@
             };
 
             var btnSearch = new Button () {
-                Width = Application.GetRealWidth (75),
-                Height = Application.GetRealHeight (75),
+                Width = Application.GetMinRealAverage (75),
+                Height = Application.GetMinRealAverage (75),
                 X = Application.GetRealWidth (520),
-                Y = Application.GetRealHeight(10),
+                Y = Application.GetRealHeight (10),
                 UnSelectedImagePath = "Item/Refresh.png",
             };
             topView.AddChidren (btnSearch);
@@ -98,19 +112,19 @@
                 addedCommon.Clear ();
                 SearchDeviceList ();
             };
-#endregion
+            #endregion
 
-            bodyView = new VerticalScrolViewLayout () { 
+            bodyView = new VerticalScrolViewLayout () {
                 Y = topView.Bottom,
-                Height = Application.GetRealHeight(1136- 126 - 95),
+                Height = Application.GetRealHeight (1136 - 126 - 95),
                 BackgroundColor = SkinStyle.Current.ViewColor,
             };
             AddChidren (bodyView);
 
-            var bottomView = new FrameLayout () { 
+            var bottomView = new FrameLayout () {
                 BackgroundColor = SkinStyle.Current.Black50Transparent,
                 Y = bodyView.Bottom,
-                Height = Application.GetRealHeight(100),
+                Height = Application.GetRealHeight (100),
             };
             AddChidren (bottomView);
 
@@ -125,167 +139,31 @@
             bottomView.AddChidren (btnAssignRoom);
             btnAssignRoom.MouseUpEventHandler += (sender, e) => {
                 //bodyView.RemoveAll ();
-                RemoteSetting ();
+
+                btnAssignRoomAction ();
             };
             SearchDeviceList ();
         }
 
         /// <summary>
-        /// 杩滅▼閰嶇疆
+        /// 鍒ゆ柇璁惧绫诲瀷 鍏煎鏃ц澶�
         /// </summary>
-        void RemoteSetting ()
+        void btnAssignRoomAction ()
         {
-            byte [] gatewayBytes = null;
-            byte [] serverIPBytes = null;
+            if (gatewayDeicve.Type == DeviceType.OnePortMqttFR) {
 
-            string [] strServerIP = (MainPage.SeviceIP).Split ('.');
-            string [] strServerIP1 = (MainPage.SeviceIP).Split ('.');
-            MainPage.Loading.Start ("Configuring device...");
-            System.Threading.Tasks.Task.Run (() => {
-                try {
-                    var currentRegionIdBytes = new byte [] {
-                        (byte)(UserConfig.Instance.CurrentRegion.RegionID / 256 / 256 / 256),
-                        (byte)(UserConfig.Instance.CurrentRegion.RegionID / 256 / 256),
-                        (byte)(UserConfig.Instance.CurrentRegion.RegionID / 256),
-                        (byte)(UserConfig.Instance.CurrentRegion.RegionID%256),
-                    };
-
-                    gatewayBytes = Control.ControlBytesSendHasReturn (Command.ReadGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
-                    serverIPBytes = Control.ControlBytesSendHasReturn (Command.ReadGatewayServerIP, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
-
-                    gatewayDeicve.Remote_GroupName = MainPage.LoginUser.AccountString;//UserConfig.Instance.CurrentRegion.RegionName;
-                    gatewayDeicve.Remote_ProjectName = gatewayDeicve.MAC.Replace(".","");//UserConfig.Instance.CurrentRegion.RegionName;
-                    gatewayDeicve.Remote_UserName = "Admin";
-                    gatewayDeicve.Remote_Password = "c" + MainPage.LoginUser.MasterID;
-                    byte [] ggn = new byte [20];
-                    byte [] b1 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_GroupName);
-                    gatewayDeicve.Remote_GroupName = CommonPage.MyEncodingGB2312.GetString (b1);
-                    Array.Copy (b1, 0, ggn, 0, 20 < b1.Length ? 20 : b1.Length);
-
-                    byte [] gpn = new byte [20];
-                    byte [] b2 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_ProjectName);
-                    Array.Copy (b2, 0, gpn, 0, 20 < b2.Length ? 20 : b2.Length);
-
-                    byte [] gun = new byte [8];
-                    byte [] b3 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_UserName);
-                    Array.Copy (b3, 0, gun, 0, 8 < b3.Length ? 8 : b3.Length);
-
-                    byte [] gpw = new byte [8];
-                    byte [] b4 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_Password);
-                    Array.Copy (b4, 0, gpw, 0, 8 < b4.Length ? 8 : b4.Length);
-
-
-                    byte [] macAddress = Control.ControlBytesSendHasReturn (Command.ReadDeviceMac, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
-                        
-                    gatewayBytes [0] = 2;//杩滅▼鏍囩ず
-                    Array.Copy (ggn, 0, gatewayBytes, 1, 20 < ggn.Length ? 20 : ggn.Length);
-                    Array.Copy (gpn, 0, gatewayBytes, 21, 20 < gpn.Length ? 20 : gpn.Length);
-                    Array.Copy (gun, 0, gatewayBytes, 41, 8 < gun.Length ? 8 : gun.Length);
-                    Array.Copy (gpw, 0, gatewayBytes, 49, 8 < gpw.Length ? 8 : gpw.Length);
-
-                    Control.ControlBytesSend (Command.SetGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, gatewayBytes);
-
-                    serverIPBytes [0] = Convert.ToByte (strServerIP [0]);
-                    serverIPBytes [1] = Convert.ToByte (strServerIP [1]);
-                    serverIPBytes [2] = Convert.ToByte (strServerIP [2]);
-                    serverIPBytes [3] = Convert.ToByte (strServerIP [3]);
-                    int point1 = 9999;
-
-                    serverIPBytes [4] = Convert.ToByte (point1 / 256);
-                    serverIPBytes [5] = Convert.ToByte (point1 % 256);
-
-                    serverIPBytes [6] = Convert.ToByte (strServerIP1 [0]);
-                    serverIPBytes [7] = Convert.ToByte (strServerIP1 [1]);
-                    serverIPBytes [8] = Convert.ToByte (strServerIP1 [2]);
-                    serverIPBytes [9] = Convert.ToByte (strServerIP1 [3]);
-                    int point2 = 9999;
-
-                    serverIPBytes [10] = Convert.ToByte (point2 / 256);
-                    serverIPBytes [11] = Convert.ToByte (point2 % 256);
-
-                    //杩滅▼ip鍦板潃鐨勮缃�
-                    var mobytes = Control.ControlBytesSendHasReturn (Command.SetGateWayModelInternetInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, serverIPBytes);
-                    if (mobytes == null) {
-                        Application.RunOnMainThread (() => {
-                            new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline),
-                                       Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                        });
-                    } else if (mobytes [0] == 0xF5) {
-                        Application.RunOnMainThread (() => {
-                            new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed),
-                                       Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                        });
-                    } else {
-                        if (gatewayDeicve.Type == DeviceType.OnePortWirelessFR) {
-                            var bindReginIdStatus = Control.ControlBytesSendHasReturn (Command.Write_APP_Data_STORE_1D5E_CMD, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, currentRegionIdBytes);
-                            if (bindReginIdStatus == null) {
-                                Application.RunOnMainThread (() => {
-                                    new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                });
-                                return;
-                            } else if (bindReginIdStatus [0] != 0xF8) {
-                                //new Alert ("", "缃戝叧缁戝畾浣忓畢澶辫触锛�", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                Application.RunOnMainThread (() => {
-                                    new Alert ("", "Gateway failed to bind residence!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                });
-                                return;
-                            }
-                        }
-                        Application.RunOnMainThread (() => {
-                            MainPage.Loading.Start ("Gateway setting succeeded锛宒ata up.Please wait...");
-                        });
-                        IO.FileUtils.SaveEquipmentMessage (gatewayDeicve);
-                        var gatewayMAC = gatewayDeicve.MAC.Replace (".", "");
-                        var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (new EditMACByHomeId { RegionID = UserConfig.Instance.CurrentRegion.RegionID, MAC = gatewayMAC, IsReBind = true });
-                        var respone = MainPage.RequestHttps ("EditMACByHomeId", requestJson);
-                        if (respone.StateCode != "SUCCESS") {
-                            Application.RunOnMainThread (() => {
-                                new Alert ("", "Communication abnormality,gateway failed to bind residence!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
-                                    new Alert (respone.StateCode, respone.ErrorInfo, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                }
-                            });
-                            return;
-                        }
-                        var gatewayListObj = new GatewayListObj ();
-                        var gatewayListJson = Newtonsoft.Json.JsonConvert.SerializeObject (gatewayListObj);
-                        var gatewayListRevertObj = MainPage.RequestHttps ("GatewayList", gatewayListJson);
-                        if (gatewayListRevertObj.StateCode == "SUCCESS") {
-                            var responseGatewayDataObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GatewayRes>> (gatewayListRevertObj.ResponseData.ToString ());
-                            if (responseGatewayDataObj.Count > 0) {
-                                UserConfig.Instance.GatewayList.Clear ();
-                                UserConfig.Instance.GatewayList.AddRange (responseGatewayDataObj);
-                                UserConfig.Instance.GatewayMAC = gatewayDeicve.MAC;
-                                UserConfig.Instance.SaveUserConfig ();
-                                MainPage.LoginUser.LastTime = DateTime.Now;
-                                Application.RunOnMainThread (() => {
-                                    UserMiddle.Init (true);
-                                });
-                            } else {
-                                Application.RunOnMainThread (() => {
-                                    new Alert ("", "Communication abnormality,gateway failed to bind residence.Please try again.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                    if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
-                                        new Alert ("22:"+respone.StateCode, respone.ErrorInfo, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                    }
-                                });
-                            }
-                        }
-                    }
-                } catch (Exception ex) {
-                    Console.WriteLine (ex.Message);
-                    Application.RunOnMainThread (() => {
-                        new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                    });
-                    bool canRemove = false;
-                } finally {
-                    Application.RunOnMainThread (() => {
-                        MainPage.Loading.Hide ();
-                        //this.RemoveAll ();
-                    });
-                }
-            });
-            //Room.InitAllRoom ();
+                Utlis.WriteLine ("Assign OnePortMqttFR锛孒DL MQTT");
+                //RemoteSetting ();
+                RemoteSettingWithHDLMQTT ();
+            } else {
+                Utlis.WriteLine ("Assign OnePortWirelessFR");
+                RemoteSettingWithOldDevice ();
+                //RemoteSettingWithMQTT ();
+            }
         }
+
+
+
 
         /// <summary>
         /// 寮�鍏虫棤绾块厤缃�
@@ -323,7 +201,7 @@
                     if (common.Type == DeviceType.MusicModel)
                         continue;
                     if (common.isMixBox) {
-                        Console.WriteLine ("IsMixBox");
+                        Utlis.WriteLine ("IsMixBox");
                         continue;
                     }
                     countDevcie++;
@@ -343,7 +221,7 @@
                         if (common == null)
                             continue;
                         Application.RunOnMainThread (() => {
-                            if(!common.isMixBox){
+                            if (!common.isMixBox) {
                                 progress++;
                             }
                             MainPage.Loading.Start ("Loading:" + common.Name + " 锛孭rogress " + progress.ToString () + "/" + CommonPage.searchTotal.ToString ());
@@ -357,7 +235,7 @@
                             }
                             if (Control.ControlBytesSendHasReturn (Command.ReadDeviceLoopInfo, common.SubnetID, common.DeviceID, new byte [] { bigClass, minClass, (byte)k }) == null) {
                                 j++;
-                                //杩炵画涓ゆ璇诲彇涓嶅埌鏁版嵁鍒欒烦鍑鸿寰幆
+                                //杩炵画涓ゆ璇诲彇涓嶅埌鏁版嵁鍒欒烦鍑鸿寰幆锛屼唬琛ㄨ澶囩绾�2020-01-11
                                 if (j == 2 && k == 2)
                                     break;
                             } else {
@@ -368,15 +246,20 @@
                     th = null;
                     Application.RunOnMainThread (() => {
                         MainPage.Loading.Hide ();
-                        if (gatewayDeicve.Type == DeviceType.OnePortWirelessFR) {
+                        if (gatewayDeicve.Type == DeviceType.OnePortWirelessFR || gatewayDeicve.Type == DeviceType.OnePortMqttFR) {
                             Control.ControlBytesSend (Command.GotoConfigMode, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
                             //new Alert ("", "缃戝叧宸茬粡杩涘叆閰嶉妯″紡锛岃鎵嬪姩鏂拌澶囪繘鍏ラ厤棰戞ā寮忋��", "Close").Show ();
-                            new Alert ("", "Searching for new devices, Please make sure all new devices are in configuration mode.", "OK").Show ();
+                            new Alert ("", ErrorCode.SearchingForNewDevices, "OK").Show ();
 
                             this.AddChidren (myLoading);
                             //myLoading.Start ("鐐瑰嚮灞忓箷鍏抽棴閰嶉妯″紡");
-                            myLoading.Start ("Searching, Please touch the here to exit the searching mode.");
+                            myLoading.Start (ErrorCode.SearchingExitTheSearchingMode);
+                            //myLoading.Start ("Waiting for new device, Please touch the here to exit the waiting mode.");
+                            
                             this.AddChidren (btnCloseLoading);
+
+                            //2020-07-02 缃戝叧閰嶉妯″紡鏃讹紝寮�鍚嚜鍔ㄦ悳绱㈢嚎绋�
+                            StartSearchDeviceThead ();
                         }
                     });
                 });
@@ -390,7 +273,7 @@
             if (curView == null || addedCommon == null)
                 return;
             lock (addedCommon) {
-                if (addedCommon.Find ((obj)=>obj.Type == common.Type&& obj.CommonLoopID == common.CommonLoopID)!=null)
+                if (addedCommon.Find ((obj) => obj.Type == common.Type && obj.CommonLoopID == common.CommonLoopID) != null)
                     return;
                 addedCommon.Add (common);
                 if (common.SubnetID == gatewayDeicve.SubnetID) {
@@ -559,7 +442,7 @@
                         Alert alert = new Alert ("", Language.StringByID (R.MyInternationalizationString.TipDeleteEquipmentMessage)
                                         , Language.StringByID (R.MyInternationalizationString.Cancel), Language.StringByID (R.MyInternationalizationString.Confrim));
                         alert.Show ();
-                        alert.ResultEventHandler += ( sender1,  e1) => {
+                        alert.ResultEventHandler += (sender1, e1) => {
                             if (e1) {
                                 MainPage.Loading.Start ("Please wait...");
                                 System.Threading.Tasks.Task.Run (() => {
@@ -589,7 +472,7 @@
                                             btnDelDevice.Parent.RemoveFromParent ();
                                         });
                                     } catch (Exception ex) {
-                                        Console.WriteLine (ex.Message);
+                                        Utlis.WriteLine (ex.Message);
                                     } finally {
                                         Application.RunOnMainThread (() => {
                                             MainPage.Loading.Hide ();
@@ -612,23 +495,24 @@
                     //}
 
                     if (config) {
-                        System.Threading.Tasks.Task.Factory.StartNew (() => {
-                            try {
-                                byte bigClass = common.BigClass;
-                                byte minClass = common.MinClass;
-                                int count = common.LoopCount;
-                                for (int k = 1, j = 0; k <= count; k++) {
-                                    if (Control.ControlBytesSendHasReturn (Command.ReadDeviceLoopInfo, common.SubnetID, common.DeviceID, new byte [] { bigClass, minClass, (byte)k }) == null) {
-                                        j++;
-                                        //杩炵画涓ゆ璇诲彇涓嶅埌鏁版嵁鍒欒烦鍑鸿寰幆
-                                        if (j == 2 && k == 2)
-                                            break;
-                                    }
-                                }
-                            } catch (Exception ex) {
-                                Console.WriteLine ("Cinfig Read Device Loop Info " + ex.Message);
-                            }
-                        });
+                        needRefresh = true;
+                        //System.Threading.Tasks.Task.Factory.StartNew (() => {
+                        //    try {
+                        //        byte bigClass = common.BigClass;
+                        //        byte minClass = common.MinClass;
+                        //        int count = common.LoopCount;
+                        //        for (int k = 1, j = 0; k <= count; k++) {
+                        //            if (Control.ControlBytesSendHasReturn (Command.ReadDeviceLoopInfo, common.SubnetID, common.DeviceID, new byte [] { bigClass, minClass, (byte)k }) == null) {
+                        //                j++;
+                        //                //杩炵画涓ゆ璇诲彇涓嶅埌鏁版嵁鍒欒烦鍑鸿寰幆
+                        //                if (j == 2 && k == 2)
+                        //                    break;
+                        //            }
+                        //        }
+                        //    } catch (Exception ex) {
+                        //        Utlis.WriteLine ("Cinfig Read Device Loop Info " + ex.Message);
+                        //    }
+                        //});
                     }
 
                     #endregion
@@ -648,12 +532,17 @@
                     //杩欓噷鎼滅储璁惧锛岀洿鍒板畬鎴愬氨閫�鍑�
                     readDevice ();
                 } catch (Exception ex) {
-                    Console.WriteLine (ex.Message);
+                    Utlis.WriteLine (ex.Message);
                 }
                 Application.RunOnMainThread (action);
             }) { IsBackground = true }.Start ();
         }
 
+        ///// <summary>
+        ///// 2020-02-11
+        ///// 鎼滅储閲嶅娆℃暟 鐢�4娆″鍔犱负6娆�
+        ///// </summary>
+        //static readonly int READ_COUNT = 6;
         /// <summary>
         /// 璇诲彇璁惧
         /// </summary>
@@ -667,7 +556,8 @@
             CommonPage.DeviceList.Clear ();
             CommonPage.searchTotal = 0;
             //濡傛灉涓ゆ閮芥病鏈夋暟鎹弽棣堬紝灏变笉璇诲彇
-            int readCount = 4;
+            //2020 - 02 - 11鎼滅储閲嶅娆℃暟 鐢�4娆″鍔犱负6娆�
+            int readCount = 6;
             while (0 < readCount) {
                 readCount--;
                 var ms = new System.IO.MemoryStream ();
@@ -687,7 +577,7 @@
                     ms.WriteByte (common.SubnetID);
                     ms.WriteByte (common.DeviceID);
                 }
-                Console.WriteLine ("鎼滅储闈炵綉鍏宠澶囷紝缃戠粶鍦板潃鏄�:" + CommonPage.EndPoint.ToString ());
+                Utlis.WriteLine ("鎼滅储闈炵綉鍏宠澶囷紝缃戠粶鍦板潃鏄�:" + CommonPage.EndPoint.ToString ());
                 var control = new Control ();
                 control.Send (new Target () {
                     IPEndPoint = CommonPage.EndPoint,
@@ -702,7 +592,7 @@
                 System.Threading.Thread.Sleep (1000);
                 //濡傛灉鏁伴噺涓嶇浉绛夛紝灏遍噸缃鏁�
                 if (tempCount != CommonPage.DeviceList.Count) {
-                    readCount = 4;
+                    readCount = 6;
                 }
             }
             CommonPage.DeviceList = CommonPage.DeviceList.FindAll ((obj) => { return obj != null && obj.SubnetID == gatewayDeicve.SubnetID; });
@@ -710,5 +600,802 @@
             CommonPage.FindGatewayChilren = false;
         }
 
+
+
+        /// <summary>
+        /// 杩滅▼閰嶇疆
+        /// </summary>
+        void RemoteSettingWithOldDevice ()
+        {
+            byte [] gatewayBytes = null;
+            byte [] serverIPBytes = null;
+
+            string [] strServerIP = (MainPage.SeviceIP).Split ('.');
+            string [] strServerIP1 = (MainPage.SeviceIP).Split ('.');
+            MainPage.Loading.Start ("Configuring device...");
+            System.Threading.Tasks.Task.Run (() => {
+                try {
+
+                    //var currentRegionIdBytes = new byte [] {
+                    //    (byte)(UserConfig.Instance.CurrentRegion.RegionID / 256 / 256 / 256),
+                    //    (byte)(UserConfig.Instance.CurrentRegion.RegionID / 256 / 256),
+                    //    (byte)(UserConfig.Instance.CurrentRegion.RegionID / 256),
+                    //    (byte)(UserConfig.Instance.CurrentRegion.RegionID % 256),
+                    //};
+
+
+
+
+                    //var currentRegionIdBytes = Utlis.IntToByteArray (UserConfig.Instance.CurrentRegion.RegionID);
+
+                    byte [] RegionIDBytes = CommonPage.MyEncodingGB2312.GetBytes (UserConfig.Instance.CurrentRegion.Id.ToString ());
+                    var currentRegionIdBytes = new byte [4];
+                    Array.Copy (RegionIDBytes, 0, currentRegionIdBytes, 0, 4 < RegionIDBytes.Length ? 4 : RegionIDBytes.Length);
+
+                    gatewayBytes = Control.ControlBytesSendHasReturn (Command.ReadGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
+                    serverIPBytes = Control.ControlBytesSendHasReturn (Command.ReadGatewayServerIP, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
+
+                    gatewayDeicve.Remote_GroupName = MainPage.LoginUser.AccountString;//UserConfig.Instance.CurrentRegion.RegionName;
+                    gatewayDeicve.Remote_ProjectName = gatewayDeicve.MAC.Replace (".", "");//UserConfig.Instance.CurrentRegion.RegionName;
+                    gatewayDeicve.Remote_UserName = "Admin";
+                    gatewayDeicve.Remote_Password = "c" + MainPage.LoginUser.ID;
+                    byte [] ggn = new byte [20];
+                    byte [] b1 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_GroupName);
+                    gatewayDeicve.Remote_GroupName = CommonPage.MyEncodingGB2312.GetString (b1);
+                    Array.Copy (b1, 0, ggn, 0, 20 < b1.Length ? 20 : b1.Length);
+
+                    byte [] gpn = new byte [20];
+                    byte [] b2 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_ProjectName);
+                    Array.Copy (b2, 0, gpn, 0, 20 < b2.Length ? 20 : b2.Length);
+
+                    byte [] gun = new byte [8];
+                    byte [] b3 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_UserName);
+                    Array.Copy (b3, 0, gun, 0, 8 < b3.Length ? 8 : b3.Length);
+
+                    byte [] gpw = new byte [8];
+                    byte [] b4 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_Password);
+                    Array.Copy (b4, 0, gpw, 0, 8 < b4.Length ? 8 : b4.Length);
+
+
+                    byte [] macAddress = Control.ControlBytesSendHasReturn (Command.ReadDeviceMac, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
+
+                    gatewayBytes [0] = 2;//杩滅▼鏍囩ず
+                    Array.Copy (ggn, 0, gatewayBytes, 1, 20 < ggn.Length ? 20 : ggn.Length);
+                    Array.Copy (gpn, 0, gatewayBytes, 21, 20 < gpn.Length ? 20 : gpn.Length);
+                    Array.Copy (gun, 0, gatewayBytes, 41, 8 < gun.Length ? 8 : gun.Length);
+                    Array.Copy (gpw, 0, gatewayBytes, 49, 8 < gpw.Length ? 8 : gpw.Length);
+
+                    Control.ControlBytesSend (Command.SetGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, gatewayBytes);
+
+                    serverIPBytes [0] = Convert.ToByte (strServerIP [0]);
+                    serverIPBytes [1] = Convert.ToByte (strServerIP [1]);
+                    serverIPBytes [2] = Convert.ToByte (strServerIP [2]);
+                    serverIPBytes [3] = Convert.ToByte (strServerIP [3]);
+                    int point1 = 9999;
+
+                    serverIPBytes [4] = Convert.ToByte (point1 / 256);
+                    serverIPBytes [5] = Convert.ToByte (point1 % 256);
+
+                    serverIPBytes [6] = Convert.ToByte (strServerIP1 [0]);
+                    serverIPBytes [7] = Convert.ToByte (strServerIP1 [1]);
+                    serverIPBytes [8] = Convert.ToByte (strServerIP1 [2]);
+                    serverIPBytes [9] = Convert.ToByte (strServerIP1 [3]);
+                    int point2 = 9999;
+
+                    serverIPBytes [10] = Convert.ToByte (point2 / 256);
+                    serverIPBytes [11] = Convert.ToByte (point2 % 256);
+
+                    //杩滅▼ip鍦板潃鐨勮缃�
+                    var mobytes = Control.ControlBytesSendHasReturn (Command.SetGateWayModelInternetInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, serverIPBytes);
+                    if (mobytes == null) {
+                        Application.RunOnMainThread (() => {
+                            new Alert ("", ErrorCode.GatewayNoResponse,
+                                       Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                        });
+                    } else if (mobytes [0] == 0xF5) {
+                        Application.RunOnMainThread (() => {
+                            new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed),
+                                       Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                        });
+                    } else {
+                        if (gatewayDeicve.Type == DeviceType.OnePortWirelessFR) {
+                            var bindReginIdStatus = Control.ControlBytesSendHasReturn (Command.Write_APP_Data_STORE_1D5E_CMD, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, currentRegionIdBytes);
+                            if (bindReginIdStatus == null) {
+                                Application.RunOnMainThread (() => {
+                                    new Alert ("", ErrorCode.GatewayNoResponse, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                                });
+                                return;
+                            } else if (bindReginIdStatus [0] != 0xF8) {
+                                //new Alert ("", "缃戝叧缁戝畾浣忓畢澶辫触锛�", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                                Application.RunOnMainThread (() => {
+                                    new Alert ("", "Gateway failed to bind residence!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                                });
+                                return;
+                            }
+                        }
+                        GotoHomePage ();
+                    }
+                } catch (Exception ex) {
+                    Utlis.WriteLine (ex.Message);
+                    Application.RunOnMainThread (() => {
+                        new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                    });
+                    bool canRemove = false;
+                } finally {
+                    Application.RunOnMainThread (() => {
+                        MainPage.Loading.Hide ();
+                        //this.RemoveAll ();
+                    });
+                }
+            });
+            //Room.InitAllRoom ();
+        }
+
+
+
+        /// <summary>
+        /// 杩滅▼閰嶇疆 HDL MQTT妯″紡
+        /// </summary>
+        void RemoteSettingWithHDLMQTT ()
+        {
+            byte [] gatewayBytes = null;
+            string [] strServerIP = (MainPage.SeviceIP).Split ('.');
+            string [] strServerIP1 = (MainPage.SeviceIP).Split ('.');
+            MainPage.Loading.Start ("Configuring gateway...");
+            System.Threading.Tasks.Task.Run (() => {
+                try {
+
+                    ////璇诲彇涓�绔彛浜ゆ崲鏈恒�佹棤绾跨綉鍏崇殑閰嶇疆淇℃伅
+                    //gatewayBytes = Control.ControlBytesSendHasReturn (Command.ReadGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
+                    //if (gatewayBytes == null) {
+                    //    //璇诲彇涓�绔彛浜ゆ崲鏈恒�佹棤绾跨綉鍏崇殑閰嶇疆淇℃伅澶辫触
+                    //    new Alert ("", "Read gateway configuration failed!", "Close").Show ();
+                    //    return;
+                    //}
+                   
+                    //1.淇敼鐢ㄦ埛鍚嶄俊鎭� 鍜屼慨鏀硅繛鎺ユā寮�
+                    if (SetGateWayModelInfo()) {
+                        //2.淇敼绠$悊淇℃伅
+                        if (SetGateWayAdminInfo ()) {
+                            //3.鍐欓厤缃垚鍔熷悗涓嬩竴姝ユ搷浣�
+                            GatewaySettingSucceeded ();
+                        }
+                    }
+
+                } catch (Exception ex) {
+                    Utlis.WriteLine (ex.Message);
+                    Application.RunOnMainThread (() => {
+                        //淇敼缃戝叧杩炴帴妯″紡澶辫触
+                        new Alert ("", "Failed to modify gateway connection mode!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                    });
+                    bool canRemove = false;
+                } finally {
+                    Application.RunOnMainThread (() => {
+                        MainPage.Loading.Hide ();
+                        //this.RemoveAll ();
+                    });
+                }
+            });
+            //Room.InitAllRoom ();
+        }
+
+        bool SetGateWayModelInfo () {
+            byte [] gatewayBytes = new byte [60];
+            gatewayDeicve.Remote_GroupName = MainPage.LoginUser.AccountString;//UserConfig.Instance.CurrentRegion.RegionName;
+            gatewayDeicve.Remote_ProjectName = gatewayDeicve.MAC.Replace (".", "");//UserConfig.Instance.CurrentRegion.RegionName;
+            gatewayDeicve.Remote_UserName = "Admin";
+            gatewayDeicve.Remote_Password = "c" + MainPage.LoginUser.ID;
+            //gatewayDeicve.Remote_Password = "85521566";
+            byte [] ggn = new byte [20];
+            byte [] b1 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_GroupName);
+            gatewayDeicve.Remote_GroupName = CommonPage.MyEncodingGB2312.GetString (b1);
+            Array.Copy (b1, 0, ggn, 0, 20 < b1.Length ? 20 : b1.Length);
+
+            byte [] gpn = new byte [20];
+            byte [] b2 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_ProjectName);
+            Array.Copy (b2, 0, gpn, 0, 20 < b2.Length ? 20 : b2.Length);
+
+            byte [] gun = new byte [8];
+            byte [] b3 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_UserName);
+            Array.Copy (b3, 0, gun, 0, 8 < b3.Length ? 8 : b3.Length);
+
+            byte [] gpw = new byte [8];
+            byte [] b4 = CommonPage.MyEncodingGB2312.GetBytes (gatewayDeicve.Remote_Password);
+            Array.Copy (b4, 0, gpw, 0, 8 < b4.Length ? 8 : b4.Length);
+
+
+            gatewayBytes [0] = TYPEHdlMQTT;//HDL MQTT
+            Array.Copy (ggn, 0, gatewayBytes, 1, 20);
+            Array.Copy (gpn, 0, gatewayBytes, 21, 20);
+            Array.Copy (gun, 0, gatewayBytes, 41, 8);
+            Array.Copy (gpw, 0, gatewayBytes, 49, 8);
+            byte [] backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, gatewayBytes);
+            return CheckIsSuccessfulWithBytes (backBytes, "Failed to modify gateway connection mode.");
+        }
+
+        /// <summary>
+        /// 淇敼绠$悊鍛樹俊鎭�
+        /// </summary>
+        /// <param name="adminBytes"></param>
+        /// <returns></returns>
+        bool SetGateWayAdminInfo (byte [] adminBytes) {
+            byte [] name = CommonPage.MyEncodingGB2312.GetBytes (MainPage.LoginUser.AccountString);
+            byte [] backBytes;
+            if (adminBytes != null && adminBytes.Length >= 73) {//杩斿洖鏁版嵁姝e父,鍙慨鏀硅处鍙蜂俊鎭�
+                Array.Copy (name, 0, adminBytes, 0, 36 < name.Length ? 36 : name.Length);
+                backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayAdminInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, adminBytes);
+
+            } else {
+                byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (UserConfig.Instance.CurrentRegion.Id.ToString ());
+                //byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (UserConfig.Instance.CurrentRegion.RegionID);
+                //var currentRegionIdBytes = Utlis.IntToByteArray (UserConfig.Instance.CurrentRegion.RegionID);
+                adminBytes = new byte [73];
+                adminBytes [36] = 1;//浣忓畢鏍囧織浣�
+                Array.Copy (name, 0, adminBytes, 0, 36 < name.Length ? 36 : name.Length);
+                Array.Copy (currentRegionIdBytes, 0, adminBytes, 37, 36 < currentRegionIdBytes.Length ? 36 : currentRegionIdBytes.Length);
+                backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayAdminInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, adminBytes);
+
+            }
+            return CheckIsSuccessfulWithBytes (backBytes);
+        }
+
+        /// <summary>
+        /// 淇敼绠$悊鍛樹俊鎭�
+        /// </summary>
+        /// <param name="adminBytes"></param>
+        /// <returns></returns>
+        bool SetGateWayAdminInfo ()
+        {
+            byte [] name = CommonPage.MyEncodingGB2312.GetBytes (MainPage.LoginUser.AccountString);
+            //byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (UserConfig.Instance.CurrentRegion.RegionID);
+            byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (UserConfig.Instance.CurrentRegion.Id.ToString ());
+            //var currentRegionIdBytes = Utlis.IntToByteArray (UserConfig.Instance.CurrentRegion.RegionID);
+            byte [] adminBytes = new byte [73];
+            adminBytes [36] = 1;//浣忓畢鏍囧織浣�
+            Array.Copy (name, 0, adminBytes, 0, 36 < name.Length ? 36 : name.Length);
+            Array.Copy (currentRegionIdBytes, 0, adminBytes, 37, 36 < currentRegionIdBytes.Length ? 36 : currentRegionIdBytes.Length);
+
+            byte [] backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayAdminInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, adminBytes);
+
+            return CheckIsSuccessfulWithBytes (backBytes, "Failed to modify gateway administrator information!");
+        }
+
+        /// <summary>
+        /// 鍒ゆ柇鏄惁淇鎴愬姛 F8 = 鎴愬姛锛� F5=澶辫触
+        /// </summary>
+        /// <param name="backBytes"></param>
+        /// <returns></returns>
+        private bool CheckIsSuccessfulWithBytes (byte [] backBytes, string errorStr = "Modify gateway configuration failed!")
+        {
+            if (backBytes == null) {
+                Application.RunOnMainThread (() => {
+                    new Alert ("", ErrorCode.GatewayNoResponse,
+                               Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                });
+                return false;
+            } else if (backBytes [0] == 0xF8) {//F8 = 鎴愬姛锛� F5=澶辫触
+                return true;
+            } else {
+                Application.RunOnMainThread (() => {
+                    new Alert ("", errorStr,
+                               Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                });
+                return false;
+            }
+        }
+
+
+        /// <summary>
+        /// 鍐欓厤缃弬鏁版垚鍔熷悗鎵ц涓嬩竴姝ユ搷浣�
+        /// </summary>
+        void GatewaySettingSucceeded ()
+        {
+
+            if (gatewayDeicve.Type == DeviceType.OnePortMqttFR) {
+                //var currentRegionIdBytes = Utlis.IntToByteArray (UserConfig.Instance.CurrentRegion.RegionID);
+                //byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (UserConfig.Instance.CurrentRegion.RegionID);
+                byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (UserConfig.Instance.CurrentRegion.Id.ToString ());
+                byte [] sendBytes = new byte [36];
+                Array.Copy (currentRegionIdBytes, 0, sendBytes, 0, 36 < currentRegionIdBytes.Length ? 36 : currentRegionIdBytes.Length);
+
+                //var currentRegionIdBytes = Utlis.IntToByteArray (UserConfig.Instance.CurrentRegion.RegionID);
+                var bindReginIdStatus = Control.ControlBytesSendHasReturn (Command.Write_APP_Data_STORE_1D5E_CMD, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, sendBytes);
+                if (bindReginIdStatus == null) {
+                    Application.RunOnMainThread (() => {
+                        new Alert ("", ErrorCode.GatewayNoResponse, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                    });
+                    return;
+                } else if (bindReginIdStatus [0] != 0xF8) {
+                    //new Alert ("", "缃戝叧缁戝畾浣忓畢澶辫触锛�", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                    Application.RunOnMainThread (() => {
+                        new Alert ("", "Gateway failed to bind residence!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                    });
+                    return;
+                }
+            }
+
+            GotoHomePage ();
+
+        }
+
+
+        ///// <summary>
+        ///// Gateway setting succeeded锛宒ata up.Please wait...
+        ///// 缁戝畾Mac(鍗板害鐗�)
+        ///// </summary>
+        //void BindGatewaysNew ()
+        //{
+        //    //Application.RunOnMainThread (() => {
+        //    //    MainPage.Loading.Start ("Gateway setting succeeded锛宒ata up. Please wait...");
+        //    //});
+        //    //IO.FileUtils.SaveEquipmentMessage (gatewayDeicve);
+        //    //var gatewayMAC = gatewayDeicve.MAC.Replace (".", "");
+
+        //    ////璧版柊鏇存柊缁戝畾鎺ュ彛
+        //    //var mBindMacObj = new BindMacObj () {
+        //    //    LoginAccessToken = MainPage.LoginUser.LoginTokenString,
+        //    //    HomeId = UserConfig.Instance.CurrentRegion.Id,
+        //    //    MAC = gatewayMAC
+
+        //    //};
+
+        //    //string urlHead = MainPage.RequestHttpsHost;
+        //    //if (mBindMacObj.IsOtherAccountCtrl) {
+        //    //    urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl;
+        //    //    mBindMacObj.LoginAccessToken = UserConfig.Instance.MasterAccountToken;
+        //    //}
+
+
+        //    //var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (mBindMacObj);
+
+        //    ////var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (new EditMACByHomeId { RegionID = UserConfig.Instance.CurrentRegion.Id, MAC = gatewayMAC, IsReBind = true });
+        //    //var respone = MainPage.RequestHttps (API.BindMac, requestJson, urlHead);
+        //    //if (respone.StateCode.ToUpper () != StateCode.SUCCESS) {
+        //    //    GetNowHomeGatewayAfterBindMacFailed ();//2020-01-11
+        //    //    Application.RunOnMainThread (() => {
+        //    //        new Alert ("", $"Failed to bind Mac address! {ErrorCode.Reason }{respone.StateCode}", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //    //        if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
+        //    //            new Alert (respone.StateCode, respone.ErrorInfo, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //    //        }
+        //    //    });
+        //    //    return;
+        //    //}
+        //    //GetNowHomeGateway ();
+
+        //    var gatewayMAC = gatewayDeicve.MAC.Replace (".", "");
+        //    AddMacToUserConfig (gatewayMAC);
+
+        //}
+
+        /// <summary>
+        /// 璺宠浆涓婚〉闈�
+        /// </summary>
+        void GotoHomePage ()
+        {
+            MainPage.LoginUser.LastTime = DateTime.Now;
+            Application.RunOnMainThread (() => {
+                this.RemoveFromParent ();
+                //MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
+                UserMiddle.Init (true);
+                MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
+                UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
+            });
+        }
+
+
+        ///// <summary>
+        ///// Gateway setting succeeded锛宒ata up.Please wait...
+        ///// </summary>
+        //void BindGateways ()
+        //{
+
+        //    Application.RunOnMainThread (() => {
+        //        MainPage.Loading.Start ("Gateway setting succeeded锛宒ata up.Please wait...");
+        //    });
+        //    IO.FileUtils.SaveEquipmentMessage (gatewayDeicve);
+        //    var gatewayMAC = gatewayDeicve.MAC.Replace (".", "");
+        //    var oldMac = "";
+        //    //2020-01-11 
+        //    if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) {
+        //        //褰撳墠浣忓畢瀛樺湪Mac 淇敼MAC鎺ュ彛
+        //        oldMac = UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId;
+        //        if (oldMac == gatewayMAC) {//鍜岀粦瀹歮ac涓�鑷达紝涓嶇敤淇敼
+        //            AddMacToUserConfig (gatewayMAC);
+        //            return;
+        //        }
+
+        //        var mUpdateMacObj = new UpdateMacObj () {
+        //            LoginAccessToken = MainPage.LoginUser.LoginTokenString,
+        //            HomeId = UserConfig.Instance.CurrentRegion.Id,
+        //            NewMac = gatewayMAC,
+        //            OldMac = oldMac
+        //        };
+        //        string urlHead = MainPage.RequestHttpsHost;
+        //        if (mUpdateMacObj.IsOtherAccountCtrl) {
+        //            urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl;
+        //            mUpdateMacObj.LoginAccessToken = UserConfig.Instance.MasterAccountToken;
+        //        }
+
+        //        var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (mUpdateMacObj);
+
+        //        //var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (new EditMACByHomeId { RegionID = UserConfig.Instance.CurrentRegion.Id, MAC = gatewayMAC, IsReBind = true });
+        //        var respone = MainPage.RequestHttps (API.UpdateMac, requestJson, urlHead);
+        //        if (respone.StateCode.ToUpper () != StateCode.SUCCESS) {
+        //            GetNowHomeGatewayAfterBindMacFailed ();//2020-01-11
+        //            Application.RunOnMainThread (() => {
+        //                new Alert ("", "Failed to update Mac address, gateway binding failed!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //                if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
+        //                    new Alert (respone.StateCode, respone.ErrorInfo, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //                }
+        //            });
+        //            return;
+        //        }
+        //        //GetNowHomeGateway ();
+        //        AddMacToUserConfig (gatewayMAC);
+        //    } else {
+        //        //璧版柊缁戝畾鎺ュ彛
+        //        var mBindMacObj = new BindGatewayToHomeObj () {
+        //            LoginAccessToken = MainPage.LoginUser.LoginTokenString,
+        //            HomeId = UserConfig.Instance.CurrentRegion.Id,
+
+        //        };
+        //        mBindMacObj.BindGateways.Add (gatewayMAC);
+        //        string urlHead = MainPage.RequestHttpsHost;
+        //        if (mBindMacObj.IsOtherAccountCtrl) {
+        //            urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl;
+        //            mBindMacObj.LoginAccessToken = UserConfig.Instance.MasterAccountToken;
+        //        }
+
+
+        //        var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (mBindMacObj);
+
+        //        //var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (new EditMACByHomeId { RegionID = UserConfig.Instance.CurrentRegion.Id, MAC = gatewayMAC, IsReBind = true });
+        //        var respone = MainPage.RequestHttps (API.BindGatewayToHome, requestJson, urlHead);
+        //        if (respone.StateCode.ToUpper () != StateCode.SUCCESS && respone.StateCode != "BindGatewaysExists") {
+        //            GetNowHomeGatewayAfterBindMacFailed ();//2020-01-11
+        //            Application.RunOnMainThread (() => {
+        //                new Alert ("", "Failed to bind Mac address, gateway binding failed!", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //                if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
+        //                    new Alert (respone.StateCode, respone.ErrorInfo, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //                }
+        //            });
+        //            return;
+        //        }
+        //        //GetNowHomeGateway ();
+        //        AddMacToUserConfig (gatewayMAC);
+        //    }
+
+        //}
+
+
+        ///// <summary>
+        ///// 缁戝畾澶辫触涔嬪悗锛屾煡璇㈠埛鏂颁竴娆″綋鍓嶄綇瀹� 缃戝叧鍒楄〃
+        ///// 2020-01-11
+        ///// </summary>
+        //void GetNowHomeGatewayAfterBindMacFailed ()
+        //{
+
+        //    var requestObj3 = new GetSingleHomeGatewayPaggerObj ();
+        //    requestObj3.ReqDto.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
+        //    requestObj3.ReqDto.HomeId = UserConfig.Instance.CurrentRegion.Id;
+        //    requestObj3.ReqDto.PageSetting.Page = 1;
+        //    requestObj3.ReqDto.PageSetting.PageSize = 10;
+        //    string urlHead = MainPage.RequestHttpsHost;
+        //    if (requestObj3.IsOtherAccountCtrl) {
+        //        urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl;
+        //        requestObj3.ReqDto.LoginAccessToken = UserConfig.Instance.MasterAccountToken;
+        //    }
+
+        //    var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3);
+        //    var revertObj3 = MainPage.RequestHttps (API.GetSingleHomeGatewayPagger, requestJson3, urlHead);
+        //    if (revertObj3.StateCode.ToUpper () == StateCode.SUCCESS) {
+        //        var infoResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGatewayResult> (revertObj3.ResponseData.ToString ());
+        //        //2020-01-11
+        //        UserConfig.Instance.SetNowHomeGateways (infoResult.PageData);
+                
+        //    } 
+
+
+        //}
+
+        #region 2020-07-02
+        /// <summary>
+        /// 瀹氭椂鎼滅储璁惧绾跨▼
+        /// </summary>
+        Thread searchDeviceThead;
+        bool bStartSearch;
+
+        /// <summary>
+        /// 2020-07-02
+        /// 缃戝叧閰嶉妯″紡鏃讹紝寮�鍚嚜鍔ㄦ悳绱㈢嚎绋�
+        /// </summary>
+        void StartSearchDeviceThead ()
+        {
+            StopSearchDeviceThead ();
+            CommonPage.LocalPhoneFindDevice = true;
+            CommonPage.FindGatewayChilren = true;
+            CommonPage.RandomHigh = (byte)new Random ().Next (255);
+            CommonPage.RandomLow = (byte)new Random ().Next (255);
+
+            bStartSearch = true;
+            searchDeviceThead = new Thread ((obj) => {
+                while (bStartSearch) {
+                    try {
+                        //瀹氭椂4S
+                        Thread.Sleep (4000);
+
+                        var ms = new System.IO.MemoryStream ();
+                        ms.WriteByte (CommonPage.RandomHigh);
+                        ms.WriteByte (CommonPage.RandomLow);
+
+                        var list = CommonPage.DeviceList;
+                        int tempCount = list.Count;
+                        string s = ";";
+                        for (int i = 0; i < list.Count; i++) {
+                            Common common = list [i];
+                            if (common.SubnetID != gatewayDeicve.SubnetID)
+                                continue;
+                            if (s.Contains (";" + common.SubnetID.ToString () + ":" + common.DeviceID.ToString ()))
+                                continue;
+                            s += common.SubnetID.ToString () + ":" + common.DeviceID.ToString () + ";";
+                            ms.WriteByte (common.SubnetID);
+                            ms.WriteByte (common.DeviceID);
+                        }
+                        Utlis.WriteLine ("SearchDeviceThead鎼滅储闈炵綉鍏宠澶囷紝缃戠粶鍦板潃鏄�:" + CommonPage.EndPoint.ToString ());
+                        var control = new Control ();
+                        control.Send (new Target () {
+                            IPEndPoint = CommonPage.EndPoint,
+                            Command = Command.ReadDeviceModul,
+                            SubnetID = gatewayDeicve.SubnetID,
+                            DeviceID = 0xFF,
+                            AddData = ms.ToArray ()
+                        }, SendCount.Zero, false);
+
+                        ms.Close ();
+                        
+                    } catch {
+
+                    }
+                }
+            });
+            searchDeviceThead.Start ();
+
+
+            Utlis.WriteLine ("----StartSearchDeviceThead----");
+        }
+
+        /// <summary>
+        /// 鏆傚仠鎼滅储璁惧绾跨▼
+        /// </summary>
+        void StopSearchDeviceThead ()
+        {
+            CommonPage.LocalPhoneFindDevice = false;
+            CommonPage.FindGatewayChilren = false;
+            bStartSearch = false;
+            if (searchDeviceThead != null)
+                searchDeviceThead.Abort ();
+
+            Utlis.WriteLine ("----StopSearchDeviceThead----");
+
+        }
+        #endregion
+
+        ///// <summary>
+        ///// 鏌ヨ褰撳墠浣忓畢 缃戝叧鍒楄〃
+        ///// </summary>
+        //void GetNowHomeGateway ()
+        //{
+
+        //    var requestObj3 = new GetSingleHomeGatewayPaggerObj ();
+        //    requestObj3.ReqDto.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
+        //    requestObj3.ReqDto.HomeId = UserConfig.Instance.CurrentRegion.Id;
+        //    requestObj3.ReqDto.PageSetting.Page = 1;
+        //    requestObj3.ReqDto.PageSetting.PageSize = 999;
+        //    string urlHead = MainPage.RequestHttpsHost;
+        //    if (requestObj3.IsOtherAccountCtrl) {
+        //        urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl;
+        //        requestObj3.ReqDto.LoginAccessToken = UserConfig.Instance.MasterAccountToken;
+        //    }
+
+
+        //    //var requestObj3 = new GatewayByRegionListObj () { RegionID = UserConfig.Instance.CurrentRegion.Id };
+        //    var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3);
+        //    var revertObj3 = MainPage.RequestHttps (API.GetSingleHomeGatewayPagger, requestJson3, urlHead);
+        //    if (revertObj3.StateCode.ToUpper () == StateCode.SUCCESS) {
+        //        var infoResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGatewayResult> (revertObj3.ResponseData.ToString ());
+        //        var responseGatewayDataObj = infoResult.PageData;
+        //        if (responseGatewayDataObj != null && responseGatewayDataObj.Count > 0) {
+
+        //            UserConfig.Instance.GatewayList.Clear ();
+        //            UserConfig.Instance.GatewayList.AddRange (responseGatewayDataObj);
+        //            UserConfig.Instance.GatewayMAC = gatewayDeicve.MAC;
+        //            UserConfig.Instance.SaveUserConfig ();
+        //            MainPage.LoginUser.LastTime = DateTime.Now;
+        //            Application.RunOnMainThread (() => {
+        //                bodyView.RemoveAll ();
+        //                UserMiddle.Init (true);
+        //            });
+        //        } else {
+        //            Application.RunOnMainThread (() => {
+        //                new Alert ("", "Query gateway failed, gateway failed to bind residence.Please try again.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //                if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
+        //                    new Alert ("22:" + revertObj3.StateCode, revertObj3.ErrorInfo, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //                }
+        //            });
+        //        }
+        //    } else {
+
+        //        Application.RunOnMainThread (() => {
+        //            new Alert ("", "Query gateway failed, gateway failed to bind residence.Please try again.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //            if (MainPage.LoginUser.AccountString == "464027401@qq.com") {
+        //                new Alert ("22:" + revertObj3.StateCode, revertObj3.ErrorInfo, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //            }
+        //        });
+        //    }
+
+
+        //}
+
+
+
+
+        ///// <summary>
+        ///// 
+        ///// </summary>
+        ///// <param name="stateCodeStr"></param>
+        //void ShowGetAllBindGatewarysPaggerErrorInfo (string stateCodeStr)
+        //{
+        //    string mes = "";
+        //    //2020-01-06 寰呰ˉ鍏�
+        //    if (stateCodeStr == ErrorCode.NetworkError) {
+        //        mes = ErrorCode.NetworkError;
+        //    } else {
+        //        mes = ErrorCode.OperationFailed + ErrorCode.Reason + stateCodeStr;
+
+        //    }
+        //    if (!string.IsNullOrEmpty (mes)) {
+        //        Application.RunOnMainThread (() => {
+        //            new Alert ("", mes, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //        });
+        //    }
+
+
+        //}
+
+        //*****************StandardMQTT 閰嶇疆鏂瑰紡 鐩墠鐢ㄤ笉涓�*****************
+        ///// <summary>
+        ///// 杩滅▼閰嶇疆 Standard MQTT妯″紡
+        ///// </summary>
+        //void RemoteSettingWithStandardMQTT ()
+        //{
+        //    byte [] gatewayBytes = null;
+        //    string [] strServerIP = (MainPage.SeviceIP).Split ('.');
+        //    string [] strServerIP1 = (MainPage.SeviceIP).Split ('.');
+        //    MainPage.Loading.Start ("Configuring device...");
+        //    System.Threading.Tasks.Task.Run (() => {
+        //        try {
+
+        //            //璇诲彇涓�绔彛浜ゆ崲鏈恒�佹棤绾跨綉鍏崇殑閰嶇疆淇℃伅
+        //            gatewayBytes = Control.ControlBytesSendHasReturn (Command.ReadGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, new byte [] { });
+        //            //杩炴帴绫诲瀷閰嶇疆涓�5 Standard MQTT妯″紡
+        //            gatewayBytes [0] = TYPEStandardMQTT;//Standard MQTT
+        //            Control.ControlBytesSend (Command.SetGateWayModelInfo, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, gatewayBytes);
+        //            //1.淇敼URL
+        //            //2.淇敼璇诲彇瀹㈡埛绔疘D锛岀敤鎴峰悕锛屽瘑鐮�
+        //            //3.淇敼AES鍔犲瘑
+        //            //4.淇敼涓婚
+
+        //            //1.淇敼URL
+        //            if (SetGateWayURL ("https://developer.hdlcontrol.com/api/")) {
+        //                //2.淇敼瀹㈡埛绔疘D锛岀敤鎴峰悕锛屽瘑鐮�
+        //                if (SetGateWayClientIDUsernamePassword ("85521566", "Admin", "85521566")) {
+        //                    //3.淇敼AES鍔犲瘑
+        //                    if (SetGateWayAESEncryption (true, "85521566")) {
+        //                        //4.1淇敼璁㈤槄涓婚
+        //                        if (SetGateWayTopic ("SubscribeTopic")) {
+        //                            //4.2淇敼鍙戝竷涓婚
+        //                            if (SetGateWayTopic ("PublishTopic", true)) {
+        //                                //5.鍐欓厤缃垚鍔熷悗涓嬩竴姝ユ搷浣�
+        //                                GatewaySettingSucceeded ();
+        //                            }
+        //                        }
+        //                    }
+        //                }
+        //            }
+
+        //        } catch (Exception ex) {
+        //            Utlis.WriteLine (ex.Message);
+        //            Application.RunOnMainThread (() => {
+        //                new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+        //            });
+        //            bool canRemove = false;
+        //        } finally {
+        //            Application.RunOnMainThread (() => {
+        //                MainPage.Loading.Hide ();
+        //                //this.RemoveAll ();
+        //            });
+        //        }
+        //    });
+        //    //Room.InitAllRoom ();
+        //}
+
+
+
+        ///// <summary>
+        ///// 淇敼URL
+        ///// </summary>
+        ///// <returns></returns>
+        //bool SetGateWayURL (string urlStr = "", int pointID = 1883)
+        //{
+        //    byte [] sendBytes = new byte [63];
+        //    byte [] url = CommonPage.MyEncodingGB2312.GetBytes (urlStr);
+        //    Array.Copy (url, 0, sendBytes, 1, 60 < url.Length ? 60 : url.Length);
+        //    sendBytes [0] = GuideSettingGateway.TYPEStandardMQTT;
+        //    sendBytes [61] = Convert.ToByte (pointID / 256);
+        //    sendBytes [62] = Convert.ToByte (pointID % 256);
+        //    var backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayURL, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, sendBytes);
+
+        //    return CheckIsSuccessfulWithBytes (backBytes);
+        //}
+
+
+        ///// <summary>
+        ///// 淇敼瀹㈡埛绔疘D锛岀敤鎴峰悕锛屽瘑鐮�
+        ///// </summary>
+        ///// <returns></returns>
+        //bool SetGateWayClientIDUsernamePassword (string clientIDStr = "", string usernameStr = "", string passwordStr = "")
+        //{
+
+        //    byte [] userInfoBytes = new byte [64];
+        //    byte [] clientID = CommonPage.MyEncodingGB2312.GetBytes (clientIDStr);
+        //    Array.Copy (clientID, 0, userInfoBytes, 0, 32 < clientID.Length ? 32 : clientID.Length);
+        //    byte [] username = CommonPage.MyEncodingGB2312.GetBytes (usernameStr);
+        //    Array.Copy (username, 0, userInfoBytes, 32, 16 < username.Length ? 16 : username.Length);
+        //    byte [] password = CommonPage.MyEncodingGB2312.GetBytes (passwordStr);
+        //    Array.Copy (password, 0, userInfoBytes, 48, 16 < password.Length ? 16 : password.Length);
+        //    var setUserInfoBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayClientIDUsernamePassword, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, userInfoBytes);
+
+        //    return CheckIsSuccessfulWithBytes (setUserInfoBytes);
+        //}
+
+        ///// <summary>
+        ///// 淇敼AES鍔犲瘑
+        ///// </summary>
+        ///// <returns></returns>
+        //bool SetGateWayAESEncryption (bool enable = false, string passwordStr = "")
+        //{
+        //    byte [] sendBytes = new byte [17];
+        //    sendBytes [0] = enable ? (byte)1 : (byte)0; //0:涓嶄娇鑳�  1 - 255:浣胯兘
+        //    byte [] password = CommonPage.MyEncodingGB2312.GetBytes (passwordStr);
+        //    Array.Copy (password, 0, sendBytes, 1, 16 < password.Length ? 16 : password.Length);
+        //    var backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayAESEncryption, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, sendBytes);
+
+        //    return CheckIsSuccessfulWithBytes (backBytes);
+        //}
+
+        ///// <summary>
+        ///// 淇敼涓婚
+        ///// </summary>
+        ///// <param name="bPublish">鏄惁涓哄彂甯冧富棰�</param>
+        ///// <param name="bDefault">鏄惁榛樿</param>
+        ///// <returns></returns>
+        //bool SetGateWayTopic (string topicInfoStr = "", bool bPublish = false, bool bDefault = false)
+        //{
+        //    byte [] sendBytes = new byte [50];
+        //    sendBytes [0] = bPublish ? (byte)2 : (byte)1; //1锛氳闃�  2锛氬彂甯�
+        //    sendBytes [1] = bDefault ? (byte)0 : (byte)1; //1:闈為粯璁� 0:榛樿
+
+        //    byte [] topicInfo = CommonPage.MyEncodingGB2312.GetBytes (topicInfoStr);
+        //    Array.Copy (topicInfo, 0, sendBytes, 2, 48 < topicInfo.Length ? 48 : topicInfo.Length);
+        //    var backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayTopic, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, sendBytes);
+
+        //    if (backBytes != null && backBytes.Length >= 2) {
+        //        if (backBytes [0] == sendBytes [0] && backBytes [1] == sendBytes [1]) {
+        //            return true;
+        //        }
+        //    }
+        //    return CheckIsSuccessfulWithBytes (backBytes);
+        //}
+
     }
 }
\ No newline at end of file

--
Gitblit v1.8.0