wxr
2022-06-13 acf6f2bfdd9c4fa2500cc746e1064f375dc633d1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
using Shared;
 
namespace Shared.SimpleControl.Phone
{
    public class MigrationServer
    {
        /// <summary>
        /// 标记完成迁移
        /// </summary>
        private bool finish = false;
 
        private string SeverAddr = "https://bahrain-gateway.hdlcontrol.com";
        //private string SeverAddr = "https://test-gz.hdlcontrol.com";
 
        FrameLayout contentView;
 
        Button btnTipTitle;
        Button btnTipMsg;
 
        Loading loading;
 
        EditText etPwd;
        string pwd;
        string newUserId;
 
        Button btnSave;
 
 
        public MigrationServer ()
        {
            loading = new Loading (); 
        }
 
 
 
        public void ShowDialog()
        {
 
            #region 弹窗
            Dialog dialog = new Dialog ();
 
            FrameLayout dialogBodyView = new FrameLayout () {
                Gravity = Gravity.Center,
                Width = Application.GetRealWidth (500),
                Height = Application.GetRealHeight (500),
                BackgroundColor = SkinStyle.Current.DialogColor,
                Radius = 5,
                BorderColor = SkinStyle.Current.Transparent,
                BorderWidth = 0,
            };
            dialog.AddChidren (dialogBodyView);
 
            Button btnTitle = new Button () {
                Height = Application.GetRealHeight (80),
                BackgroundColor = SkinStyle.Current.DialogTitle,
                TextAlignment = TextAlignment.Center,
                TextID = R.MyInternationalizationString.Tip,
                TextColor = SkinStyle.Current.DialogTextColor
            };
            dialogBodyView.AddChidren (btnTitle);
 
            contentView = new FrameLayout () {
                Y = Application.GetRealHeight (80),
                Height = Application.GetRealHeight (340),
                BackgroundColor = SkinStyle.Current.DialogColor,
            };
            dialogBodyView.AddChidren (contentView);
 
            btnTipTitle = new Button () {
                Gravity = Gravity.CenterHorizontal,
                Y = Application.GetRealHeight (20),
                Width = Application.GetRealWidth (400),
                Height = Application.GetRealHeight (80),
                Text = "请输入密码,确认迁移",
                TextAlignment = TextAlignment.CenterLeft,
                TextColor = SkinStyle.Current.TextColor,
                IsMoreLines = true,
            };
            contentView.AddChidren (btnTipTitle);
 
            etPwd = new EditText () {
                Gravity = Gravity.CenterHorizontal,
                Y = btnTipTitle.Bottom,
                Width = Application.GetRealWidth (400),
                Height = Application.GetRealHeight (80),
                TextAlignment = TextAlignment.Center,
                Radius = 5,
                BorderColor = SkinStyle.Current.BorderColor,
                BorderWidth = 1,
                TextColor = SkinStyle.Current.TextColor,
                SecureTextEntry = true
            };
            contentView.AddChidren (etPwd);
            etPwd.EditorEnterAction += (obj) => {
                Application.HideSoftInput ();
            };
 
            btnTipMsg = new Button () {
                Gravity = Gravity.CenterHorizontal,
                Y = etPwd.Bottom,
                Width = Application.GetRealWidth (400),
                Height = Application.GetRealHeight (80),
                TextAlignment = TextAlignment.CenterLeft,
                TextColor = SkinStyle.Current.DelColor,
                IsMoreLines = true,
            };
            contentView.AddChidren (btnTipMsg);
 
 
            dialogBodyView.AddChidren (loading);
 
            FrameLayout bottomView = new FrameLayout () {
                Y = Application.GetRealHeight (420),
                Height = Application.GetRealHeight (85),
                BackgroundColor = SkinStyle.Current.DialogTitle
            };
            dialogBodyView.AddChidren (bottomView);
 
            Button btnClose = new Button () {
                Width = Application.GetRealWidth (249),
                TextID = R.MyInternationalizationString.Close,
                TextAlignment = TextAlignment.Center
            };
            bottomView.AddChidren (btnClose);
            btnClose.MouseUpEventHandler += (send2er, e2) => {
                dialog.Close ();
            };
 
            Button btnBottomLine = new Button () {
                X = btnClose.Right,
                Width = 1,
                BackgroundColor = SkinStyle.Current.Black50Transparent,
            };
            bottomView.AddChidren (btnBottomLine);
 
            btnSave = new Button () {
                X = btnBottomLine.Right,
                Width = Application.GetRealWidth (249),
                TextID = R.MyInternationalizationString.Confrim,
                TextAlignment = TextAlignment.Center
            };
            bottomView.AddChidren (btnSave);
            etPwd.TextChangeEventHandler = (sender, e) => {
                btnTipMsg.Text = "";
            };
 
            btnSave.MouseUpEventHandler += (sender2, e2) => {
                if (finish) {
                    dialog.Close ();
                    return;
                }
 
#if DEBUG
                //WriteSecretKey (1, 0, new byte [] {1,1,2,3,2,3,4,5,2,3,5,6 });
                //CheckGateway ();
 
                //var newHomeId = Home2New ();
                //if (newHomeId == "") { } else { }
                //Account2New (etPwd.Text.Trim());
 
                //return;
#endif
 
                if (etPwd.Text.Trim() == "") {
                    btnTipMsg.Text = "请输入密码";
                    return;
                }
 
                loading.Start ("");
                pwd = etPwd.Text.Trim ();
 
                //验证密码
                new System.Threading.Thread (() => {
                    try {
                        var verResult = AcountVer (pwd);
                        if (verResult) {
                            Application.RunOnMainThread (() => {
                                btnTipMsg.Text = "验证通过,正在检测网关配置";
                                btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                CheckGateway (); 
                            });
                        } else {
                            Application.RunOnMainThread (() => {
                                btnTipMsg.Text = "密码错误,验证失败,请重试。";
                                loading.Hide ();
                            });
                        }
                    } catch {
                        Application.RunOnMainThread (() => {
                            loading.Hide ();
                        });
                    } finally {
                        
                    }
                }) { IsBackground = true }.Start ();
 
 
            };
            dialog.Show ();
 
 
 
            if (MainPage.WiFiStatus != "CrabtreeAdd/WiFi.png") {
                //status = btnSave.Text = "ReCheck";
                btnTipMsg.Text = "请在局域网内连接网关设备";
                etPwd.Visible = false;
                btnSave.MouseUpEventHandler = (sender2, e2) => {
                    dialog.Close ();
                };
            } else {
 
 
 
            }
 
 
 
            //2.进入网关升级模式
            //3.接收升级文件获取请求
            //迁移账号
 
            #endregion
 
 
 
        }
 
        #region 云端
        /// <summary>
        /// 账号登录验证
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        private bool AcountVer(string pwd)
        {
            var requestObj = new LoginObj () { Account = MainPage.LoginUser.AccountString, Password = pwd, Company = MainPage.SoftSmsType };
            var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj);
            var revertObj = MainPage.RequestHttps ("Login", requestJson, false);
            if (revertObj.StateCode == "SUCCESS") {
                return true;
            } else {
                return false;
            }
        }
        /// <summary>
        /// 账号迁移
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public bool Account2New (string pwd)
        {
            Dictionary<string, object> dicAccount = new Dictionary<string, object> ();
            dicAccount.Add ("email", MainPage.LoginUser.AccountString);
            dicAccount.Add ("language", "ENGLISH");
            dicAccount.Add ("appCode", "HDL-HOME-IND-APP");
            dicAccount.Add ("pwd", pwd);
            dicAccount.Add ("tenantId", "202106");
            var requestJson = HttpUtil.GetSignRequestJson (dicAccount);// Newtonsoft.Json.JsonConvert.SerializeObject (dicAccount);
            var revertObj2 = MainPage.RequestHttps ("/home-wisdom/data/move/user/save", requestJson, false, false, SeverAddr);
            if (revertObj2.code == "0") {
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<MoveAccountResult> (revertObj2.data.ToString ());
                if (info != null) {
                    newUserId = info.memberId;
                }
                return true;
            } else {
                return false;
            }
        }
        /// <summary>
        /// 住宅迁移
        /// </summary>
        /// <returns>new homeId</returns>
        private string Home2New ()
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("homeName", UserConfig.Instance.CurrentRegion.RegionName);
            dic.Add ("userId", newUserId);
            dic.Add ("homeType", "BUSPRO");
            dic.Add ("tenantId", "202106");
            var requestJson = HttpUtil.GetSignRequestJson (dic);// Newtonsoft.Json.JsonConvert.SerializeObject (dic);
            var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/home/save", requestJson, false, false, SeverAddr);
            if (revertObj != null) {
                if (revertObj.data != null) {
                    var newHomeInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Move_HomeInfo> (revertObj.data.ToString ());
                    return newHomeInfo.homeId;
                }
            }
            return "";
        }
        /// <summary>
        /// 迁移网关
        /// </summary>
        /// <param name="mac"></param>
        /// <param name="newHomeId">新平台的住宅id</param>
        /// <returns></returns>
        private bool Gateway2New (string mac,string newHomeId)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("mac", mac);
            dic.Add ("homeId", newHomeId);
            dic.Add ("userId", newUserId);
            dic.Add ("gatewayType", 0);
 
            dic.Add ("tenantId", "202106");
            var requestJson = HttpUtil.GetSignRequestJson (dic);
            
            var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/gateway/save", requestJson, false, false, SeverAddr);
            if (revertObj!= null && revertObj.code == "0") {
                return true;
            } 
            return false;
        }
        /// <summary>
        /// 获取上网密秘钥
        /// </summary>
        /// <returns></returns>
        private string GetInternetAccessKey (string mac)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("supplier", "HDL");
            dic.Add ("mac", mac);
            dic.Add ("spk", "BUSUDPGATEWAY");
            var requestJson = HttpUtil.GetSignRequestJson (dic);
 
            //var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (dic);
            var revertObj = MainPage.RequestHttps ("/smart-open/third/device/authByMac", requestJson, false, false, SeverAddr);
            if (revertObj.code == "0") {
                return revertObj.data.ToString ();
            } else { }
            return "";
        }
 
        /// <summary>
        /// 迁移备份
        /// </summary>
        /// <param name="newHomeId"></param>
        /// <param name="newUserId"></param>
        /// <returns></returns>
        private string moveFolder2New (string newHomeId,string newUserId)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("backupDataType", "HDL_ON");
            dic.Add ("homeId",newHomeId);
            dic.Add ("userId",newUserId);
            dic.Add ("backupClassify", "USER_DEFINED_BACKUP");
            dic.Add ("folderName", "迁移备份" + DateTime.Now.ToString ());
            dic.Add ("tenantId", "202106");
            var requestJson = HttpUtil.GetSignRequestJson (dic);
            var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/folder/save", requestJson, false, false, SeverAddr);
            if(revertObj!= null) {
                if(revertObj.code == "0") {
                    var resultObj = Newtonsoft.Json.JsonConvert.DeserializeObject<FolderObj> (revertObj.data.ToString ());
                    
                    return resultObj.id;
                }
            }
            Application.RunOnMainThread (() => {
                btnTipTitle.Text = "备份迁移失败.";
                btnTipTitle.TextColor = SkinStyle.Current.DelColor;
            });
            return "";
        }
 
 
        private string MoveFile2New(string newHomeId, string newUserId,string backupId)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("backupId", backupId);//1534728347497418754//1534728860322385922
            dic.Add ("homeId", newHomeId);
            dic.Add ("userId", newUserId);
            dic.Add ("backupClassify", "USER_DEFINED_BACKUP");
            dic.Add ("tenantId", "202106");
 
            List<BackupFileObj> fileObjs = new List<BackupFileObj> ();
 
            var backuplist = IO.FileUtils.ReadFiles ();
            int index = 0;
            foreach (var fileName in backuplist) {
                index++;
                /// <summary>
                /// 如果是特殊的注册登陆文件,则不需要备份到服务器
                /// </summary>
                if (fileName == UserInfo.GlobalRegisterFile) {
                    continue;
                }
                BackupFileObj backupFileObj = new BackupFileObj () { fileName = fileName, content = IO.FileUtils.ReadFile (fileName) };
                fileObjs.Add (backupFileObj);
 
                if(fileObjs.Count > 9) {
                    if (!dic.ContainsKey ("list")) {
                        dic.Add ("list", fileObjs);
                    //} else {
                    //    dic ["list"] = fileObjs;
                    }
                    var json = HttpUtil.GetSignRequestJson (dic);
                    var revertObj_foreach = MainPage.RequestHttps ("/home-wisdom/data/move/file/save", json, false, false, SeverAddr);
                    if(revertObj_foreach!= null) {
                        if(revertObj_foreach.code == "0") {
                            fileObjs.Clear ();
                            continue;
                        }
                    }
                }
            }
            if (!dic.ContainsKey ("list")) {
                dic.Add ("list", fileObjs);
                //} else {
                //    dic ["list"] = fileObjs;
            }
            var requestJson = HttpUtil.GetSignRequestJson (dic);
            var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/file/save", requestJson, false, false, SeverAddr);
            if (revertObj != null) {
                if (revertObj.code == "0") {
                    return "true";
                }
            }
            return "";
        }
        /// <summary>
        /// 标记2.0平台数据
        /// </summary>
        /// <returns></returns>
        private bool Mark(string newHomeId)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("homeId", newHomeId);
            dic.Add ("mark", false);
            var requestJson = HttpUtil.GetSignRequestJson (dic);
            var revertObj = MainPage.RequestHttps ("/home-wisdom/app/home/markVoice", requestJson, false, false, SeverAddr);
            if (revertObj != null) {
                if(revertObj.code == "0") {
                    if(revertObj.data.ToString() == "true") {
                        return true;
                    }
                }
            }
            return false;
        }
 
        #endregion
 
        /// <summary>
        /// 检测一端口信息
        /// </summary>
        /// <param name="btnTipMsg"></param>
        /// <param name="btnSave"></param>
        public void CheckGateway()
        {
            Application.RunOnMainThread (() => {
                loading.Start ("");
            });
            new System.Threading.Thread (() => {
                //1.检测一端口固件
                var localFileList = IO.FileUtils.ReadFiles ();
                var gateWayList = localFileList.FindAll ((obj) => {
                    return (obj.StartsWith ("Equipment_")) && (
                     obj.Split ('_') [1].ToString () == DeviceType.OnePortBus.ToString () ||
                        obj.Split ('_') [1].ToString () == DeviceType.RCU.ToString () ||
                        obj.Split ('_') [1].ToString () == DeviceType.OnePortWirelessFR.ToString ());
                });
                List<string> linkList = new List<string> ();
                GatewayBase common = null;
                string gateWayString = "";
                if (gateWayList.Count > 0) {
                    foreach (var gatewayFileName in gateWayList) {
                        var tempStrings = gatewayFileName.Split ('_');
                        if (tempStrings [1].ToString () == DeviceType.OnePortBus.ToString () || tempStrings [1].ToString () == DeviceType.RCU.ToString () ||
                            tempStrings [1].ToString () == DeviceType.OnePortWirelessFR.ToString ()) {
                            gateWayString = CommonPage.MyEncodingUTF8.GetString (IO.FileUtils.ReadFile (gatewayFileName));
                            common = Newtonsoft.Json.JsonConvert.DeserializeObject<GatewayBase> (gateWayString);
 
 
                            var bytes = Control.ControlBytesSendHasReturn (Command.readGatewayVision, common.SubnetID, common.DeviceID, new byte [] { });
                            if(bytes == null) {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "无法搜索到网关,请确定是否与网关在同一网络。";
                                    btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                    loading.Hide ();
                                });
                                return;
                            } else {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "网关连接成功,正在检查网关固件。";
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                });
                            }
                            var visionString = Encoding.GetEncoding ("gb2312").GetString (bytes);
 
 
                            int result = -99;
 
 
                            if (visionString.Contains( "Ind_V03.01U_2021/07/12")) {//FW_MCIP-L1_RF.01_V03.01_210712_STM32F107VCT6_U2_india_beta") {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "网关固件已升级,正在初始化网关";
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                });
                                result = 100;
                            } else {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "正在升级网关";
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                });
                                //需要升级一端口
                                List<List<byte>> upgradeData = ReadUpgradeData ();
 
                                for (int i = 0; i < 7; i++) {
                                    Control.ControlBytesSend (Command.enjoyUpgrade, common.SubnetID, common.DeviceID, new byte [] { });
                                }
                                byte [] arrayTemp = new byte [4];
                                arrayTemp [0] = Convert.ToByte ((upgradeData.Count & 0xFF000000) >> 24);
                                arrayTemp [1] = Convert.ToByte ((upgradeData.Count & 0xFF0000) >> 16);
                                arrayTemp [2] = Convert.ToByte ((upgradeData.Count & 0xFF00) >> 8);
                                arrayTemp [3] = Convert.ToByte (upgradeData.Count & 0xFF);
                                //丢失次数
                                int lostCount = 0;
 
                                while (true) {
                                    var ub = MainPage.GatewayStatus.Split ("_");
                                    if (ub.Length > 1) {
                                         result = Convert.ToInt32 (ub [1]);
                                        //if (result < result0 && result0 < 100)
                                        {
                                            //result = result0;
                                            Application.RunOnMainThread (() => {
                                                btnTipMsg.Text = "正在升级网关 " + result + "/" + upgradeData.Count;
                                            });
                                        }
                                    }
                                    if (MainPage.GatewayStatus.Contains ("upgrading") && result == 0) {
                                        SendUpgradeData (common.SubnetID, common.DeviceID, arrayTemp);
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "正在升级网关 " + result + "/" + upgradeData.Count;
                                        });
                                    } else if (result == -99) {
                                        System.Threading.Thread.Sleep (100);
                                        continue;
                                    } else if (result == 100) {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "网关升级成功.正在初始化网关";
                                            btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                        });
                                        break;
                                    }
 
 
                                     //if (result == -1) {
                                     //    if (lostCount > 3) {
                                     //        Application.RunOnMainThread (() => {
                                     //            btnTipMsg.Text = "网关升级失败,请重试.";
                                     //            loading.Hide ();
                                     //        });
                                     //        return;
                                     //    }
                                     //} else if (result == -2) {
                                     //    if (lostCount > 3) {
                                     //        Application.RunOnMainThread (() => {
                                     //            btnTipMsg.Text = "网关无响应。";
                                     //            loading.Hide ();
                                     //        });
                                     //        return;
                                     //    }
                                     //} else if (result == 999999) {
                                     //    Application.RunOnMainThread (() => {
                                     //        btnTipMsg.Text = "网关升级成功.正在初始化网关";
                                     //        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                     //    });
                                     //    break;
                                     //}
                                     else {
                                        if (upgradeData.Count >= result) {
                                            var listPack = upgradeData [result-1];//
                                            byte [] packData = new byte [2 + listPack.Count];
                                            packData [0] = Convert.ToByte (result / 256);
                                            packData [1] = Convert.ToByte (result % 256 );
                                            Array.Copy (listPack.ToArray (), 0, packData, 2, listPack.Count);
                                            Console.WriteLine ("packId"+result);
                                            SendUpgradeData (common.SubnetID, common.DeviceID, packData);
 
                                        }
                                    }
                                }
                            }
 
 
 
                            if (result == 100) {
 
                                //初始化网关
                                var initialBytes = new byte [12];
                                initialBytes [0] = 0x00;
                                initialBytes [1] = 0x00;
 
                                string [] mac = common.MAC.Split ('.');
                                for (int i = 0; i < mac.Length; i++)
                                    initialBytes [i + 2] = Convert.ToByte (mac [i], 16);
 
 
                                initialBytes [10] = Convert.ToByte (common.SubnetID);
                                initialBytes [11] = 0x00;
                                //初始化网关命令发送
                                InitializationGateway (common.SubnetID, common.DeviceID, initialBytes);
                                while (true) {
                                    if (MainPage.GatewayStatus != "Initialization_complete") {
                                        System.Threading.Thread.Sleep (100);
                                    } else {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "初始化网关成功,正在打开网关远程配置。";
                                            btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                        });
                                        break;
                                    }
                                }
                                //开启网关远程
                                var setRemoteResult = SetGatewayRemote (common.SubnetID, common.DeviceID);
                                if (setRemoteResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "网关远程已开启,正在迁移账号信息。";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "网关远程开启失败。";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                    });
                                    return;
                                }
 
                                //迁移账号
                                var moveAccontResult = Account2New (pwd);
                                if (moveAccontResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "账号信息迁移成功,正在迁移住宅。";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "账号迁移失败。";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                    });
                                    return;
                                }
                                //迁移住宅,获取新的homeid
                                var newHomeId = Home2New ();
                                if (newHomeId == "") {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "住宅迁移失败。";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                    return;
                                } else {
                                    btnTipMsg.Text = "住宅迁移成功,正在配置网关住宅信息。";
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                }
 
                                //写入homeId
                                var homeIdSendBytes = new byte [73];
                                var homeIdByte = new byte [36];
                                var homeStrs = newHomeId;// UserConfig.Instance.CurrentRegion.RegionID.ToString ();//需要使用新平台生成的homeId
                                for (int i = 0; i < UserConfig.Instance.CurrentRegion.RegionID.ToString ().Length; i++) {
                                    homeIdByte [i] = Convert.ToByte (homeStrs [i].ToString (), 16);
                                }
                                Array.Copy (homeIdByte, homeIdSendBytes, homeIdByte.Length);
                                var writeHomeIdResult = WriteHomeId (common.SubnetID, common.DeviceID, homeIdSendBytes);
                                if (writeHomeIdResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "网关住宅信息配置成功,正在获取上网秘钥。";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "网关住宅信息配置失败.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                    });
                                }
                                //获取上网秘钥
                                var netKet = GetInternetAccessKey (common.MAC.Replace (".", ""));
 
                                if (!string.IsNullOrEmpty (netKet)) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "获取上网秘钥成功。正在写入";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                    var secretkeySendBytes = new byte [netKet.Length + 1];
                                    var secretkeyByte = new byte [netKet.Length];
                                    for (int i = 0; i < netKet.Length; i++) {
                                        secretkeyByte [i] = Convert.ToByte (netKet [i].ToString (), 16);
                                    }
                                    Array.Copy (secretkeyByte, 0, secretkeySendBytes, 1, secretkeyByte.Length);
                                    secretkeySendBytes [0] = 1;
                                    //写入上网秘钥
                                    var writeSecretKeyResult = WriteSecretKey (common.SubnetID, common.DeviceID, secretkeySendBytes);
                                    if (writeSecretKeyResult) {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "上网秘钥写入成功,正在迁移网关。";
                                        });
                                    } else {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "上网秘钥写入失败。";
                                            btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                            return;
                                        });
                                    }
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "上网秘钥获取失败。";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                    });
                                }
                                //迁移网关
                                var moveGatewayResult = Gateway2New (common.MAC.Replace (".", ""), newHomeId);
                                if (moveGatewayResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "网关迁移成功,正在迁移备份数据。";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "网关迁移失败。";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                    return;
                                }
                                //创建迁移备份文件夹
                                var backId = moveFolder2New (newHomeId, newUserId);
                                //迁移备份文件
                                var moveFileResult = MoveFile2New (newHomeId, newUserId, backId);
                                if (moveFileResult == "true") {
                                    //标记流程完成
                                    //var markResult = Mark (newHomeId);
                                    //if (markResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipTitle.Text = "备份数据迁移成功,平台迁移完成。";
                                        //btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                        btnTipMsg.Text = "";
                                        etPwd.Visible = false;
                                        loading.Hide ();
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "备份数据迁移失败。";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                }
                                //}
 
                            }
 
 
                            Application.RunOnMainThread (() => {
                            });
 
                            break;//只升级一个
                        }
                    }
                } else {
                    //没有网关
                    Application.RunOnMainThread (() => {
                        btnTipTitle.Text = "未检测到网关,请检查本地数据.";
                    });
                    return;
                }
            }) { IsBackground = true }.Start ();
            //Control.ControlBytesSend (Command.enjoyUpgrade2, common.SubnetID, common.DeviceID, new byte [] { });
        }
 
        /// <summary>
        /// 读取固件数据
        /// </summary>
        /// <returns></returns>
        private static List<List<byte>> ReadUpgradeData ()
        {
            byte [] buffer = new byte [1024];
            List<List<byte>> upgradeData = new List<List<byte>> ();
            System.IO.Stream stream = Application.Activity.Assets.Open ("FW_MCIP-L1_RF.01_V03.01_210712_STM32F107VCT6_U2_india_beta.bin");
            int length = 0;
            try {
                while ((length = stream.Read (buffer, 0, buffer.Length)) != 0) {
                    List<byte> bbb = new List<byte> ();
                    for (int i = 0; i < length; i++) {
                        bbb.Add (buffer [i]);
                    }
                    upgradeData.Add (bbb);
                }
            } catch {
            } finally {
                stream.Close ();
            }
 
            return upgradeData;
        }
        /// <summary>
        /// 发送网关固件数据
        /// </summary>
        /// <param name="subnetId"></param>
        /// <param name="deviceId"></param>
        /// <param name="sendByets"></param>
        /// <returns></returns>
        public void SendUpgradeData (byte subnetId,byte deviceId,byte[] sendByets)
        {
            var resutl = Control.ControlBytesSendHasReturn (Command.enjoyUpgrade2, subnetId, deviceId, sendByets);
            //if(resutl == null) {
            //    return -2;
            //}
            //if (resutl.Length == 0) {
            //    return -1;
            //}
            //if (resutl [0] == 0xF8) {
            //    return 999999;
            //} else {
            //    if (resutl.Length > 1) {
            //        var packId = resutl [0] * 256 + resutl [1];
            //        Console.WriteLine ("packId:"+packId);
            //        return packId;
            //    }
            //    return 1;
            //}
        }
 
        /// <summary>
        /// 初始化网关
        /// </summary>
        /// <param name="subnetId"></param>
        /// <param name="deviceId"></param>
        private void InitializationGateway(byte subnetId, byte deviceId, byte [] sendByets)
        {
            Control.ControlBytesSend (Command.InitializationGateway, subnetId, deviceId, sendByets);
 
        }
 
        /// <summary>
        /// 设备网关开启远程
        /// </summary>
        private bool SetGatewayRemote(byte subnetId, byte deviceId)
        {
            var sendByte = new byte [67];
            sendByte [0] = 4;
            var result = Control.ControlBytesSendHasReturn (Command.SetGateWayModelInfo, subnetId, deviceId, sendByte);
            if (result == null) {
 
            } else {
                if(result.Length>0 && result[0] == 248) {
                    return true;
                }
            }
            return false;
        }
 
        /// <summary>
        /// 写入homeId
        /// </summary>
        /// <param name="subnetId"></param>
        /// <param name="deviceId"></param>
        /// <param name="sendByets"></param>
        private bool WriteHomeId (byte subnetId, byte deviceId, byte [] sendByets)
        {
            var result = Control.ControlBytesSendHasReturn (Command.WriteHomeId, subnetId, deviceId, sendByets);
            if (result == null)
                return false;
            if (result.Length == 3) {
                if (result [2] == 0xF8) {
                    return true;
                }
            } else if (result.Length == 1) {
                if (result [0] == 0xF8) {
                    return true;
                }
            }
            return false;
        }
 
        
        /// <summary>
        /// 写入上网秘钥
        /// </summary>
        /// <param name="subnetId"></param>
        /// <param name="deviceId"></param>
        /// <param name="sendByets"></param>
        /// <returns></returns>
        private bool WriteSecretKey (byte subnetId, byte deviceId, byte [] sendByets)
        {
            var result = Control.ControlBytesSendHasReturn (Command.WriteSecretKey, subnetId, deviceId, sendByets);
            if (result!= null  ) {
                return true;
                //if (result.Length > 26) {
                //    if (result [26] == 0xF8) {
                //        return true;
                //    }
                //} else {
                //    if (result.Length > 3) {
                //        if (result [1] == 0xF8) {
                //            return true;
                //        }
                //    }
                //}
            }
            return false;
        }
 
        
    }
}