JLChen
2020-01-15 4a61a132ce09b1fd42fd80fcbff1855bad4c0f48
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);
@@ -136,6 +136,9 @@
        public void ShowPage (RegionInfoRes home)
        {
            ////2020-01-14 第一次进入页面默认
            //UserConfig.Instance.IsLocalEncrypt = false;
            addedList = new List<Common> ();
            inView = this;
            #region 标题
@@ -177,6 +180,8 @@
            };
            topView.AddChidren (back);
            back.MouseUpEventHandler += (sender, e) => {
                //重置为加密模式
                UserConfig.Instance.IsLocalEncrypt = true;
                (Parent as PageLayout).PageIndex -= 1;
            };
@@ -256,7 +261,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,68 +299,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 ("ÿ", "");
                                    //2020-01-12
                                    backIDStr = backIDStr.Replace ("\0", "");
                                    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);
                            Console.WriteLine (ex.Message);
                        } finally {
                            Application.RunOnMainThread (() => {
                                MainPage.Loading.Hide ();
@@ -376,6 +324,8 @@
                                        UserMiddle.guidePageView.AddChidren (guide);
                                        guide.ShowHomeList ();
                                        UserMiddle.guidePageView.PageIndex = 0;
                                        //重置为加密模式
                                        UserConfig.Instance.IsLocalEncrypt = true;
                                    }
                                }
                            });
@@ -418,13 +368,16 @@
                        MainPage.Loading.Start ("Searching for gateway...");
                    });
                    #region 搜索设备
                    ////2020-01-14 默认明文开始搜索
                    UserConfig.Instance.IsLocalEncrypt = false;
                    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 ();
@@ -466,7 +419,7 @@
                        System.Threading.Thread.Sleep (800);
                        //如果数量不相等,就重置次数
                        if (tempCount != CommonPage.GateWayList.Count) {
                            readCount = 2;
                            readCount = 3;
                        }
                    }
                    CommonPage.FindGateway = false;
@@ -490,7 +443,7 @@
                            }
                        } 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) {
                                    confirmAlert1.Show ();
                                    confirmAlert1.ResultEventHandler += (ddf, ddd) => {
                                        MainPage.Loading.Hide ();
@@ -503,7 +456,128 @@
                        }
                    });
                }
            }) { IsBackground=true}.Start();
            }) { IsBackground = true }.Start ();
        }
        //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)
        {
            if (backBytes == null) {
                Application.RunOnMainThread (() => {
                    new Alert ("", Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline),
                               Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
                return false;
            } else if (backBytes [0] == 0xF8) {//F8 = 成功; F5=失败
                return true;
            } else {
                Application.RunOnMainThread (() => {
                    new Alert ("", Language.StringByID (R.MyInternationalizationString.OperationFailed),
                               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;
                System.Console.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 ();
                });
            }
            MainPage.LoadingHide ();
            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)) {
                    goNext = true;
                } else {
                    Application.RunOnMainThread (() => {
                        new Alert ("", ErrorCode.UnableToBindGateway, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                    });
                }
            } else {
                Application.RunOnMainThread (() => {
                    new Alert ("", ErrorCode.GatewayVersionLow, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
            }
            return goNext;
        }
    }
}