From 66a9965c44ecc32a6696abca876ab9d1cd091584 Mon Sep 17 00:00:00 2001
From: gxc <guoxuecheng@guoxuechengdeMacBook-Pro.local>
Date: 星期五, 28 二月 2020 15:25:13 +0800
Subject: [PATCH] 2020.2.28

---
 ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlGatewayLogic.cs |  773 +++++++++++++++++++++++++++++++++++++++++++++++++----------
 1 files changed, 638 insertions(+), 135 deletions(-)

diff --git a/ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlGatewayLogic.cs b/ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlGatewayLogic.cs
index 20c6cb8..5fafb97 100755
--- a/ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlGatewayLogic.cs
+++ b/ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlGatewayLogic.cs
@@ -15,11 +15,11 @@
         #region 鈻� 鍙橀噺澹版槑___________________________
 
         /// <summary>
-        /// 澶囦唤涓氬姟鐨勯�昏緫
+        /// 缃戝叧涓氬姟鐨勯�昏緫绫�
         /// </summary>
         private static HdlGatewayLogic m_Current = null;
         /// <summary>
-        /// 澶囦唤涓氬姟鐨勯�昏緫
+        /// 缃戝叧涓氬姟鐨勯�昏緫绫�
         /// </summary>
         public static HdlGatewayLogic Current
         {
@@ -117,10 +117,20 @@
             {
                 return;
             }
+
+            List<string> listBackupGwId = new List<string>();
+            var fileData = Global.ReadFileByDirectory(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile);
+            if (fileData != null)
+            {
+                //鏂板锛氳櫧鐒舵鐜囦綆锛屼絾鏄‘瀹炲彂鐢熶簡銆傚鏋滄湁缃戠粶鏃讹紝App閲嶆柊缁戝畾璁板綍鐨勭綉鍏冲け璐ョ殑璇�
+                //涓嶅簲璇ュ垹闄ゅ畠
+                listBackupGwId = JsonConvert.DeserializeObject<List<string>>(System.Text.Encoding.UTF8.GetString(fileData));
+            }
+
             List<string> listDelete = new List<string>();
             foreach (var gatewayId in this.dicGateway.Keys)
             {
-                if (result.ContainsKey(gatewayId) == false)
+                if (result.ContainsKey(gatewayId) == false && listBackupGwId.Contains(gatewayId) == false)
                 {
                     //鏈湴瀛樺湪浜戠涓嶅瓨鍦ㄧ殑缃戝叧锛屽垯鍒犻櫎
                     listDelete.Add(gatewayId);
@@ -132,8 +142,10 @@
                 List<CommonDevice> list = Common.LocalDevice.Current.GetDeviceByGatewayID(gatewayId);
                 foreach (var device in list)
                 {
-                    //鍒犻櫎璁惧锛屼笉鍒犻櫎鎴块棿淇℃伅
-                    Common.LocalDevice.Current.DeleteMemmoryDevice(device, false);
+                    //鍒犻櫎涓�鑸澶�
+                    Common.LocalDevice.Current.DeleteMemmoryDevice(device, true);
+                    //鍒犻櫎Ota璁惧
+                    Common.LocalDevice.Current.DeleteMemmoryOtaDevice(device.DeviceAddr);
                 }
                 //鍒犻櫎缃戝叧鏂囦欢
                 this.DeleteGatewayFile(gatewayId);
@@ -168,10 +180,18 @@
         /// <returns></returns>
         private ZbGateway GetGatewayFromFile(string file)
         {
-            byte[] filebyte = Global.ReadFileByHomeId(file);
-            string strvalue = System.Text.Encoding.UTF8.GetString(filebyte);
-            var gateway = JsonConvert.DeserializeObject<ZbGateway>(strvalue);
-            return gateway;
+            try
+            {
+                byte[] filebyte = Global.ReadFileByHomeId(file);
+                string strvalue = System.Text.Encoding.UTF8.GetString(filebyte);
+                var gateway = JsonConvert.DeserializeObject<ZbGateway>(strvalue);
+                return gateway;
+            }
+            catch (Exception ex)
+            {
+                HdlLogLogic.Current.WriteLog(ex);
+                return null;
+            }
         }
 
         #endregion
@@ -179,20 +199,36 @@
         #region 鈻� 娣诲姞缃戝叧___________________________
 
         /// <summary>
-        /// 娣诲姞鏂扮綉鍏�(浠呴檺杩藉姞鏂扮殑缃戝叧  1:姝e父  -1:寮傚父  0:褰撳墠鐨勭綉鍏崇粦瀹氬湪浜嗗綋鍓嶈处鍙蜂笅鐨勪笉鍚屼綇瀹呴噷闈�)
+        /// 娣诲姞鏂扮綉鍏�(浠呴檺杩藉姞鏂扮殑缃戝叧)
         /// </summary>
         /// <param name="zbGateway">缃戝叧</param>
         /// <param name="mode">鏄惁鏄剧ず閿欒</param>
-        public async Task<int> AddNewGateway(ZbGateway zbGateway, ShowErrorMode mode)
+        public async Task<bool> AddNewGateway(ZbGateway zbGateway, ShowErrorMode mode)
         {
             //鎵ц娣诲姞缃戝叧鍒板唴瀛�
             var result = await this.DoAddGatewayToMemory(zbGateway, mode);
-            if (result != 1)
+            //鍓嶇殑缃戝叧缁戝畾鍦ㄤ簡褰撳墠璐﹀彿涓嬬殑涓嶅悓浣忓畢閲岄潰
+            if (result == 0)
             {
-                return result;
+                if (mode == ShowErrorMode.YES)
+                {
+                    //缃戝叧缁戝畾鍦ㄥ綋鍓嶈处鍙蜂笅鐨勫叾浠栦綇瀹呴噷\r\n璇疯В闄ょ粦瀹氬悗鍐嶈瘯
+                    string msg = Language.StringByID(R.MyInternationalizationString.uTheGatewayInOtherResidenceMsg);
+                    if (msg.Contains("{0}") == true)
+                    {
+                        msg = string.Format(msg, "\r\n");
+                    }
+                    this.ShowTipMsg(msg);
+                }
+                return false;
+            }
+            if (result == -1)
+            {
+                return false;
             }
-
-            return 1;
+            //璁剧疆缃戝叧鐨勭粡绾害
+            bool falge = this.SetGatewaySite(zbGateway, Common.Config.Instance.Home.Longitude, Common.Config.Instance.Home.Latitude);
+            return falge;
         }
 
         /// <summary>
@@ -391,6 +427,7 @@
         /// 閲嶆柊缁戝畾缃戝叧(1:姝e父  -1:寮傚父  0:褰撳墠鐨勭綉鍏崇粦瀹氬湪浜嗗綋鍓嶈处鍙蜂笅鐨勪笉鍚屼綇瀹呴噷闈�)
         /// </summary>
         /// <param name="zbGateway">缃戝叧</param>
+        /// <param name="btnMsg">娑堟伅鎺т欢</param>
         public async Task<int> ReBindNewGateway(ZbGateway zbGateway, NormalViewControl btnMsg = null)
         {
             if (zbGateway == null)
@@ -398,6 +435,12 @@
                 //閿欒:缃戝叧瀵硅薄涓㈠け
                 string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                 this.ShowTipMsg(msg);
+                return -1;
+            }
+            //璁剧疆缃戝叧鐨勭粡绾害
+            bool falge = this.SetGatewaySite(zbGateway, Common.Config.Instance.Home.Longitude, Common.Config.Instance.Home.Latitude);
+            if (falge == false)
+            {
                 return -1;
             }
 
@@ -437,7 +480,7 @@
                     btnMsg.TextID = R.MyInternationalizationString.uGatewayDataIsChangingPleaseWhait;
                 });
             }
-            await System.Threading.Tasks.Task.Delay(8000);
+            await Task.Delay(8000);
 
             //鑾峰彇缃戝叧鐨勪俊鎭�
             var result = await zbGateway.GetZbGwInfoAsync();
@@ -449,15 +492,7 @@
                 return -1;
             }
 
-            if (result == null)
-            {
-                //鑾峰彇缃戝叧淇℃伅澶辫触
-                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayInfoFail);
-                this.ShowTipMsg(msg);
-                return -1;
-            }
-
-            if (result.getGwData == null)
+            if (result == null || result.getGwData == null)
             {
                 //鑾峰彇缃戝叧淇℃伅澶辫触
                 string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayInfoFail);
@@ -548,8 +583,104 @@
             HdlAutoBackupLogic.AddOrEditorFile(zbGateway.FilePath);
 
             return true;
-        }
-
+        }
+
+        #endregion
+
+        #region 鈻� 缃戝叧鍒囨崲___________________________
+
+        /// <summary>
+        /// 鎵ц鍒囨崲缃戝叧鎿嶄綔
+        /// </summary>
+        /// <param name="gatewayId"></param>
+        public async Task<bool> DoSwitchGateway(string gatewayId)
+        {
+            var zbGateway = this.GetLocalGateway(gatewayId);
+            if (this.CheckGatewayOnlineByFlag(zbGateway) == true)
+            {
+                //閲嶆柊鑾峰彇鍦ㄧ嚎缃戝叧鐨勪俊鎭�
+                var result = await this.GetOnlineGatewayInfo(gatewayId);
+                if (result == false)
+                {
+                    return false;
+                }
+            }
+            //鍒囨崲缃戝叧,淇濆瓨缂撳瓨
+            this.SaveGatewayIdToLocation(gatewayId);
+            return true;
+        }
+
+        /// <summary>
+        /// 鑾峰彇鍦ㄧ嚎缃戝叧淇℃伅
+        /// </summary>
+        /// <param name="gatewayId"></param>
+        /// <returns></returns>
+        private async Task<bool> GetOnlineGatewayInfo(string gatewayId)
+        {
+            //鏄剧ず杩涘害鏉�
+            ProgressBar.Show();
+
+            //妫�娴嬪箍鎾埌鐨勮繖涓綉鍏虫槸鍚︽嫢鏈変綇瀹匢D
+            ZbGateway realWay = null;
+            bool getGatewayInfo = true;
+            if (this.GetRealGateway(ref realWay, gatewayId) == true)
+            {
+                //閲嶆柊璁剧疆浣忓畢ID(杩欎釜搴旇鏄笉缁忚繃APP,鐩存帴鎶婄綉鍏虫仮澶嶄簡鍑哄巶璁剧疆)
+                if (this.HomeIdIsEmpty(realWay.getGatewayBaseInfo.HomeId) == true)
+                {
+                    int result2 = await this.ReBindNewGateway(realWay);
+                    if (result2 == 0)
+                    {
+                        //鍑虹幇鏈煡閿欒,璇风◢鍚庡啀璇�
+                        this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndResetAgain));
+                        //鍏抽棴杩涘害鏉�
+                        ProgressBar.Close();
+                    }
+                    else if (result2 == -1)
+                    {
+                        //鍏抽棴杩涘害鏉�
+                        ProgressBar.Close();
+                        return false;
+                    }
+                    //閲嶆柊缁戝畾缃戝叧閲岄潰宸茬粡閲嶆柊鑾峰彇浜嗙綉鍏充俊鎭�
+                    getGatewayInfo = false;
+                }
+            }
+
+            if (getGatewayInfo == true)
+            {
+                //鑾峰彇缃戝叧淇℃伅
+                var info = await this.GetGatewayNewInfoAsync(realWay);
+                if (info == null)
+                {
+                    //鍏抽棴杩涘害鏉�
+                    ProgressBar.Close();
+                    return false;
+                }
+            }
+
+            //鑾峰彇鍏ㄩ儴璁惧
+            int result = LocalDevice.Current.SetDeviceToMemmoryByGateway(realWay);
+            //鍏抽棴杩涘害鏉�
+            ProgressBar.Close();
+            if (result == -1)
+            {
+                return false;
+            }
+            return true;
+        }
+
+        /// <summary>
+        /// 淇濆瓨閫夋嫨鐨勭綉鍏矷D鍒版湰鍦�
+        /// </summary>
+        /// <param name="gatewayId"></param>
+        public void SaveGatewayIdToLocation(string gatewayId)
+        {
+            GatewayResourse.AppOldSelectGatewayId = gatewayId;
+            byte[] data = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(GatewayResourse.AppOldSelectGatewayId));
+            Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.AppOldSelectGatewayFile, data);
+        }
+
         #endregion
 
         #region 鈻� 鍒犻櫎缃戝叧___________________________
@@ -581,15 +712,15 @@
                 bool result = await this.SetHomeIdToGateway(realWay, string.Empty);
                 if (result == false)
                 {
-                    //缃戝叧瑙g粦澶辫触
+                    //缃戝叧瑙g粦澶辫触  涓嶇悊瀹�,鍥犱负缃戝叧鍙互鎸夋寜閿己鍒舵悳绱㈠緱鍒�
                     string msg = Language.StringByID(R.MyInternationalizationString.uGatewayUnBindFail);
-                    this.ShowErrorMsg(msg);
-                    return false;
+                    //this.ShowErrorMsg(msg);
+                    //return false;
                 }
             }
 
             //鍒犻櫎浜戠鐨勭綉鍏�
-            await Phone.UserCenter.HdlGatewayLogic.Current.DeleteDataBaseGateway(zbGatewayID);
+            await this.DeleteDataBaseGateway(zbGatewayID);
 
             //鍒犻櫎缃戝叧鏂囦欢
             this.DeleteGatewayFile(zbGatewayID);
@@ -597,7 +728,7 @@
             //绉婚櫎
             ZbGateway.GateWayList.RemoveAll((obj) => this.GetGatewayId(obj) == zbGatewayID);
             //鏂紑mqtt杩炴帴
-            realWay.DisConnect("GD");
+            realWay.DisConnectLocalMqttClient("GD");
 
             return true;
         }
@@ -630,6 +761,8 @@
             {
                 //鍒犻櫎璁惧鏂囦欢
                 Common.LocalDevice.Current.DeleteMemmoryDevice(device, true);
+                //鍒犻櫎Ota璁惧
+                Common.LocalDevice.Current.DeleteMemmoryOtaDevice(device.DeviceAddr);
             }
             //濡傛灉鏄富缃戝叧
             if (this.IsMainGateway(zbGatewayID) == 1)
@@ -688,8 +821,8 @@
 
             if (waitTime == true)
             {
-                //杩欐槸绗竴閬撳潕,寮哄埗妫�鏌IFI:绛夊緟3绉�(鍥犱负wifi鐨勬椂鍊欙紝瀹冧細鑷姩鍘诲埛鏂癴lage)
-                System.Threading.Thread.Sleep(3000);
+                //杩欐槸绗竴閬撳潕,寮哄埗妫�鏌IFI:绛夊緟2绉�(鍥犱负wifi鐨勬椂鍊欙紝瀹冧細鑷姩鍘诲埛鏂癴lage)
+                System.Threading.Thread.Sleep(2000);
                 //妫�鏌ユ槸鍚︽嫢鏈夌綉鍏冲瓨鍦ㄤ簬WIFi涓�
                 if (this.CheckHadGatewayInWifi(listRealWay) == false)
                 {
@@ -917,6 +1050,268 @@
 
         #endregion
 
+        #region 鈻� 鑾峰彇鍗忚皟鍣ㄥ綋鍓嶄俊閬揰________________
+
+        /// <summary>
+        /// 鑾峰彇鍗忚皟鍣ㄥ綋鍓嶄俊閬�(浼氭湁绛夊緟寤惰繜,杩斿洖-1浠h〃閿欒)
+        /// </summary>
+        /// <param name="zbGateway"></param>
+        /// <returns></returns>
+        public int GetGatewayChannelId(ZbGateway zbGateway)
+        {
+            ZbGateway realWay = null;
+            if (this.GetRealGateway(ref realWay, zbGateway) == false)
+            {
+                //閿欒:缃戝叧瀵硅薄涓㈠け
+                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
+                return -1;
+            }
+            int data = -1;
+            Action<string, string> action = (topic, message) =>
+            {
+                var gatewayID = topic.Split('/')[0];
+                if (topic == gatewayID + "/" + "ZbGw/GetChannel_Respon")
+                {
+                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
+                    data = Convert.ToInt32(jobject["Data"]["Channel"].ToString());
+                }
+            };
+            realWay.Actions += action;
+
+            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 64512 }, { "Command", 8 } };
+            realWay.Send("ZbGw/GetChannel", jObject.ToString());
+
+            int TimeOut = 0;
+            while (data == -1 && TimeOut < 30)
+            {
+                System.Threading.Thread.Sleep(100);
+                TimeOut++;
+            }
+
+            realWay.Actions -= action;
+            if (data == -1)
+            {
+                //鑾峰彇鍗忚皟鍣ㄤ俊閬撳け璐�
+                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayChannelIdFail);
+                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "鍥炲瓒呮椂");
+                this.ShowTipMsg(msg);
+            }
+
+            return data;
+        }
+
+        #endregion
+
+        #region 鈻� 鑾峰彇鍗忚皟鍣∕AC______________________
+
+        /// <summary>
+        /// 鑾峰彇鍗忚皟鍣∕AC鍦板潃(浼氭湁绛夊緟寤惰繜,杩斿洖null浠h〃閿欒)
+        /// </summary>
+        /// <param name="zbGateway"></param>
+        /// <returns></returns>
+        public string GetGatewayCoordinatorMac(ZbGateway zbGateway)
+        {
+            ZbGateway realWay = null;
+            if (this.GetRealGateway(ref realWay, zbGateway) == false)
+            {
+                //閿欒:缃戝叧瀵硅薄涓㈠け
+                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
+                return null;
+            }
+            string data = null;
+            Action<string, string> action = (topic, message) =>
+            {
+                var gatewayID = topic.Split('/')[0];
+                if (topic == gatewayID + "/" + "ZbGw/GetMac_Respon")
+                {
+                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
+                    data = jobject["Data"]["MacAddr"].ToString();
+                }
+            };
+            realWay.Actions += action;
+
+            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 64512 }, { "Command", 13 } };
+            realWay.Send("ZbGw/GetMac", jObject.ToString());
+
+            int TimeOut = 0;
+            while (data == null && TimeOut < 30)
+            {
+                System.Threading.Thread.Sleep(100);
+                TimeOut++;
+            }
+
+            realWay.Actions -= action;
+            if (data == null)
+            {
+                //鑾峰彇鍗忚皟鍣∕ac澶辫触
+                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayCoordinatorMacFail);
+                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "鍥炲瓒呮椂");
+                this.ShowTipMsg(msg);
+            }
+
+            return data;
+        }
+
+        #endregion
+
+        #region 鈻� 鑾峰彇鍗忚皟鍣≒anID____________________
+
+        /// <summary>
+        /// 鑾峰彇鍗忚皟鍣≒anID(浼氭湁绛夊緟寤惰繜,杩斿洖-1浠h〃閿欒)
+        /// </summary>
+        /// <param name="zbGateway"></param>
+        /// <returns></returns>
+        public int GetGatewayPanId(ZbGateway zbGateway)
+        {
+            ZbGateway realWay = null;
+            if (this.GetRealGateway(ref realWay, zbGateway) == false)
+            {
+                //閿欒:缃戝叧瀵硅薄涓㈠け
+                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
+                return -1;
+            }
+            int panId = -1;
+            Action<string, string> action = (topic, message) =>
+            {
+                var gatewayID = topic.Split('/')[0];
+                if (topic == gatewayID + "/" + "ZbGw/GetPanId_Respon")
+                {
+                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
+                    panId = Convert.ToInt32(jobject["Data"]["PANID"].ToString());
+                }
+            };
+            realWay.Actions += action;
+
+            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 64512 }, { "Command", 12 } };
+            realWay.Send("ZbGw/GetPanId", jObject.ToString());
+
+            int TimeOut = 0;
+            while (panId == -1 && TimeOut < 30)
+            {
+                System.Threading.Thread.Sleep(100);
+                TimeOut++;
+            }
+
+            realWay.Actions -= action;
+            if (panId == -1)
+            {
+                //鑾峰彇鍗忚皟鍣≒anID澶辫触
+                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayPanIDFail);
+                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "鍥炲瓒呮椂");
+                this.ShowTipMsg(msg);
+            }
+
+            return panId;
+        }
+
+        #endregion
+
+        #region 鈻� 缃戝叧鑷姩澶囦唤璁剧疆___________________
+
+        /// <summary>
+        /// 鑾峰彇缃戝叧鑷姩澶囦唤璁剧疆(-1:寮傚父 0:鍏抽棴 1:鎵撳紑)
+        /// </summary>
+        /// <param name="zbGateway"></param>
+        /// <returns></returns>
+        public int GetGatewayAutoBackupStatu(ZbGateway zbGateway)
+        {
+            ZbGateway realWay = null;
+            if (this.GetRealGateway(ref realWay, zbGateway) == false)
+            {
+                //閿欒:缃戝叧瀵硅薄涓㈠け
+                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
+                return -1;
+            }
+            int statu = -1;
+            Action<string, string> action = (topic, message) =>
+            {
+                var gatewayID = topic.Split('/')[0];
+                if (topic == gatewayID + "/GatewayAutoBackup_Respon")
+                {
+                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
+                    statu = Convert.ToInt32(jobject["Data"]["AutoBackupStatus"].ToString());
+                }
+            };
+            realWay.Actions += action;
+
+            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6205 } };
+            var data = new Newtonsoft.Json.Linq.JObject { { "AutoBackup", 1 } };
+            jObject.Add("Data", data);
+            realWay.Send("GatewayAutoBackup", jObject.ToString());
+
+            int TimeOut = 0;
+            while (statu == -1 && TimeOut < 60)
+            {
+                System.Threading.Thread.Sleep(100);
+                TimeOut++;
+            }
+
+            realWay.Actions -= action;
+            if (statu == -1)
+            {
+                //鑾峰彇缃戝叧鑷姩澶囦唤璁剧疆澶辫触
+                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayAutoBackupStatuFail);
+                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "鍥炲瓒呮椂");
+                this.ShowTipMsg(msg);
+            }
+
+            return statu;
+        }
+
+        /// <summary>
+        /// 璁剧疆缃戝叧鑷姩澶囦唤璁剧疆
+        /// </summary>
+        /// <param name="zbGateway"></param>
+        /// <param name="statu"></param>
+        /// <returns></returns>
+        public bool SetGatewayAutoBackupStatu(ZbGateway zbGateway, bool statu)
+        {
+            ZbGateway realWay = null;
+            if (this.GetRealGateway(ref realWay, zbGateway) == false)
+            {
+                //閿欒:缃戝叧瀵硅薄涓㈠け
+                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
+                return false;
+            }
+            int result = -1;
+            Action<string, string> action = (topic, message) =>
+            {
+                var gatewayID = topic.Split('/')[0];
+                if (topic == gatewayID + "/GatewayAutoBackup_Respon")
+                {
+                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
+                    result = Convert.ToInt32(jobject["Data"]["AutoBackupStatus"].ToString());
+                }
+            };
+            realWay.Actions += action;
+
+            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6205 } };
+            var data = new Newtonsoft.Json.Linq.JObject { { "AutoBackup", statu == true ? 2 : 3 } };
+            jObject.Add("Data", data);
+            realWay.Send("GatewayAutoBackup", jObject.ToString());
+
+            int TimeOut = 0;
+            while (result == -1 && TimeOut < 60)
+            {
+                System.Threading.Thread.Sleep(100);
+                TimeOut++;
+            }
+
+            realWay.Actions -= action;
+            if (result == -1)
+            {
+                //璁剧疆缃戝叧鑷姩澶囦唤澶辫触
+                string msg = Language.StringByID(R.MyInternationalizationString.uSetGatewayAutoBackupStatuFail);
+                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "鍥炲瓒呮椂");
+                this.ShowTipMsg(msg);
+                return false;
+            }
+
+            return true;
+        }
+
+        #endregion
+
         #region 鈻� 鑾峰彇缃戝叧GwInfo閲岄潰鐨勫睘鎬__________
 
         /// <summary>
@@ -948,44 +1343,6 @@
             {
                 //鑾峰彇鏈湴鐨勫睘鎬� 
                 objValue = localWay.getGwInfo.GetType().InvokeMember(attributeName, System.Reflection.BindingFlags.GetField, null, localWay.getGwInfo, null);
-            }
-
-            if (objValue == null)
-            {
-                return defult;
-            }
-            return objValue;
-        }
-
-        /// <summary>
-        /// 鑾峰彇缃戝叧GatewayBaseInfo閲岄潰鐨勫睘鎬�
-        /// </summary>
-        /// <param name="zbGateway">缃戝叧瀵硅薄</param>
-        /// <param name="attributeName">GatewayBaseInfo閲岄潰灞炴�х殑鍚嶅瓧</param>
-        /// <param name="defult">濡傛灉鑾峰彇涓嶅埌鏃讹紝璁剧疆鐨勯粯璁ゅ��</param>
-        /// <returns></returns>
-        public object GetGatewayBaseInfoAttribute(ZbGateway zbGateway, string attributeName, string defult = "")
-        {
-            string gwID = this.GetGatewayId(zbGateway);
-            var localWay = this.GetLocalGateway(gwID);
-
-            object objValue = null;
-            if (localWay == null || localWay.getGatewayBaseInfo == null)
-            {
-                //鏈湴娌℃湁璁板綍鏈夎繖涓笢瑗�,鍒欑洿鎺ヨ繑鍥炲弬鏁扮殑鏁版嵁
-                if (zbGateway.getGatewayBaseInfo != null)
-                {
-                    objValue = zbGateway.getGatewayBaseInfo.GetType().InvokeMember(attributeName, System.Reflection.BindingFlags.GetField, null, zbGateway.getGatewayBaseInfo, null);
-                }
-                else
-                {
-                    return defult;
-                }
-            }
-            else
-            {
-                //鑾峰彇鏈湴灞炴�� 
-                objValue = localWay.getGatewayBaseInfo.GetType().InvokeMember(attributeName, System.Reflection.BindingFlags.GetField, null, localWay.getGatewayBaseInfo, null);
             }
 
             if (objValue == null)
@@ -1222,7 +1579,7 @@
             //鏈�鍚庡啀鏂紑mqtt杩炴帴
             for (int i = 0; i < list.Count; i++)
             {
-                list[i].DisConnect("G");
+                list[i].DisConnectLocalMqttClient("G");
             }
             list.Clear();
         }
@@ -1496,51 +1853,15 @@
                 return;
             }
             var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 85 } };
-            realWay.Send("GwLinuxLocate_Respon", jObject.ToString());
-        }
-
-        #endregion
-
-        #region 鈻� 涓�鑸柟娉昣__________________________
-
-        /// <summary>
-        /// 寮瑰嚭缃戝叧涓嶅湪绾跨殑
-        /// </summary>
-        private void ShowGatewayNotOnlineMsg()
-        {
-            Application.RunOnMainThread(() =>
+            if (this.IsGatewayExist(zbGateway) == true)
             {
-                //缃戝叧杩炴帴澶辫触,璇风‘璁ょ綉缁�
-                string msg = Language.StringByID(R.MyInternationalizationString.uGatewayIsNotLinkAndCheckNetwork);
-                var control = new ShowMsgControl(ShowMsgType.Tip, msg);
-                control.Show();
-            });
-        }
-
-        /// <summary>
-        /// 鏄剧ず閿欒淇℃伅绐楀彛
-        /// </summary>
-        /// <param name="msg"></param>
-        private void ShowErrorMsg(string msg)
-        {
-            Application.RunOnMainThread(() =>
+                realWay.Send("GwLinuxLocate_Respon", jObject.ToString());
+            }
+            else
             {
-                var contr = new ShowMsgControl(ShowMsgType.Error, msg);
-                contr.Show();
-            });
-        }
-
-        /// <summary>
-        /// 鏄剧ずTip淇℃伅绐楀彛
-        /// </summary>
-        /// <param name="msg"></param>
-        private void ShowTipMsg(string msg)
-        {
-            Application.RunOnMainThread(() =>
-            {
-                var contr = new ShowMsgControl(ShowMsgType.Tip, msg);
-                contr.Show();
-            });
+                //濡傛灉杩欎釜缃戝叧杩樻病鏈夌粦瀹氱殑璇濓紝鍒欏己鍒朵娇鐢ㄦ湰鍦拌繛鎺�
+                realWay.SendLocation("GwLinuxLocate_Respon", System.Text.Encoding.UTF8.GetBytes(jObject.ToString()));
+            }
         }
 
         #endregion
@@ -1746,17 +2067,19 @@
             {
                 return;
             }
-            //鑾峰彇褰撳墠鎺ュ彈鍦ㄧ嚎鐘舵�佹帹閫佺殑鐣岄潰
-            var listForm = new List<CommonFormBase>();
-            listForm.AddRange(UserCenterResourse.listGatewayOnlinePushForm);
-            if (listForm.Count > 0)
+            //淇濆瓨褰撳墠婵�娲荤殑鐣岄潰ID
+            var listId = new List<string>();
+            listId.AddRange(UserCenterResourse.listActionFormId);
+            for (int i = 0; i < listId.Count; i++)
             {
-                for (int i = 0; i < listChange.Count; i++)
+                if (UserCenterResourse.DicActionForm.ContainsKey(listId[i]) == false)
                 {
-                    foreach (var form in listForm)
-                    {
-                        form?.GatewayOnlinePush(listChange[i], listChangeStatu[i]);
-                    }
+                    continue;
+                }
+                //缃戝叧鍦ㄧ嚎鎺ㄩ��
+                for (int j = 0; j < listChange.Count; j++)
+                {
+                    UserCenterResourse.DicActionForm[listId[i]]?.GatewayOnlinePush(listChange[j], listChangeStatu[j]);
                 }
             }
         }
@@ -1827,7 +2150,7 @@
             bool canBreak = false;
             HdlThreadLogic.Current.RunThread(async () =>
             {
-                List<string> list = new List<string>() { "NotSetAgain" };
+                List<string> list = new List<string>() { "NotSetAgain", "NotCheck" };
 
                 //璁剧疆璁块棶鎺ュ彛鐨勫弬鏁�
                 var pra = new GetGatewayPra();
@@ -1870,6 +2193,82 @@
 
         #endregion
 
+        #region 鈻� 璁剧疆缃戝叧缁忕含搴____________________
+
+        /// <summary>
+        /// 璁剧疆缃戝叧缁忕含搴�
+        /// </summary>
+        /// <param name="gateway">缃戝叧瀵硅薄</param>
+        /// <param name="Longitude">缁忓害</param>
+        /// <param name="Latitude">缁村害</param>
+        /// <returns></returns>
+        public bool SetGatewaySite(ZbGateway gateway, double Longitude, double Latitude)
+        {
+            ZbGateway realWay = null;
+            if (this.GetRealGateway(ref realWay, gateway) == false)
+            {
+                //閿欒:缃戝叧瀵硅薄涓㈠け
+                string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
+                this.ShowTipMsg(msg);
+                return false;
+            }
+
+            int result = -1;
+            Action<string, string> action = (topic, message) =>
+            {
+                var gatewayID = topic.Split('/')[0];
+                if (topic == gatewayID + "/" + "Logic/SetSite_Respon")
+                {
+                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
+                    result = Convert.ToInt32(jobject["Data"]["Result"].ToString());
+                }
+            };
+            realWay.Actions += action;
+            //涓や綅灏忔暟
+            Longitude = Math.Round(Longitude, 2);
+            Latitude = Math.Round(Latitude, 2);
+
+            int intLongitude = Convert.ToInt32(Longitude.ToString().Replace(".", string.Empty));
+            int intLatitude = Convert.ToInt32(Latitude.ToString().Replace(".", string.Empty));
+
+            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 2013 } };
+            var data = new Newtonsoft.Json.Linq.JObject { { "Longitude", intLongitude }, { "Latitude", intLatitude } };
+            jObject.Add("Data", data);
+            if (this.IsGatewayExist(gateway) == true)
+            {
+                realWay.Send("Logic/SetSite", jObject.ToString());
+            }
+            else
+            {
+                //濡傛灉杩欎釜缃戝叧杩樻病鏈夌粦瀹氱殑璇濓紝鍒欏己鍒朵娇鐢ㄦ湰鍦拌繛鎺�
+                realWay.SendLocation("Logic/SetSite", System.Text.Encoding.UTF8.GetBytes(jObject.ToString()));
+            }
+
+            int TimeOut = 0;
+            while (result == -1 && TimeOut < 30)
+            {
+                System.Threading.Thread.Sleep(100);
+                TimeOut++;
+            }
+
+            realWay.Actions -= action;
+            if (result != 0)
+            {
+                //璁剧疆缃戝叧缁忕含搴﹀け璐�
+                string msg = Language.StringByID(R.MyInternationalizationString.uSetGatewaySiteFail);
+                if (result == -1)
+                {
+                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "鍥炲瓒呮椂");
+                }
+                this.ShowTipMsg(msg);
+                return false;
+            }
+
+            return true;
+        }
+
+        #endregion
+
         #region 鈻� 瑙g粦浜戠缃戝叧_______________________
 
         /// <summary>
@@ -1883,7 +2282,7 @@
             //鑾峰彇鎺у埗涓讳汉璐﹀彿鐨凾oken
             Pra.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
 
-            List<string> listNotShowError = new List<string>() { "NoExist", "NoBind", "NoRecord" };
+            List<string> listNotShowError = new List<string>() { "NoExist", "NoBind", "NoRecord", "NotSetAgain" };
 
             bool result = await UserCenterLogic.GetResultStatuByRequestHttps("App/ReleaseGatewayToHome", true, Pra, listNotShowError);
             if (result == false)
@@ -2024,6 +2423,7 @@
         {
             //鑾峰彇浠庝簯绔偅閲屽緱鏉ョ殑鍏ㄩ儴鏂囦欢
             var listBackFile = HdlAutoBackupLogic.GetFileFromDirectory(UserCenterLogic.CombinePath(backDirectory));
+            listBackFile.Sort();
             //娣诲姞闄勫姞鎯呮姤:杩樺師璁惧閰嶇疆
             ProgressBar.SetAppendText(Language.StringByID(R.MyInternationalizationString.uRecoverDeviceSettion));
             ProgressBar.SetMaxValue(listBackFile.Count);
@@ -2032,7 +2432,7 @@
             var listSaveFile = new HashSet<string>();
             foreach (string fileName in listBackFile)
             {
-                if (fileName.Length < 10 || fileName.StartsWith(Common.LocalDevice.deviceFirstName) == false)
+                if (fileName.Length < 10 || fileName.StartsWith("Device_") == false)
                 {
                     //涓嶆槸璁惧澶囦唤鏂囦欢
                     continue;
@@ -2092,7 +2492,7 @@
                 if (deleteFile.Length > 12)
                 {
                     string deviceFileName = deleteFile.Substring(5);
-                    if (deviceFileName.StartsWith(Common.LocalDevice.deviceFirstName) == false)
+                    if (deviceFileName.StartsWith("Device_") == false)
                     {
                         //涓嶆槸璁惧鏂囦欢
                         continue;
@@ -2151,19 +2551,19 @@
             else if (backType == GatewayBackupEnum.APir鐏厜閰嶇疆)
             {
                 var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<IASZone.ConfigureParamates>(System.Text.Encoding.UTF8.GetString(byteData));
-                result = await HdlPirSensorLogic.Current.SetPirSensorLightSettion((IASZone)device, recoverData);
+                result = await HdlDevicePirSensorLogic.Current.SetPirSensorSettion((IASZone)device, recoverData);
             }
             else if (backType == GatewayBackupEnum.A骞叉帴鐐归鑹茶皟鑺�)
             {
                 var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<Panel.KeyColorData>(System.Text.Encoding.UTF8.GetString(byteData));
-                result = await HdlPanelLogic.Current.SetPanelEpointColorInfo((Panel)device, recoverData);
+                result = await HdlDevicePanelLogic.Current.SetPanelEpointColorInfo((Panel)device, recoverData);
             }
             else if (backType == GatewayBackupEnum.A骞叉帴鐐逛寒搴﹁皟鑺�)
             {
                 var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(System.Text.Encoding.UTF8.GetString(byteData));
                 int directionsLevel = Convert.ToInt32(recoverData["directionsLevel"]);
                 int backlightLevel = Convert.ToInt32(recoverData["backlightLevel"]);
-                result = await HdlPanelLogic.Current.SetDeviceLightSettion((Panel)device, directionsLevel, backlightLevel);
+                result = await HdlDevicePanelLogic.Current.SetDeviceLightSettion((Panel)device, directionsLevel, backlightLevel);
             }
             else if (backType == GatewayBackupEnum.A骞叉帴鐐硅妭鑳芥ā寮�)
             {
@@ -2171,16 +2571,119 @@
                 bool modeEnable = Convert.ToBoolean(recoverData["modeEnable"]);
                 int modeTime = Convert.ToInt32(recoverData["modeTime"]);
                 int level = Convert.ToInt32(recoverData["level"]);
-                result = await HdlPanelLogic.Current.SetDeviceEnergyConservationMode((Panel)device, modeEnable, modeTime, level);
+                result = await HdlDevicePanelLogic.Current.SetDeviceEnergyConservationMode((Panel)device, modeEnable, modeTime, level);
             }
-            else if (backType == GatewayBackupEnum.A骞叉帴鐐圭鏈夊睘鎬�)
+            else if (backType == GatewayBackupEnum.A骞叉帴鐐圭涓夌骇鍒鏈夊睘鎬�)
             {
                 var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(System.Text.Encoding.UTF8.GetString(byteData));
-                result = await HdlPanelLogic.Current.EditorDryContactFunction((Panel)device, recoverData);
+                result = await HdlDevicePanelLogic.Current.EditorDryContactThirdFunction((Panel)device, recoverData);
+            }
+            else if (backType == GatewayBackupEnum.A绐楀笜鏂瑰悜)
+            {
+                var statu = Newtonsoft.Json.JsonConvert.DeserializeObject<bool>(System.Text.Encoding.UTF8.GetString(byteData));
+                result = await HdlDeviceCurtainLogic.Current.SetCurtainDirection((Rollershade)device, statu);
+            }
+            else if (backType == GatewayBackupEnum.A绐楀笜鎵嬫媺鎺у埗)
+            {
+                var statu = Newtonsoft.Json.JsonConvert.DeserializeObject<bool>(System.Text.Encoding.UTF8.GetString(byteData));
+                result = await HdlDeviceCurtainLogic.Current.SetHandPullControl((Rollershade)device, statu);
+            }
+            else if (backType == GatewayBackupEnum.A绐楀笜涓婁笅闄愪綅)
+            {
+                var curtainDevice = (Rollershade)device;
+                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(System.Text.Encoding.UTF8.GetString(byteData));
+                int upLimit = Convert.ToInt32(recoverData["upLimit"]);
+                int downLimit = Convert.ToInt32(recoverData["downLimit"]);
+                //鍏堥噸缃獥甯�
+                result = await HdlDeviceCurtainLogic.Current.RestoreCurtain(curtainDevice);
+                if (result == false) { return -1; }
+                await Task.Delay(5000);
+                //閲嶇疆涓婇檺浣�
+                result = await HdlDeviceCurtainLogic.Current.DeleteCurtainLimitPoint(curtainDevice, Rollershade.LimiType.UpLimit);
+                if (result == false) { return -1; }
+                //灏嗙獥甯樿皟鏁村埌鎸囧畾鐧惧垎姣�
+                curtainDevice.WcdGoToTiltValue(upLimit);
+                await Task.Delay(3000);
+                //鎵ц纭鍙婅鐩栫獥甯橀檺浣嶇偣
+                result = await HdlDeviceCurtainLogic.Current.CommitCurtainLimitPoint(curtainDevice, Rollershade.CurtainPrivateInstalledLimi.UpLimit, -1, -1);
+                if (result == false) { return -1; }
+
+                await Task.Delay(2000);
+                //閲嶇疆涓嬮檺浣�
+                result = await HdlDeviceCurtainLogic.Current.DeleteCurtainLimitPoint(curtainDevice, Rollershade.LimiType.DownLimit);
+                if (result == false) { return -1; }
+                //灏嗙獥甯樿皟鏁村埌鎸囧畾鐧惧垎姣�
+                curtainDevice.WcdGoToTiltValue(downLimit);
+                await Task.Delay(3000);
+                //鎵ц纭鍙婅鐩栫獥甯橀檺浣嶇偣
+                result = await HdlDeviceCurtainLogic.Current.CommitCurtainLimitPoint(curtainDevice, Rollershade.CurtainPrivateInstalledLimi.DownLimit, -1, -1);
+            }
+            else if (backType == GatewayBackupEnum.A绌鸿皟鑷畾涔夋ā寮�)
+            {
+                var data = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(System.Text.Encoding.UTF8.GetString(byteData));
+                result = await HdlDeviceAirConditionerLogic.Current.SetAcModeSupport((AC)device, data);
+                if (result == true)
+                {
+                    //杞崲涓轰簩杩涘埗
+                    var value = Convert.ToString(data, 2).PadLeft(16, '0');
+                    //杩欎簲涓缃槸鏀惧湪鍚庨潰鐨�
+                    var fixValue = value.Substring(0, value.Length - 5);
+                    var reportValue = value.Substring(fixValue.Length);
+                    //鏇存敼缂撳瓨
+                    for (int i = 0; i < reportValue.Length; i++)
+                    {
+                        ((AC)device).listSupportMode[i] = Convert.ToInt32(reportValue[i]);
+                    }
+                    device.ReSave();
+                }
             }
             return result == true ? 1 : -1;
         }
 
         #endregion
+
+        #region 鈻� 涓�鑸柟娉昣__________________________
+
+        /// <summary>
+        /// 寮瑰嚭缃戝叧涓嶅湪绾跨殑
+        /// </summary>
+        private void ShowGatewayNotOnlineMsg()
+        {
+            Application.RunOnMainThread(() =>
+            {
+                //缃戝叧杩炴帴澶辫触,璇风‘璁ょ綉缁�
+                string msg = Language.StringByID(R.MyInternationalizationString.uGatewayIsNotLinkAndCheckNetwork);
+                var control = new ShowMsgControl(ShowMsgType.Tip, msg);
+                control.Show();
+            });
+        }
+
+        /// <summary>
+        /// 鏄剧ず閿欒淇℃伅绐楀彛
+        /// </summary>
+        /// <param name="msg"></param>
+        private void ShowErrorMsg(string msg)
+        {
+            Application.RunOnMainThread(() =>
+            {
+                var contr = new ShowMsgControl(ShowMsgType.Error, msg);
+                contr.Show();
+            });
+        }
+
+        /// <summary>
+        /// 鏄剧ずTip淇℃伅绐楀彛
+        /// </summary>
+        /// <param name="msg"></param>
+        private void ShowTipMsg(string msg)
+        {
+            Application.RunOnMainThread(() =>
+            {
+                var contr = new ShowMsgControl(ShowMsgType.Tip, msg);
+                contr.Show();
+            });
+        }
+
+        #endregion
     }
 }

--
Gitblit v1.8.0