From f60ce72c3c29c7d31a046795c88ec39a69e73d45 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期三, 06 一月 2021 17:33:54 +0800
Subject: [PATCH] 2021-01-06 1.替换新云端前期准备相关接口,和修改相关参数。

---
 Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideAddGateway.cs |  335 +++++++++++++++++++++++++++++++++++++++++--------------
 1 files changed, 249 insertions(+), 86 deletions(-)

diff --git a/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideAddGateway.cs b/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideAddGateway.cs
index 85688bb..3462211 100644
--- a/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideAddGateway.cs
+++ b/Crabtree/SmartHome/UI/SimpleControl/Phone/Guide/GuideAddGateway.cs
@@ -26,7 +26,7 @@
         /// <summary>
         /// 淇敼缃戝叧澶囨敞
         /// </summary>
-        static void ResetGatewayName (GatewayBase gatewayBase,Button nameButton1)
+        static void ResetGatewayName (GatewayBase gatewayBase, Button nameButton1)
         {
             Dialog dialog = new Dialog ();
 
@@ -62,7 +62,7 @@
                 Height = Application.GetRealHeight (80),
                 TextAlignment = TextAlignment.CenterLeft,
                 TextColor = SkinStyle.Current.TextColor,
-                Text  = "Gateway Name : "
+                Text = "Gateway Name : "
             };
             bodyView.AddChidren (btnZoneName);
 
@@ -83,10 +83,11 @@
             etRemark.EditorEnterAction += (obj) => {
                 Application.HideSoftInput ();
             };
-            if (MainPage.LoginUser.AccountType == 1) {
-                etRemark.Enable = false;
-                etRemark.BorderWidth = 0;
-            }
+
+            //if (MainPage.LoginUser.AccountType == 1) {
+            //    etRemark.Enable = false;
+            //    etRemark.BorderWidth = 0;
+            //}
 
             var BottomView = new FrameLayout () {
                 Y = Application.GetRealHeight (400 - 88),
@@ -136,6 +137,9 @@
 
         public void ShowPage (RegionInfoRes home)
         {
+            ////2020-01-14 绗竴娆¤繘鍏ラ〉闈㈤粯璁�
+            //UserConfig.Instance.IsLocalEncrypt = false;
+
             addedList = new List<Common> ();
             inView = this;
             #region 鏍囬
@@ -177,6 +181,8 @@
             };
             topView.AddChidren (back);
             back.MouseUpEventHandler += (sender, e) => {
+                //閲嶇疆涓哄姞瀵嗘ā寮�
+                UserConfig.Instance.IsLocalEncrypt = true;
                 (Parent as PageLayout).PageIndex -= 1;
             };
 
@@ -256,7 +262,7 @@
                     var delAlert = new Alert ("", "If you delete gateway, you will not able to control the devices. Still you want to delete the gateway?", "No", "Yes");
                     delAlert.Show ();
 
-                    delAlert.ResultEventHandler += ( sender1,  e1) => {
+                    delAlert.ResultEventHandler += (sender1, e1) => {
                         if (e1) {
                             var delFile = IO.FileUtils.ReadFiles ().FindAll ((w) => {
                                 return (w.Split ('_') [0] == "Equipment") && (w.Split ('_') [2] == common.SubnetID.ToString ());
@@ -294,67 +300,11 @@
                     bool goNext = false;
                     System.Threading.Tasks.Task.Run (() => {
                         try {
-                            if (common.Type == DeviceType.OnePortWirelessFR || common.Type == DeviceType.OnePortMqttFR) {
-                                var backBytes = Control.ControlBytesSendHasReturn (Command.Read_APP_Data_STORE_1D5C_CMD, common.SubnetID, common.DeviceID, new byte [] { });
-                                if (backBytes == null) {
-                                    Application.RunOnMainThread (() => {
-                                        new Alert ("", "No response from gateway. Please make sure the gateway is online and its firmware is up to date.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                    });
-                                }
-                           
-                              
-                                if (backBytes.Length >= 37) {
 
-                                    //******************浣忓畢ID string绫诲瀷*************
-                                    bool enable = backBytes [0] == 0 ? false : true;
-                                    //杩斿洖浣忓畢ID 杞负string绫诲瀷
-                                    string backIDStr = CommonPage.MyEncodingGB2312.GetString (backBytes, 1, 36).Trim ('\0');
-                                    backIDStr = backIDStr.Replace ("每", "");
-                                    //|| backIDStr == "每每每每每每每每每每每每每每每每每每每每每每每每每每每每每每每每每每每每"
-                                    if (enable || backIDStr == UserConfig.Instance.CurrentRegion.Id || string.IsNullOrEmpty (backIDStr) ) {
-                                        goNext = true;
-                                    } else {
-                                        //#if DEBUG
-                                        //                                    Control.ControlBytesSendHasReturn (Command.Write_APP_Data_STORE_1D5E_CMD, common.SubnetID, common.DeviceID, new byte [] { 0, 0, 0, 0 });
-                                        //#endif
-                                        Application.RunOnMainThread (() => {
-                                            //new Alert ("", "This gateway has been bound to a residence, please reset it before binding to another residence.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                            new Alert ("", ErrorCode.UnableToBindGateway, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-
-                                        });
-                                    }
-
-                                    //******************浣忓畢ID int绫诲瀷*************
-                                    //bool enable = backBytes [32] == 0 ? false : true;
-                                    //int bingResideceId = 0;
-                                    ////杩斿洖浣忓畢ID 杞负string绫诲瀷
-                                    //string backIDStr = CommonPage.MyEncodingGB2312.GetString (backBytes, 0, 32).Trim ('\0');
-
-                                    //bingResideceId = Utlis.StringToInt (backIDStr);
-
-                                    //if (true ||  bingResideceId == UserConfig.Instance.CurrentRegion.RegionID || bingResideceId == 0) {
-                                    //    goNext = true;
-                                    //} else {
-                                    //    //#if DEBUG
-                                    //    //                                    Control.ControlBytesSendHasReturn (Command.Write_APP_Data_STORE_1D5E_CMD, common.SubnetID, common.DeviceID, new byte [] { 0, 0, 0, 0 });
-                                    //    //#endif
-                                    //    Application.RunOnMainThread (() => {
-                                    //        new Alert ("", "This gateway has been bound to a residence, please reset it before binding to another residence.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                    //    });
-                                    //}
-
-                                } else {
-                                    Application.RunOnMainThread (() => {
-                                        new Alert ("", ErrorCode.GatewayVersionLow, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
-                                    });
-                                    //goNext = true;
-                                }
-
-                            } else {
-                                goNext = true;
-                            }
+                            goNext = CheckIfGoNext (common);
+                         
                         } catch (Exception ex) {
-                            Console.WriteLine (ex.Message); 
+                            Utlis.WriteLine (ex.Message);
                         } finally {
                             Application.RunOnMainThread (() => {
                                 MainPage.Loading.Hide ();
@@ -363,18 +313,20 @@
                                     CommonPage.FindGatewayChilrenIPAddress = common.IPAddress;
                                     inThisView = false;
                                     if (inView != null) {
-                                        Console.WriteLine ("inView != null");
+                                        Utlis.WriteLine ("inView != null");
                                         var deviceListView = new GuideSettingGateway (common);
                                         (inView.Parent as PageLayout).AddChidren (deviceListView);
                                         deviceListView.ShowPage ();
                                         (inView.Parent as PageLayout).PageIndex = (inView.Parent as PageLayout).ChildrenCount - 1;
                                     } else {
-                                        Console.WriteLine ("inView == null");
+                                        Utlis.WriteLine ("inView == null");
                                         UserHomePage.FrameLayoutMain.AddChidren (UserMiddle.guidePageView);
                                         var guide = new GuideAddResidence ();
                                         UserMiddle.guidePageView.AddChidren (guide);
-                                        guide.ShowHomeList ();
+                                        guide.ShowHomeView ();
                                         UserMiddle.guidePageView.PageIndex = 0;
+                                        //閲嶇疆涓哄姞瀵嗘ā寮�
+                                        UserConfig.Instance.IsLocalEncrypt = true;
                                     }
                                 }
                             });
@@ -394,12 +346,16 @@
 
 
         static bool inThisView = false;
-        Alert checkInternetAlert = new Alert ("", "Your phone in not connected to WIFI network, please connet", "Close", "Search again");
-        Alert confirmAlert = new Alert ("", "Please make sure gateway is powered up and comect to WiFi router.", "Close", "Search again");
-        Alert confirmAlert1 = new Alert ("", "If not all the gateways are in the list,you can search again.", "Close", "Search again");
+        //Alert checkInternetAlert = new Alert ("", "Your phone in not connected to WIFI network, please connet", "Close", "Search again");
+        //Alert confirmAlert = new Alert ("", "Please make sure gateway is powered up and comect to WiFi router.", "Close", "Search again");
+        //Alert confirmAlert1 = new Alert ("", "If not all the gateways are in the list,you can search again.", "Close", "Search again");
+        //Alert wrongPasswordAlert = new Alert ("", ErrorCode.GatewayPasswordError, "Close", "Search again");
+
         void SearchGatewayList ()
         {
             if (UserConfig.Instance.internetStatus == 0 || UserConfig.Instance.internetStatus == 1) {
+                Alert checkInternetAlert = new Alert ("", ErrorCode.NotConnectedToWIFI, "Close", "Search again");
+
                 checkInternetAlert.Show ();
 
                 checkInternetAlert.ResultEventHandler += (dsss, eee) => {
@@ -417,13 +373,17 @@
                         MainPage.Loading.Start ("Searching for gateway...");
                     });
                     #region 鎼滅储璁惧
+                    ////2020-01-14 榛樿鏄庢枃寮�濮嬫悳绱�
+                    UserConfig.Instance.IsLocalEncrypt = false;
+                    UserConfig.Instance.EncryptedPasswordCorrect = true;
+
                     CommonPage.LocalPhoneFindDevice = true;
                     CommonPage.RandomHigh = (byte)new Random ().Next (255);
                     CommonPage.RandomLow = (byte)new Random ().Next (255);
                     CommonPage.GateWayList.Clear ();
                     CommonPage.FindGateway = true;
                     //濡傛灉涓ゆ閮芥病鏈夋暟鎹弽棣堬紝灏变笉璇诲彇
-                    int readCount = 2;
+                    int readCount = 3;
                     while (0 < readCount) {
                         readCount--;
                         System.IO.MemoryStream ms = new System.IO.MemoryStream ();
@@ -444,7 +404,7 @@
                         }
                         Control control = new Control ();
 
-                        Console.WriteLine ("缁勬挱鎼滅储缃戝叧锛屾悳绱㈠湴鍧�鏄�:" + CommonPage.EndPoint.ToString () + "    " + CommonPage.GateWayList.Count);
+                        Utlis.WriteLine ("缁勬挱鎼滅储缃戝叧锛屾悳绱㈠湴鍧�鏄�:" + CommonPage.EndPoint.ToString () + "    " + CommonPage.GateWayList.Count);
                         control.Send (new Target () {
                             IPEndPoint = CommonPage.EndPoint,
                             Command = Command.ReadGateway,
@@ -453,7 +413,7 @@
                             AddData = ms.ToArray ()
                         }, SendCount.Zero, false);
 
-                        Console.WriteLine ("骞挎挱鎼滅储缃戝叧锛屾悳绱㈠湴鍧�鏄�:" + new Net.NetWiFi ().BroadcastIpAddress.ToString () + "    " + CommonPage.GateWayList.Count);
+                        Utlis.WriteLine ("骞挎挱鎼滅储缃戝叧锛屾悳绱㈠湴鍧�鏄�:" + new Net.NetWiFi ().BroadcastIpAddress.ToString () + "    " + CommonPage.GateWayList.Count);
                         control.Send (new Target () {
                             IPEndPoint = new System.Net.IPEndPoint (new Net.NetWiFi ().BroadcastIpAddress, 6000),
                             Command = Command.ReadGateway,
@@ -465,7 +425,7 @@
                         System.Threading.Thread.Sleep (800);
                         //濡傛灉鏁伴噺涓嶇浉绛夛紝灏遍噸缃鏁�
                         if (tempCount != CommonPage.GateWayList.Count) {
-                            readCount = 2;
+                            readCount = 3;
                         }
                     }
                     CommonPage.FindGateway = false;
@@ -473,23 +433,21 @@
                     CommonPage.LocalPhoneFindDevice = false;
                     #endregion
                 } catch (Exception ex) {
-                    Console.WriteLine (ex.ToString ());
+                    Utlis.WriteLine (ex.ToString ());
                 } finally {
                     Application.RunOnMainThread (() => {
                         if (CommonPage.GateWayList.Count == 0) {
                             MainPage.Loading.Hide ();
                             if (this != null && this.Parent != null) {
-                                confirmAlert.Show ();
-                                confirmAlert.ResultEventHandler += (ddf, ddd) => {
-                                    MainPage.Loading.Hide ();
-                                    if (ddd) {
-                                        SearchGatewayList ();
-                                    }
-                                };
+                                ShowConfirmAlert ();
+                                
+                               
                             }
                         } else {
                             if (this != null && this.Parent != null) {
-                                if (inThisView){// this.Parent.GetChildren (this.Parent.ChildrenCount - 1) == this) {
+                                if (inThisView) {// this.Parent.GetChildren (this.Parent.ChildrenCount - 1) == this) {
+                                    Alert confirmAlert1 = new Alert ("", ErrorCode.IfAllTheGatewaysAreNotInTheList, "Close", "Search again");
+
                                     confirmAlert1.Show ();
                                     confirmAlert1.ResultEventHandler += (ddf, ddd) => {
                                         MainPage.Loading.Hide ();
@@ -502,7 +460,212 @@
                         }
                     });
                 }
-            }) { IsBackground=true}.Start();
+            }) { IsBackground = true }.Start ();
+        }
+
+        /// <summary>
+        /// 鎻愮ず
+        /// Please make sure gateway is powered up and comect to WiFi router.
+        /// 鎴栬��
+        /// 
+        /// </summary>
+        static void ShowConfirmAlert () {
+            if (UserConfig.Instance.IsLocalEncrypt) {
+                //瀵嗙爜妫�楠屾纭�
+                if (UserConfig.Instance.EncryptedPasswordCorrect) {
+                    Alert confirmAlert = new Alert ("", ErrorCode.MakeSureGatewayIsPoweredUp, "Close", "Search again");
+                    confirmAlert.Show ();
+                    confirmAlert.ResultEventHandler += (ddf, ddd) => {
+                        MainPage.Loading.Hide ();
+                        if (ddd) {
+                            inView.SearchGatewayList ();
+                        }
+                    };
+                } else {
+                    Alert wrongPasswordAlert = new Alert ("", ErrorCode.GatewayPasswordError, "Close", "Search again");
+                    wrongPasswordAlert.Show ();
+                    wrongPasswordAlert.ResultEventHandler += (ddf, ddd) => {
+                        MainPage.Loading.Hide ();
+                        if (ddd) {
+                            inView.SearchGatewayList ();
+                        }
+                    };
+
+                }
+            } else {
+                Alert confirmAlert = new Alert ("", ErrorCode.MakeSureGatewayIsPoweredUp, "Close", "Search again");
+                confirmAlert.Show ();
+                confirmAlert.ResultEventHandler += (ddf, ddd) => {
+                    MainPage.Loading.Hide ();
+                    if (ddd) {
+                        inView.SearchGatewayList ();
+                    }
+                };
+
+            }
+           
+
+        }
+
+
+        //static byte [] AseKeyBytes;
+        /// <summary>
+        /// 淇敼缃戝叧鏈湴鍔犲瘑
+        /// </summary>
+        /// <param name="gatewayDeicve"></param>
+        /// <param name="isEncrypt"></param>
+        /// <returns></returns>
+        static bool SetGateWayLocalEncryption (GatewayBase gatewayDeicve, bool isEncrypt = true)
+        {
+            if (UserConfig.Instance.CurrentRegion == null) return false;
+
+            byte [] AseKeyBytes = UserConfig.Instance.GenerateLocalEncryptionKey ();
+            byte [] sendBytes = new byte [17];
+            sendBytes [0] = isEncrypt ? (byte)1 : (byte)0; //0:涓嶅姞瀵� 1:鍔犲瘑
+            Array.Copy (AseKeyBytes, 0, sendBytes, 1, 16);
+            byte [] backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayLocalEncryption, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, sendBytes);
+            return CheckIsSuccessfulWithBytes (backBytes);
+        }
+
+        /// <summary>
+        /// 鍒ゆ柇鏄惁淇鎴愬姛 F8 = 鎴愬姛锛� F5=澶辫触
+        /// </summary>
+        /// <param name="backBytes"></param>
+        /// <returns></returns>
+        static bool CheckIsSuccessfulWithBytes (byte [] backBytes, string errorStr = "Modify gateway configuration failed,please try again!")
+        {
+            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>
+        /// CheckIfGoNext
+        /// </summary>
+        /// <returns></returns>
+        static bool CheckIfGoNext (GatewayBase common)
+        {
+            bool goNext = false;
+            if (common.Type == DeviceType.OnePortWirelessFR || common.Type == DeviceType.OnePortMqttFR) {
+                goNext = CheckIfGoNextMqttGateway (common);
+            } else {
+                goNext = true;
+            }
+            return goNext;
+        }
+
+        /// <summary>
+        /// CheckIfGoNextMqttGateway
+        /// </summary>
+        /// <returns></returns>
+        static bool CheckIfGoNextMqttGateway (GatewayBase common)
+        {
+            Application.RunOnMainThread (() => {
+                MainPage.Loading.Start ("Please wait...");
+            });
+
+            bool goNext = false;
+            //if (!UserConfig.Instance.IsLocalEncrypt) {
+            //    //濡傛灉娌″姞瀵嗭紝璧颁慨鏀瑰姞瀵嗘柟娉�
+            //    var result = SetGateWayLocalEncryption (common);
+            //    if (!result) {
+            //        MainPage.LoadingHide ();
+            //        return result;//淇敼澶辫触 杩斿洖goNext false
+            //    }
+            //    //淇敼鎴愬姛,璁剧疆鏈湴涓哄姞瀵嗘柟寮�
+            //    UserConfig.Instance.IsLocalEncrypt = true;
+            //    //string aseKeyStr = CommonPage.MyEncodingUTF8.GetString (AseKeyBytes);
+            //    //UserConfig.Instance.LocalEncryptKey = aseKeyStr;
+            //    Utlis.WriteLine ($"============>LocalEncryptKey 鍔犲瘑鎴愬姛Key涓猴細{UserConfig.Instance.LocalEncryptKey}");
+            //}
+
+            var backBytes = Control.ControlBytesSendHasReturn (Command.Read_APP_Data_STORE_1D5C_CMD, common.SubnetID, common.DeviceID, new byte [] { });
+          
+            if (backBytes == null) {
+                Application.RunOnMainThread (() => {
+                    new Alert ("", "No response from gateway. Please make sure the gateway is online and its firmware is up to date.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                });
+               
+            }
+
+            if (backBytes.Length >= 37) {
+                //******************浣忓畢ID string绫诲瀷*************
+                bool enable = backBytes [0] == 0 ? false : true;
+                //杩斿洖浣忓畢ID 杞负string绫诲瀷
+                string backIDStr = CommonPage.MyEncodingGB2312.GetString (backBytes, 1, 36).Trim ('\0');
+                backIDStr = backIDStr.Replace ("每", "");
+                //2020-01-12
+                backIDStr = backIDStr.Replace ("\0", "");
+                if (enable || backIDStr == UserConfig.Instance.CurrentRegion.Id || string.IsNullOrEmpty (backIDStr)) {
+                   
+
+                    if (!UserConfig.Instance.IsLocalEncrypt) {
+                        //濡傛灉娌″姞瀵嗭紝璧颁慨鏀瑰姞瀵嗘柟娉�
+                        var result = SetGateWayLocalEncryption (common);
+                        if (!result) {
+                            Application.RunOnMainThread (() => {
+                                MainPage.Loading.Hide ();
+                                new Alert ("", "Encryption gateway failed, please try again.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+
+                            });
+                          
+                            return result;//淇敼澶辫触 杩斿洖goNext false
+                        }
+                        //淇敼鎴愬姛,璁剧疆鏈湴涓哄姞瀵嗘柟寮�
+                        UserConfig.Instance.IsLocalEncrypt = true;
+                        //Utlis.WriteLine ($"============>LocalEncryptKey 鍔犲瘑鎴愬姛Key涓猴細{UserConfig.Instance.LocalEncryptKey}");
+                    }
+                    goNext = true;
+
+                } else {
+                    UnableToBindGatewayAlertShow ();
+                }
+            } else {
+                Application.RunOnMainThread (() => {
+                    new Alert ("", ErrorCode.GatewayVersionLow, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
+                });
+            }
+            MainPage.LoadingHide ();
+            return goNext;
+
+        }
+
+
+        static void UnableToBindGatewayAlertShow ()
+        {
+            if (inView == null)
+                return;
+            Application.RunOnMainThread (() => {
+
+                //if (this != null && this.Parent != null) {
+                var alter = new Alert ("", ErrorCode.UnableToBindGateway, Language.StringByID (R.MyInternationalizationString.Close));
+                alter.ResultEventHandler += (sender1, e1) => {
+                    if (e1) {
+                        if (inView == null)
+                            return;
+                        //閲嶇疆涓哄姞瀵嗘ā寮�
+                        UserConfig.Instance.IsLocalEncrypt = true;
+                        (inView.Parent as PageLayout).PageIndex -= 1;
+                    }
+                };
+                alter.Show ();
+                //}
+
+            });
+
         }
     }
 }
\ No newline at end of file

--
Gitblit v1.8.0