wxr
2022-08-30 a93db4940a37fd73a37dd9b237c16e744e36f9ea
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
using Shared;
 
namespace Shared.SimpleControl.Phone
{
    public class DeviceSecret
    {
        public string deviceSecret;
    }
 
    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;
        Button btnClose;
 
 
 
        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 = "Please enter the password to confirm the migration",
                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 (120),
                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);
 
            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
 
 
 
                var moveAccontResult = Account2New ("12345678");
                var newHomeId = Home2New ();
                //迁移网关
                var moveGatewayResult = Gateway2New ("4D59383553502243", newHomeId, 0);
#endif
 
                if (etPwd.Text.Trim() == "") {
                    btnTipMsg.Text = "Please input a password";
                    return;
                }
 
                loading.Start ("");
                pwd = etPwd.Text.Trim ();
 
                //验证密码
                new System.Threading.Thread (() => {
                    try {
                        var verResult = AcountVer (pwd);
                        if (verResult) {
                            Application.RunOnMainThread (() => {
                                btnTipMsg.Text = "Verification passed, detecting gateway configuration";
                                btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                CheckGateway (); 
                            });
                        } else {
                            Application.RunOnMainThread (() => {
                                btnTipMsg.Text = "Password error, verification failed, please try again.";
                                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 = "Please connect the gateway device in the LAN.";
                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,int subnetId)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("mac", mac);
            dic.Add ("homeId", newHomeId);
            dic.Add ("userId", newUserId);
            dic.Add ("subnetId",subnetId);
            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 ("/home-wisdom/program/device/secret/applyDeviceSecret", requestJson, false, false, SeverAddr);
            //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>
        /// <returns></returns>
        private string moveFolder2New (string newHomeId)
        {
            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", "MigrateBackup" + 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;
                }
            }
            return "";
        }
 
 
        private string MoveFile2New(string newHomeId,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);
                    }
                    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>
        /// 获取定时器列表
        /// </summary>
        /// <param name="newHomeId"></param>
        private List<BackupFileObj> GetTimer (string newHomeId)
        {
            var requestObj = new Timer () { RegionID = UserConfig.Instance.CurrentRegion.RegionID };
            var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj);
            var revertObj = MainPage.RequestHttps ("GetTimerList", requestJson);
            if (revertObj.StateCode == "SUCCESS") {
                var timers = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Timer>> (revertObj.ResponseData.ToString ());
                if(timers.Count > 0) {
                    List<BackupFileObj> backups = new List<BackupFileObj> ();
                    foreach (var timer in timers) {
                        var timerContent = System.Text.Encoding.UTF8.GetBytes (Newtonsoft.Json.JsonConvert.SerializeObject (timer));
                        BackupFileObj backupFileObj = new BackupFileObj () {
                            fileName = timer.TimerName,
                            content = timerContent
                        };
                        backups.Add (backupFileObj);
                    }
                    return backups;
                }
            } else {
                return null;
            }
            return new List<BackupFileObj> ();
        }
 
        /// <summary>
        /// 定时器备份
        /// </summary>
        /// <returns></returns>
        private string BackupSchedule (string newHomeId, List<BackupFileObj> backups)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("backupDataType", "HDL_ON");
            dic.Add ("homeId", newHomeId);
            dic.Add ("userId", newUserId);
            dic.Add ("backupClassify", "CUSTOM_PROJECT_BACKUP");
            dic.Add ("folderName", "ScheduleBackup" + 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 ());
                    var ddd =  MoveTimerFileData (newHomeId,resultObj.id, backups);
                    return ddd;
                }
            }
            return "";
        }
 
        /// <summary>
        /// 保存定时器数据
        /// </summary>
        /// <param name="newHomeId"></param>
        /// <param name="backupId"></param>
        /// <param name="fileObjs"></param>
        /// <returns></returns>
        private string MoveTimerFileData (string newHomeId, string backupId, List<BackupFileObj> fileObjs)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("backupId", backupId);
            dic.Add ("homeId", newHomeId);
            dic.Add ("userId", newUserId);
            dic.Add ("backupClassify", "CUSTOM_PROJECT_BACKUP");
            dic.Add ("tenantId", "202106");
            dic.Add ("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 "";
        }
 
 
 
        #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 = "The gateway cannot be searched. Please make sure it is on the same network as the gateway.";
                                    btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                    loading.Hide ();
                                });
                                return;
                            } else {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "Gateway connection succeeded. Checking gateway firmware.";
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                });
                            }
                            var visionString = Encoding.GetEncoding ("gb2312").GetString (bytes);
 
                            int result = -99;
 
                            if (visionString.Contains ("Ind_C03.02U_2022/06/22")) {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "Gateway firmware has been upgraded, initializing gateway.";
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                });
                                result = 100;
                            //} else if (!visionString.Contains ("Ind_V02.35U_2019/06/25")) {//目前只允许升级这个固件的网关
                            //    Application.RunOnMainThread (() => {
                            //        btnTipTitle.Text = "The gateway does not support automatic migration. Please contact technical support.";
                            //        btnTipTitle.Height = Application.GetRealHeight (150);
                            //        btnTipTitle.TextColor = SkinStyle.Current.DelColor;
                            //        btnTipMsg.Text = "";
                            //        etPwd.Visible = false;
                            //        loading.Hide ();
                            //        btnSave.Visible = false;
                            //        btnClose.Width = Application.GetRealWidth (500);
                            //    });
                            //    return;
                            } else {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "Upgrading gateway.";
                                    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);
 
                                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 = "Upgrading gateway " + result + "/" + upgradeData.Count;
                                            });
                                        }
                                    }
                                    if (MainPage.GatewayStatus.Contains ("upgrading") && result == 0) {
                                        SendUpgradeData (common.SubnetID, common.DeviceID, arrayTemp);
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "Upgrading gateway " + result + "/" + upgradeData.Count;
                                        });
                                    } else if (result == -99) {
                                        System.Threading.Thread.Sleep (100);
                                        continue;
                                    } else if (result == 100) {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "Gateway upgrade succeeded. Initializing gateway.";
                                            btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                        });
                                        //初始化标记
                                        MainPage.GatewayStatus = "";
                                        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);
 
                                        }
                                    }
                                }
                            }
                            //重新设置一下子网号
                            SetSubnetId (common);
                            System.Threading.Thread.Sleep (1000);
 
                            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);
                                int initiaIndex = 0;
                                while (true) {
                                    if (MainPage.GatewayStatus != "Initialization_complete") {
                                        System.Threading.Thread.Sleep (100);
                                    } else if (initiaIndex == 0) {
                                        //初始化标记
                                        MainPage.GatewayStatus = "";
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "Successfully initialized the gateway. Opening the gateway remote configuration.";
                                            btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                        });
                                        break;
                                    }
                                    initiaIndex++;
                                    if(initiaIndex > 200) {
                                        break;
                                    }
                                }
                                //开启网关远程
                                var setRemoteResult = SetGatewayRemote (common.SubnetID, common.DeviceID);
                                if (setRemoteResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "The gateway remote has been enabled, and the account information is being migrated.";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Gateway remote opening failed. Please try again.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                    return;
                                }
 
                                //迁移账号
                                var moveAccontResult = Account2New (pwd);
                                if (moveAccontResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "The account information is migrated successfully. The account is being migrated.";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Account migration failed. Please try again.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                    return;
                                }
                                //迁移住宅,获取新的homeid
                                var newHomeId = Home2New ();
                                if (newHomeId == "") {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Home migration failed. Please try again.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                    return;
                                } else {
                                    btnTipMsg.Text = "Residence migration succeeded. Gateway residence information is being configured.";
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                }
 
 
                                //写入homeId
                                var writeHomeIdResult = SetGateWayAdminInfo (common.SubnetID, newHomeId);
                                if (writeHomeIdResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "The gateway home information is configured successfully, and the Internet access key is being obtained.";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Gateway home information configuration failed. Please try again.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                        return;
                                    });
                                }
                                //获取上网秘钥
                                var netKet = GetInternetAccessKey (common.MAC.Replace (".", ""));
 
                                if (!string.IsNullOrEmpty (netKet)) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "The Internet access key was obtained successfully. It is being written.";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                    var deviceSecret = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceSecret> (netKet);
                                    var secretkeyByte = Encoding.UTF8.GetBytes (deviceSecret.deviceSecret);
                                    var secretkeySendBytes = new byte [secretkeyByte.Length + 1];
                                    secretkeySendBytes [0] = 1;
                                    Array.Copy (secretkeyByte, 0, secretkeySendBytes, 1, secretkeyByte.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;
                                    System.Threading.Thread.Sleep (10000);
                                    //写入上网秘钥
                                    var writeSecretKeyResult = WriteSecretKey (common.SubnetID, common.DeviceID, secretkeySendBytes);
                                    if (writeSecretKeyResult) {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "The Internet access key was written successfully. The gateway is being migrated.";
                                        });
                                    } else {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "Failed to write Internet secret key. Please try again.";
                                            btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                            loading.Hide ();
                                            return;
                                        });
                                    }
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Failed to obtain the Internet secret key. Please try again.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        return;
                                    });
                                }
                                //写入mqtt域名信息
                                SetGateWayMqttUrlAddress (common.SubnetID, common.DeviceID);
 
 
                                //迁移网关
                                var moveGatewayResult = Gateway2New (common.MAC.Replace (".", ""), newHomeId, common.SubnetID);
                                if (moveGatewayResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Gateway migration succeeded. The backup data is being migrated.";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Gateway migration failed. Please try again.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                    return;
                                }
                                //创建迁移备份文件夹
                                var backId = moveFolder2New (newHomeId);
                                //迁移备份文件
                                var moveFileResult = MoveFile2New (newHomeId, backId);
                                if (moveFileResult == "true") {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Migration backup succeeded, migrating Schedule data.";
                                        btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                    });
                                    //迁移定时器
                                    var timerList = GetTimer (newHomeId);
                                    if (timerList == null) {
                                        Application.RunOnMainThread (() => {
                                            btnTipMsg.Text = "Schedule migration failed. Please try again.";
                                            btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                            loading.Hide ();
                                            return;
                                        });
                                    } else {
                                        if (timerList.Count > 0) {
                                            var backupTimerResult = BackupSchedule (newHomeId, timerList);
                                            if (string.IsNullOrEmpty (backupTimerResult)) {
                                                btnTipMsg.Text = "Schedule migration failed.. Please try again.";
                                                btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                                loading.Hide ();
                                                return;
                                            }
                                        }
                                    }
 
 
                                    //标记流程完成
                                    //var markResult = Mark (newHomeId);
                                    //if (markResult) {
                                    Application.RunOnMainThread (() => {
                                        btnTipTitle.Text = "The backup data migration is successful, and the platform migration is completed.";
                                        btnTipTitle.Height = Application.GetRealHeight (150);
                                        //btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                        btnTipMsg.Text = "";
                                        etPwd.Visible = false;
                                        loading.Hide ();
                                        btnSave.Visible = false;
                                        btnClose.Width = Application.GetRealWidth (500);
                                    });
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Backup data migration failed. Please try again.";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                    });
                                }
                                //}
 
                            }
 
 
                            break;//只升级一个
                        }
                    }
                } else {
                    //没有网关
                    Application.RunOnMainThread (() => {
                        btnTipMsg.Text = "No gateway detected, please check local data";
                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                        loading.Hide ();
                    });
                    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 ("india_beta.bin");
            //System.IO.Stream stream = Application.Activity.Assets.Open ("india_test.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>
        /// <param name="gatewayDevice"></param>
        private void SetSubnetId (GatewayBase gatewayDevice)
        {
            string [] macAddress = gatewayDevice.MAC.Split ('.');
                byte [] Musics = new byte [10];
                for (int i = 0; i < macAddress.Length; i++) {
                    Musics [i] = Convert.ToByte (macAddress [i], 16);
                }
                try {
                    Musics [8] = Convert.ToByte (Convert.ToInt32 (gatewayDevice.SubnetID));
                    if (Musics [8] < 0 || Musics [8] > 255) {
                        throw new Exception ();
                    }
                } catch {
                    return;
                }
                Control.ControlBytesSend (Command.SetDeviceSubnetID, gatewayDevice.SubnetID, gatewayDevice.DeviceID, Musics);
        }
 
        /// <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) {
                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;
 
        //    return SetGateWayAdminInfo (subnetId, homeId);
 
        //}
 
        
        /// <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;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private byte GetCheckSum (byte [] bytes)
        {
            //byte checksum = 0x00;
            //foreach (byte bt in bytes) {
            //    checksum ^= bt;
            //}
 
            int iSum = 0;
            for (int i = 0; i < bytes.Length; i++) {
                iSum += bytes [i];
            }
            return (byte)(0xff & (0x100 - iSum));
        }
 
 
        /// <summary>
        /// 修改Mqtt域名地址
        /// </summary>
        /// <returns></returns>
        void SetGateWayMqttUrlAddress (byte subnetId,byte deviceId)
        {
            byte [] utlBytes = new byte [65];
            var url = new Uri (SeverAddr);
            var host = "";
            if (url != null) {
                host = url.Host;
            }
            byte [] hostBytes = CommonPage.MyEncodingGB2312.GetBytes (host);
            Array.Copy (hostBytes, 0, utlBytes, 0, 64 < hostBytes.Length ? 64 : hostBytes.Length);
            var sum = GetCheckSum (hostBytes);
            utlBytes [64] = sum;//校验位
            byte [] backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayMqttURLAddress, subnetId, deviceId, utlBytes);
 
            //return CheckIsSuccessfulWithBytes (backBytes, "Failed to modify gateway remote address!");
        }
 
        /// <summary>
        /// 修改管理员信息
        /// </summary>
        /// <param name="adminBytes"></param>
        /// <returns></returns>
        private bool SetGateWayAdminInfo (byte subnetId,string homeId)
        {
            //byte [] name = CommonPage.MyEncodingGB2312.GetBytes (MainPage.LoginUser.AccountString);
            byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (homeId);
            byte [] adminBytes = new byte [73];
            adminBytes [36] = 1;//住宅标志位
            Array.Copy (currentRegionIdBytes, 0, adminBytes, 37, 36 < currentRegionIdBytes.Length ? 36 : currentRegionIdBytes.Length);
 
            byte [] result = Control.ControlBytesSendHasReturn (Command.WriteHomeId, subnetId, 0, adminBytes);
            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;
        }
 
    }
    
}