CrabtreeOn,印度客户定制APP,迁移2.0平台版本
wxr
2023-01-06 c05a93ddb0714a310a31574aaf030e677d9a07b6
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
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Shared.SimpleControl.Phone
{
    /// <summary>
    /// 搜索和写加密网关、绑定网关的页面
    /// </summary>
    public class GuideAddGateway : FrameLayout
    {
        static GuideAddGateway inView;
        static VerticalScrolViewLayout verticalScrolView;
        static List<Common> addedList = new List<Common> ();
 
        public GuideAddGateway ()
        {
            BackgroundColor = SkinStyle.Current.MainColor;
            inThisView = true;
 
 
            //var secretKeyPack = HttpServerRequest.Current.ApplyDeviceSecret ("3782DACE9D900428");
            //if (secretKeyPack != null) {
            //    if (secretKeyPack.Code == StateCode.SUCCESS) {
            //        var pack = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceSecret> (secretKeyPack.Data.ToString ());
            //        if (pack != null) {
            //            byte [] usefullBytes = new byte [17];
            //            usefullBytes [0] = 1;
            //            byte [] ddd = System.Text.Encoding.ASCII.GetBytes (pack.deviceSecret);
            //            Array.Copy (ddd, 0, usefullBytes, 1, 16 < ddd.Length ? 16 : ddd.Length);
            //        }
            //    }
            //}
 
        }
 
        public override void RemoveFromParent ()
        {
            inView = null;
            base.RemoveFromParent ();
            inThisView = false;
        }
 
        /// <summary>
        /// 修改网关备注
        /// </summary>
        static void ResetGatewayName (GatewayBase gatewayBase, Button nameButton1)
        {
            Dialog dialog = new Dialog ();
 
            var dialogView = new FrameLayout ();
            dialogView.MouseUpEventHandler += (sn, dd) => {
                dialog.Close ();
            };
            dialog.AddChidren (dialogView);
            var bodyView = new FrameLayout () {
                Gravity = Gravity.Center,
                Width = Application.GetRealWidth (500),
                Height = Application.GetRealHeight (400),
                Radius = 5,
                BorderColor = SkinStyle.Current.Transparent,
                BorderWidth = 0,
                BackgroundColor = SkinStyle.Current.DialogColor,
            };
            dialogView.AddChidren (bodyView);
 
            var btnTitle = new Button () {
                Height = Application.GetRealHeight (80),
                TextAlignment = TextAlignment.Center,
                Text = "Setting",
                TextColor = SkinStyle.Current.DialogTextColor,
                BackgroundColor = SkinStyle.Current.DialogTitle,
            };
            bodyView.AddChidren (btnTitle);
 
            var btnZoneName = new Button () {
                X = Application.GetRealWidth (50),
                Y = btnTitle.Bottom + Application.GetRealHeight (10),
                Width = Application.GetRealWidth (400),
                Height = Application.GetRealHeight (80),
                TextAlignment = TextAlignment.CenterLeft,
                TextColor = SkinStyle.Current.TextColor,
                Text = "Gateway Name : "
            };
            bodyView.AddChidren (btnZoneName);
 
            var etRemark = new EditText () {
                X = Application.GetRealWidth (50),
                Y = btnZoneName.Bottom + Application.GetRealHeight (10),
                Width = Application.GetRealWidth (400),
                Height = Application.GetRealHeight (80),
                TextColor = SkinStyle.Current.TextColor,
                TextAlignment = TextAlignment.Center,
                Radius = 5,
                BorderColor = SkinStyle.Current.BorderColor,
                BorderWidth = 2,
                Text = gatewayBase.Name,
            };
            bodyView.AddChidren (etRemark);
 
            etRemark.EditorEnterAction += (obj) => {
                Application.HideSoftInput ();
            };
 
            //if (MainPage.LoginUser.AccountType == 1) {
            //    etRemark.Enable = false;
            //    etRemark.BorderWidth = 0;
            //}
 
            var BottomView = new FrameLayout () {
                Y = Application.GetRealHeight (400 - 88),
                Height = Application.GetRealHeight (90),
                BackgroundColor = SkinStyle.Current.Black50Transparent,
            };
            bodyView.AddChidren (BottomView);
 
 
 
            var btnClose = new Button () {
                Width = Application.GetRealWidth (250),
                TextID = R.MyInternationalizationString.cancel,
                TextColor = SkinStyle.Current.DialogTextColor,
                BackgroundColor = SkinStyle.Current.DialogTitle,
                TextAlignment = TextAlignment.Center,
            };
            BottomView.AddChidren (btnClose);
            btnClose.MouseUpEventHandler += (bb, cc) => {
                dialog.Close ();
            };
 
            var btnOption = new Button () {
                X = btnClose.Right + 1,
                Width = Application.GetRealWidth (250),
                TextID = R.MyInternationalizationString.OK,
                TextColor = SkinStyle.Current.DialogTextColor,
                BackgroundColor = SkinStyle.Current.DialogTitle,
                TextAlignment = TextAlignment.Center,
            };
            btnOption.MouseUpEventHandler += (sdf, fds) => {
                dialog.Close ();
                if (etRemark.Text.Trim () == "") {
                    new Alert ("", "Please enter gateway name", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                    return;
                }
                gatewayBase.Name = etRemark.Text.Trim ();
                CommonPage.UpdateRemark (gatewayBase.SubnetID, gatewayBase.DeviceID, etRemark.Text.Trim ());
                nameButton1.Text = etRemark.Text.Trim ();
                IO.FileUtils.SaveEquipmentMessage (gatewayBase);
            };
 
            BottomView.AddChidren (btnOption);
 
            dialog.Show ();
        }
 
        public void ShowPage (RegionInfoRes home)
        {
            ////2020-01-14 第一次进入页面默认
            //UserConfig.Instance.IsLocalEncrypt = false;
 
            addedList = new List<Common> ();
            inView = this;
            #region 标题
            var topView = new FrameLayout () {
                Y = Application.GetRealHeight (36),
                Height = Application.GetRealHeight (90),
                Width = Application.GetRealWidth (640),
            };
            AddChidren (topView);
 
            var title = new Button () {
                TextAlignment = TextAlignment.Center,
                Text = home.Name,
                TextColor = SkinStyle.Current.TextColor1,
                TextSize = 19,
            };
            topView.AddChidren (title);
 
            var logo = new Button () {
                Width = Application.GetRealWidth (154),
                Height = Application.GetRealHeight (90),
                X = Application.GetRealWidth (486),
                UnSelectedImagePath = MainPage.LogoString,
            };
            topView.AddChidren (logo);
            logo.MouseUpEventHandler += (dd, fff) => {
#if DEBUG
                verticalScrolView.RemoveAll ();
                addedList.Clear ();
                SearchGatewayList ();
#endif
            };
 
            var back = new Button () {
                Height = Application.GetRealHeight (90),
                Width = Application.GetRealWidth (85),
                UnSelectedImagePath = "Item/Back.png",
                SelectedImagePath = "Item/BackSelected.png",
            };
            topView.AddChidren (back);
            back.MouseUpEventHandler += (sender, e) => {
                //重置为加密模式
                UserConfig.Instance.IsLocalEncrypt = true;
                (Parent as PageLayout).PageIndex -= 1;
            };
 
            #endregion
            verticalScrolView = new VerticalScrolViewLayout () {
                Y = Application.GetRealHeight (126),
                //Y = waitView.Bottom,
                Height = Application.GetRealHeight (1136 - 126 - 0),
                BackgroundColor = SkinStyle.Current.ViewColor
            };
            AddChidren (verticalScrolView);
 
            SearchGatewayList ();
        }
 
        //static DateTime waitingTime = DateTime.Now;
        //static int sleepTime = 0;
 
        public static void InitGatewayRowView (GatewayBase common)
        {
            if (inView == null)
                return;
            lock (addedList) {
                if (addedList.Find ((obj) => obj.SubnetID == common.SubnetID && obj.DeviceID == common.DeviceID) != null)
                    return;
                addedList.Add (common);
 
                var gatewayView = new RowLayout () {
                    Height = Application.GetRealHeight (120),
                    BackgroundColor = SkinStyle.Current.ViewColor,
                };
                verticalScrolView.AddChidren (gatewayView);
 
                var pointButton1 = new Button () {
                    Width = Application.GetRealHeight (13),
                    Height = Application.GetRealHeight (13),
                    X = Application.GetRealWidth (60),
                    UnSelectedImagePath = "Item/Point.png",
                    SelectedImagePath = "Item/PointSelected.png",
                    Gravity = Gravity.CenterVertical,
                };
                gatewayView.AddChidren (pointButton1);
 
                var nameButton1 = new Button () {
                    Width = Application.GetRealWidth (342),
                    Height = LayoutParams.MatchParent,
                    Text = common.Name,
                    TextAlignment = TextAlignment.CenterLeft,
                    X = pointButton1.Right + Application.GetRealWidth (20),
                    TextColor = SkinStyle.Current.TextColor1
                };
                gatewayView.AddChidren (nameButton1);
 
                var rightButton1 = new Button () {
                    X = Application.GetRealWidth (550),
                    Width = Application.GetRealWidth (28),
                    Height = Application.GetRealHeight (40),
                    Gravity = Gravity.CenterVertical,
                    UnSelectedImagePath = "Item/Right.png",
                    SelectedImagePath = "Item/RightSelected.png",
                };
                gatewayView.AddChidren (rightButton1);
 
                var goNextRight = new Button () {
                    X = Application.GetRealWidth (550),
                    Width = Application.GetRealWidth (80),
                };
                gatewayView.AddChidren (goNextRight);
 
 
                var btnDel = new Button () {
                    Text = "Delete",
                    BackgroundColor = SkinStyle.Current.DelColor,
                };
                gatewayView.AddRightView (btnDel);
                btnDel.MouseUpEventHandler += (sender, e) => {
                    var delAlert = new Alert ("", "If you delete gateway, you will not able to control the devices. Still you want to delete the gateway?", "No", "Yes");
                    delAlert.Show ();
 
                    delAlert.ResultEventHandler += (sender1, e1) => {
                        if (e1) {
                            var delFile = IO.FileUtils.ReadFiles ().FindAll ((w) => {
                                return (w.Split ('_') [0] == "Equipment") && (w.Split ('_') [2] == common.SubnetID.ToString ());
                            });
                            for (int k = 0; k < delFile.Count; k++) {
                                if (delFile [k].Contains (DeviceType.OnePortWirelessFR.ToString ())
                                || delFile [k].Contains (DeviceType.OnePortMqttFR.ToString ())
                                || delFile [k].Contains (DeviceType.OnePortBus.ToString ())
                                || delFile [k].Contains (DeviceType.RCU.ToString ())
                                || delFile [k].Contains (DeviceType.SuperWireless.ToString ())) {
                                    continue;
                                }
                                IO.FileUtils.DeleteFile (delFile [k]);
                            }
                            addedList.Remove (common);
                            gatewayView.RemoveFromParent ();
                        }
                    };
                };
 
                EventHandler<MouseEventArgs> eHandler = (sender, e) => {
                    //跳转之前先绑定APP
 
                    MainPage.Loading.Start ("Please wait...");
                    bool needHide = true;
                    new System.Threading.Thread (() => {
                        System.Threading.Thread.Sleep (10000);
                        if (needHide) {
                            MainPage.Loading.MouseUpEventHandler += (sd, dd) => {
                                Application.RunOnMainThread (() => {
                                    MainPage.Loading.Hide ();
                                    needHide = false;
                                });
                            };
                        }
                    }) { IsBackground = true }.Start ();
                    bool goNext = false;
                    System.Threading.Tasks.Task.Run (() => {
                        try {
                            //
                            goNext = CheckIfGoNext (common);
                            if (goNext) {
                                //先重置
                                goNext = false;
                                //网关版本符合要求,继续判断是否绑定网关成功,绑定成功了才能进行下一步跳转设备搜索页面
                                goNext = CheckIfBindGatewaySuccess (common);
                            }
                         
                        } catch (Exception ex) {
                            Utlis.WriteLine (ex.Message);
                        } finally {
                            Application.RunOnMainThread (() => {
                                MainPage.Loading.Hide ();
                                needHide = false;
                                if (goNext) {
                                    CommonPage.FindGatewayChilrenIPAddress = common.IPAddress;
                                    inThisView = false;
                                    if (inView != null) {
                                        Utlis.WriteLine ("inView != null");
                                        //跳转设备搜索页面
                                        var deviceListView = new GuideSettingGateway (common);
                                        (inView.Parent as PageLayout).AddChidren (deviceListView);
                                        deviceListView.ShowPage ();
                                        (inView.Parent as PageLayout).PageIndex = (inView.Parent as PageLayout).ChildrenCount - 1;
                                    } else {
                                        Utlis.WriteLine ("inView == null");
                                        UserHomePage.FrameLayoutMain.AddChidren (UserMiddle.guidePageView);
                                        var guide = new GuideAddResidence ();
                                        UserMiddle.guidePageView.AddChidren (guide);
                                        guide.ShowHomeView ();
                                        UserMiddle.guidePageView.PageIndex = 0;
                                        //重置为加密模式
                                        UserConfig.Instance.IsLocalEncrypt = true;
                                    }
                                }
                            });
                        }
                    });
                };
 
                goNextRight.MouseUpEventHandler += eHandler;
                rightButton1.MouseUpEventHandler += eHandler;
                nameButton1.MouseUpEventHandler += (sender, e) => {
                    ResetGatewayName (common, nameButton1);
                };
            }
        }
 
        /// <summary>
        /// 检测是否绑定网关成功
        /// </summary>
        /// <returns></returns>
        static bool CheckIfBindGatewaySuccess (GatewayBase gatewayBase)
        {
            try {
                if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) {
                    //之前绑定过网关,并且和当前搜索到到网关一致,子网号设备号都要一致
                    if (UserConfig.Instance.HomeGateway.mac.ToUpper () == gatewayBase.MAC.Replace (".", "").ToUpper ()
                        && UserConfig.Instance.HomeGateway.subnetId == gatewayBase.SubnetID
                        && UserConfig.Instance.HomeGateway.deviceId == gatewayBase.DeviceID
                        ) {
                        return true;
                    }
                }
 
                var gatewayMAC = gatewayBase.MAC.Replace (".", "");
                //重新绑定
                var bindGatewayObj = new BindGatewayObj () {
                    homeId = UserConfig.Instance.CurrentRegion.Id,
                    subnetId = gatewayBase.SubnetID,
                    deviceId = gatewayBase.DeviceID,
                    gatewayType = GatewayType.BUSUDPGATEWAY.ToString (),
                    mac = gatewayMAC
                };
                var revertObj = HttpServerRequest.Current.BindGateway (bindGatewayObj);
                if (revertObj.Code == StateCode.SUCCESS) {
                    var homeGatewayInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<HomeGatewayInfo> (revertObj.Data.ToString ());
                    if (homeGatewayInfo != null && !string.IsNullOrEmpty (homeGatewayInfo.gatewayId)) {
                        //绑定网关成功,并且成功获取到新绑定的gatewayId
                        UserConfig.Instance.HomeGateway = homeGatewayInfo;
                        UserConfig.Instance.SaveUserConfig ();
                        return true;
                    }
                } else {
                    IMessageCommon.Current.ShowErrorInfoAlter (revertObj.Code);
                }
            } catch {
                Utlis.WriteLine ("绑定网关失败");
            }
            return false;
        }
 
 
        static bool inThisView = false;
        //Alert checkInternetAlert = new Alert ("", "Your phone in not connected to WIFI network, please connet", "Close", "Search again");
        //Alert confirmAlert = new Alert ("", "Please make sure gateway is powered up and comect to WiFi router.", "Close", "Search again");
        //Alert confirmAlert1 = new Alert ("", "If not all the gateways are in the list,you can search again.", "Close", "Search again");
        //Alert wrongPasswordAlert = new Alert ("", ErrorCode.GatewayPasswordError, "Close", "Search again");
 
        void SearchGatewayList ()
        {
            if (UserConfig.Instance.internetStatus == 0 || UserConfig.Instance.internetStatus == 1) {
                Alert checkInternetAlert = new Alert ("", ErrorCode.NotConnectedToWIFI, "Close", "Search again");
 
                checkInternetAlert.Show ();
 
                checkInternetAlert.ResultEventHandler += (dsss, eee) => {
                    if (eee) {
                        SearchGatewayList ();
                    }
                };
                return;
            }
 
            CommonPage.FindGateway = true;
            new System.Threading.Thread (() => {
                try {
                    Application.RunOnMainThread (() => {
                        MainPage.Loading.Start ("Searching for gateway...");
                    });
                    #region 搜索设备
                    //是否需要加密检测、、为了适配多网关,搜索添加网关的时候需要关掉加密检测,然后同时发送密文,明文搜索网关 2023-01-06 16:49:30
                    CommonPage.needEncryptionDetection = false;
                    ////2020-01-14 默认明文开始搜索
                    UserConfig.Instance.IsLocalEncrypt = false;
                    UserConfig.Instance.EncryptedPasswordCorrect = true;
 
                    CommonPage.LocalPhoneFindDevice = true;
                    CommonPage.RandomHigh = (byte)new Random ().Next (255);
                    CommonPage.RandomLow = (byte)new Random ().Next (255);
                    CommonPage.GateWayList.Clear ();
                    CommonPage.FindGateway = true;
                    //如果两次都没有数据反馈,就不读取
                    int readCount = 3;
                    while (0 < readCount) {
                        readCount--;
                        System.IO.MemoryStream ms = new System.IO.MemoryStream ();
                        ms.WriteByte (CommonPage.RandomHigh);
                        ms.WriteByte (CommonPage.RandomLow);
 
                        List<Common> list = CommonPage.GateWayList;
 
                        int tempCount = list.Count;
                        string s = ";";
                        for (int i = 0; i < list.Count; i++) {
                            Common common = list [i];
                            if (s.Contains (";" + common.SubnetID.ToString () + ":" + common.DeviceID.ToString ()))
                                continue;
                            s += common.SubnetID.ToString () + ":" + common.DeviceID.ToString () + ";";
                            ms.WriteByte (common.SubnetID);
                            ms.WriteByte (common.DeviceID);
                        }
                        Control control = new Control ();
 
                        Utlis.WriteLine ("组播搜索网关,搜索地址是:" + CommonPage.EndPoint.ToString () + "    " + CommonPage.GateWayList.Count);
                        control.Send (new Target () {
                            IPEndPoint = CommonPage.EndPoint,
                            Command = Command.ReadGateway,
                            SubnetID = 0xFF,
                            DeviceID = 0xFF,
                            AddData = ms.ToArray ()
                        }, SendCount.Zero, false);
 
                        Utlis.WriteLine ("广播搜索网关,搜索地址是:" + new Net.NetWiFi ().BroadcastIpAddress.ToString () + "    " + CommonPage.GateWayList.Count);
                        control.Send (new Target () {
                            IPEndPoint = new System.Net.IPEndPoint (new Net.NetWiFi ().BroadcastIpAddress, 6000),
                            Command = Command.ReadGateway,
                            SubnetID = 0xFF,
                            DeviceID = 0xFF,
                            AddData = ms.ToArray ()
                        }, SendCount.Zero, false);
 
                        System.Threading.Thread.Sleep (800);
                        //如果数量不相等,就重置次数
                        if (tempCount != CommonPage.GateWayList.Count) {
                            readCount = 3;
                        }
                    }
 
                    //2023-01-06 16:33:09 增加同时发送密文搜索
                    CommonPage.needEncryptionDetection = true;
                    UserConfig.Instance.IsLocalEncrypt = true;
                    readCount = 3;
                    while (0 < readCount) {
                        readCount--;
                        System.IO.MemoryStream ms = new System.IO.MemoryStream ();
                        ms.WriteByte (CommonPage.RandomHigh);
                        ms.WriteByte (CommonPage.RandomLow);
 
                        List<Common> list = CommonPage.GateWayList;
 
                        int tempCount = list.Count;
                        string s = ";";
                        for (int i = 0; i < list.Count; i++) {
                            Common common = list [i];
                            if (s.Contains (";" + common.SubnetID.ToString () + ":" + common.DeviceID.ToString ()))
                                continue;
                            s += common.SubnetID.ToString () + ":" + common.DeviceID.ToString () + ";";
                            ms.WriteByte (common.SubnetID);
                            ms.WriteByte (common.DeviceID);
                        }
                        Control control = new Control ();
 
                        Utlis.WriteLine ("组播搜索网关,搜索地址是:" + CommonPage.EndPoint.ToString () + "    " + CommonPage.GateWayList.Count);
                        control.Send (new Target () {
                            IPEndPoint = CommonPage.EndPoint,
                            Command = Command.ReadGateway,
                            SubnetID = 0xFF,
                            DeviceID = 0xFF,
                            AddData = ms.ToArray ()
                        }, SendCount.Zero, false);
 
                        Utlis.WriteLine ("广播搜索网关,搜索地址是:" + new Net.NetWiFi ().BroadcastIpAddress.ToString () + "    " + CommonPage.GateWayList.Count);
                        control.Send (new Target () {
                            IPEndPoint = new System.Net.IPEndPoint (new Net.NetWiFi ().BroadcastIpAddress, 6000),
                            Command = Command.ReadGateway,
                            SubnetID = 0xFF,
                            DeviceID = 0xFF,
                            AddData = ms.ToArray ()
                        }, SendCount.Zero, false);
 
                        System.Threading.Thread.Sleep (800);
                        //如果数量不相等,就重置次数
                        if (tempCount != CommonPage.GateWayList.Count) {
                            readCount = 3;
                        }
                    }
 
                    CommonPage.FindGateway = false;
                    CommonPage.LocalPhoneFindDevice = false;
                    #endregion
                } catch (Exception ex) {
                    Utlis.WriteLine (ex.ToString ());
                } finally {
                    Application.RunOnMainThread (() => {
                        if (CommonPage.GateWayList.Count == 0) {
                            MainPage.Loading.Hide ();
                            if (this != null && this.Parent != null) {
                                ShowConfirmAlert ();
                                
                               
                            }
                        } else {
                            if (this != null && this.Parent != null) {
                                if (inThisView) {// this.Parent.GetChildren (this.Parent.ChildrenCount - 1) == this) {
                                    Alert confirmAlert1 = new Alert ("", ErrorCode.IfAllTheGatewaysAreNotInTheList, "Close", "Search again");
 
                                    confirmAlert1.Show ();
                                    confirmAlert1.ResultEventHandler += (ddf, ddd) => {
                                        MainPage.Loading.Hide ();
                                        if (ddd) {
                                            SearchGatewayList ();
                                        }
                                    };
                                }
                            }
                        }
                    });
                }
            }) { IsBackground = true }.Start ();
        }
 
        /// <summary>
        /// 提示
        /// Please make sure gateway is powered up and comect to WiFi router.
        /// 或者
        /// 
        /// </summary>
        static void ShowConfirmAlert () {
            if (UserConfig.Instance.IsLocalEncrypt) {
                //密码检验正确
                if (UserConfig.Instance.EncryptedPasswordCorrect) {
                    Alert confirmAlert = new Alert ("", ErrorCode.MakeSureGatewayIsPoweredUp, "Close", "Search again");
                    confirmAlert.Show ();
                    confirmAlert.ResultEventHandler += (ddf, ddd) => {
                        MainPage.Loading.Hide ();
                        if (ddd) {
                            inView.SearchGatewayList ();
                        }
                    };
                } else {
                    Alert wrongPasswordAlert = new Alert ("", ErrorCode.GatewayPasswordError, "Close", "Search again");
                    wrongPasswordAlert.Show ();
                    wrongPasswordAlert.ResultEventHandler += (ddf, ddd) => {
                        MainPage.Loading.Hide ();
                        if (ddd) {
                            inView.SearchGatewayList ();
                        }
                    };
 
                }
            } else {
                Alert confirmAlert = new Alert ("", ErrorCode.MakeSureGatewayIsPoweredUp, "Close", "Search again");
                confirmAlert.Show ();
                confirmAlert.ResultEventHandler += (ddf, ddd) => {
                    MainPage.Loading.Hide ();
                    if (ddd) {
                        inView.SearchGatewayList ();
                    }
                };
 
            }
           
 
        }
 
 
        //static byte [] AseKeyBytes;
        /// <summary>
        /// 修改网关本地加密
        /// </summary>
        /// <param name="gatewayDeicve"></param>
        /// <param name="isEncrypt"></param>
        /// <returns></returns>
        static bool SetGateWayLocalEncryption (GatewayBase gatewayDeicve, bool isEncrypt = true)
        {
            if (UserConfig.Instance.CurrentRegion == null) return false;
 
            byte [] AseKeyBytes = UserConfig.Instance.GenerateLocalEncryptionKey ();
            byte [] sendBytes = new byte [17];
            sendBytes [0] = isEncrypt ? (byte)1 : (byte)0; //0:不加密 1:加密
            Array.Copy (AseKeyBytes, 0, sendBytes, 1, 16);
            byte [] backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayLocalEncryption, gatewayDeicve.SubnetID, gatewayDeicve.DeviceID, sendBytes);
            return CheckIsSuccessfulWithBytes (backBytes);
        }
 
        /// <summary>
        /// 判断是否修复成功 F8 = 成功; F5=失败
        /// </summary>
        /// <param name="backBytes"></param>
        /// <returns></returns>
        static bool CheckIsSuccessfulWithBytes (byte [] backBytes, string errorStr = "Modify gateway configuration failed,please try again!")
        {
            if (backBytes == null) {
                Application.RunOnMainThread (() => {
                    new Alert ("", ErrorCode.GatewayNoResponse,
                               Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
                return false;
            } else if (backBytes [0] == 0xF8) {//F8 = 成功; F5=失败
                return true;
            } else {
                Application.RunOnMainThread (() => {
                    new Alert ("", errorStr,
                               Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
                return false;
            }
        }
 
 
        /// <summary>
        /// CheckIfGoNext
        /// </summary>
        /// <returns></returns>
        static bool CheckIfGoNext (GatewayBase common)
        {
            bool goNext = false;
            if (common.Type == DeviceType.OnePortWirelessFR || common.Type == DeviceType.OnePortMqttFR) {
                goNext = CheckIfGoNextMqttGateway (common);
            } else {
                goNext = true;
            }
            return goNext;
        }
 
        /// <summary>
        /// CheckIfGoNextMqttGateway
        /// </summary>
        /// <returns></returns>
        static bool CheckIfGoNextMqttGateway (GatewayBase common)
        {
            Application.RunOnMainThread (() => {
                MainPage.Loading.Start ("Please wait...");
            });
 
            bool goNext = false;
            //if (!UserConfig.Instance.IsLocalEncrypt) {
            //    //如果没加密,走修改加密方法
            //    var result = SetGateWayLocalEncryption (common);
            //    if (!result) {
            //        MainPage.LoadingHide ();
            //        return result;//修改失败 返回goNext false
            //    }
            //    //修改成功,设置本地为加密方式
            //    UserConfig.Instance.IsLocalEncrypt = true;
            //    //string aseKeyStr = CommonPage.MyEncodingUTF8.GetString (AseKeyBytes);
            //    //UserConfig.Instance.LocalEncryptKey = aseKeyStr;
            //    Utlis.WriteLine ($"============>LocalEncryptKey 加密成功Key为:{UserConfig.Instance.LocalEncryptKey}");
            //}
            UserConfig.Instance.IsLocalEncrypt = false;
            var backBytes = Control.ControlBytesSendHasReturn (Command.Read_APP_Data_STORE_1D5C_CMD, common.SubnetID, common.DeviceID, new byte [] { });
          
            if (backBytes == null) {
                Application.RunOnMainThread (() => {
                    new Alert ("", "No response from gateway. Please make sure the gateway is online and its firmware is up to date.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
                return false;
            }
 
            if (backBytes.Length >= 37) {
                //******************住宅ID string类型*************
                bool enable = backBytes [0] == 0 ? false : true;
                //返回住宅ID 转为string类型
                string backIDStr = CommonPage.MyEncodingGB2312.GetString (backBytes, 1, 36).Trim ('\0');
                backIDStr = backIDStr.Replace ("ÿ", "");
                //2020-01-12
                backIDStr = backIDStr.Replace ("\0", "");
                if (enable || backIDStr == UserConfig.Instance.CurrentRegion.Id || string.IsNullOrEmpty (backIDStr)) {
                   
 
                    if (!UserConfig.Instance.IsLocalEncrypt || true) {//不管加没加密,都重新加密一次,防止多网关的时候有从网关没加密 2022-12-26 13:42:09
                        //如果没加密,走修改加密方法
                        var result = SetGateWayLocalEncryption (common);
                        if (!result) {
                            Application.RunOnMainThread (() => {
                                MainPage.Loading.Hide ();
                                new Alert ("", "Encryption gateway failed, please try again.", Language.StringByID (R.MyInternationalizationString.Close)).Show ();
 
                            });
                          
                            return result;//修改失败 返回goNext false
                        }
                        //修改成功,设置本地为加密方式
                        UserConfig.Instance.IsLocalEncrypt = true;
                        //Utlis.WriteLine ($"============>LocalEncryptKey 加密成功Key为:{UserConfig.Instance.LocalEncryptKey}");
                    }
                    goNext = true;
 
                } else {
                    UnableToBindGatewayAlertShow ();
                }
            } else {
                Application.RunOnMainThread (() => {
                    new Alert ("", ErrorCode.GatewayVersionLow, Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
            }
            MainPage.LoadingHide ();
            return goNext;
 
        }
 
 
        static void UnableToBindGatewayAlertShow ()
        {
            if (inView == null)
                return;
            Application.RunOnMainThread (() => {
 
                //if (this != null && this.Parent != null) {
                var alter = new Alert ("", ErrorCode.UnableToBindGateway, Language.StringByID (R.MyInternationalizationString.Close));
                alter.ResultEventHandler += (sender1, e1) => {
                    if (e1) {
                        if (inView == null)
                            return;
                        //重置为加密模式
                        UserConfig.Instance.IsLocalEncrypt = true;
                        (inView.Parent as PageLayout).PageIndex -= 1;
                    }
                };
                alter.Show ();
                //}
 
            });
 
        }
    }
}