黄学彪
2019-10-10 2ed75b8b337048e5d75e6d9ec8307633134f02fd
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using ZigBee.Device;
 
namespace Shared.Phone.UserCenter.GatewayAdd
{
    /// <summary>
    /// 网关搜索中
    /// </summary>
    public class WiredGatewaySearchForm : EditorCommonForm
    {
        #region ■ 变量声明___________________________
 
        /// <summary>
        /// 列表控件
        /// </summary>
        private VerticalScrolViewLayout listView = null;
        /// <summary>
        /// 这是个透明的控件
        /// </summary>
        private FrameLayout frameTransparent = null;
        /// <summary>
        /// 线程执行中
        /// </summary>
        private bool IsThreadAction = true;
        /// <summary>
        /// 搜索时间
        /// </summary>
        private int searchTime = 60;
        /// <summary>
        /// 停止搜索的按键
        /// </summary>
        private BottomClickButton btnStop = null;
        /// <summary>
        /// 网关的主键(value:剩余检测次数,用于对应异常的网关)
        /// </summary>
        private Dictionary<string, int> dicGatewayId = new Dictionary<string, int>();
 
        #endregion
 
        #region ■ 初始化_____________________________
 
        /// <summary>
        /// 画面显示(底层会固定调用此方法,借以完成画面创建)
        /// </summary>
        public void ShowForm()
        {
            //设置标题信息
            base.SetTitleText(Language.StringByID(R.MyInternationalizationString.uAddWiredGateway));
 
            //初始化中部控件
            this.InitMiddleFrame();
 
            //开启线程
            this.StartThread();
        }
 
        /// <summary>
        /// 初始化中部控件
        /// </summary>
        private void InitMiddleFrame()
        {
            //清空bodyFrame
            this.ClearBodyFrame();
 
            //网关列表,这个控件置于背部
            listView = new VerticalScrolViewLayout();
            listView.Height = ControlCommonResourse.ListViewRowHeight * 5;
            bodyFrameLayout.AddChidren(listView);
 
            //图片,背景要透明
            frameTransparent = new FrameLayout
            {
                Width = bodyFrameLayout.Width,
                Height = bodyFrameLayout.Height,
                Gravity = Gravity.CenterHorizontal,
                BackgroundColor = UserCenterColor.Current.Transparent
            };
            bodyFrameLayout.AddChidren(frameTransparent);
 
            //图片
            var btnimage = new PicViewControl(620, 620);
            btnimage.Y = ControlCommonResourse.ListViewRowHeight * 2;
            btnimage.Gravity = Gravity.CenterHorizontal;
            btnimage.UnSelectedImagePath = "Gateway/SearchGateway.png";
            frameTransparent.AddChidren(btnimage);
 
            //智能网关配置网络中
            var btnText1 = new NormalViewControl(bodyFrameLayout.Width, false);
            btnText1.Y = btnimage.Bottom + Application.GetRealHeight(60);
            btnText1.Gravity = Gravity.CenterHorizontal;
            btnText1.TextID = R.MyInternationalizationString.uGatewaySetting;
            frameTransparent.AddChidren(btnText1);
 
            //请稍候
            var btnText2 = new NormalViewControl(bodyFrameLayout.Width, false);
            btnText2.Y = btnText1.Bottom + Application.GetRealHeight(30);
            btnText2.Gravity = Gravity.CenterHorizontal;
            btnText2.TextID = R.MyInternationalizationString.uPleaseWait;
            frameTransparent.AddChidren(btnText2);
 
            //停止搜索
            btnStop = new BottomClickButton();
            btnStop.TextID = R.MyInternationalizationString.uStopSearch;
            frameTransparent.AddChidren(btnStop);
 
            btnStop.MouseUpEventHandler += this.btnStop_MouseClick;
        }
 
        #endregion
 
        #region ■ 开启线程___________________________
 
        /// <summary>
        /// 开启搜索网关的子线程
        /// </summary>
        private void StartThread()
        {
            string textValue = btnStop.Text;
            //清空保存的主键
            this.dicGatewayId.Clear();
            //线程运行中
            this.IsThreadAction = true;
 
            //清空全部列表
            HdlGatewayLogic.Current.ClearAllRealGateway();
            ZigBee.Common.Application.IsSearchingGateway = true;
 
            //开启倒计时线程
            this.StartTimeCountThread(textValue);
 
            HdlThreadLogic.Current.RunThread(async () =>
            {
                while (this.IsThreadAction)
                {
                    await Task.Delay(2500);
                    //异步网关检测中(先等个5秒,然后等mqtt连接)
                    if (this.searchTime > 55)
                    {
                        continue;
                    }
 
                    //检测搜索到的网关,然后添加到画面的行里面
                    await this.CheckZbGatewayAndSetRow();
                }
            });
        }
 
        /// <summary>
        /// 开启倒计时线程
        /// </summary>
        /// <param name="textValue"></param>
        private void StartTimeCountThread(string textValue)
        {
            //搜索时间
            this.searchTime = 60;
 
            HdlThreadLogic.Current.RunThread(() =>
            {
                while (this.IsThreadAction)
                {
                    System.Threading.Thread.Sleep(1000);
 
                    this.searchTime--;
                    if (this.searchTime == 0 || this.IsThreadAction == false)
                    {
                        //时间截止
                        this.btnStop_MouseClick(null, null);
                        break;
                    }
                    Application.RunOnMainThread(() =>
                    {
                        if (btnStop != null)
                        {
                            //倒计时显示
                            btnStop.Text = textValue + "(" + searchTime + ")";
                        }
                    });
                }
                Application.RunOnMainThread(() =>
                {
                    if (btnStop != null)
                    {
                        btnStop.Text = textValue;
                    }
                });
            });
        }
 
        #endregion
 
        #region ■ 网关检测___________________________
 
        /// <summary>
        /// 检测搜索到的网关,然后添加到画面的行里面
        /// </summary>
        private async Task<bool> CheckZbGatewayAndSetRow()
        {
            List<string> listId = new List<string>();
            for (int i = 0; i < ZbGateway.GateWayList.Count; i++)
            {
                string strip = HdlGatewayLogic.Current.GetGatewayBaseInfoAttribute(ZbGateway.GateWayList[i], "IpAddress").ToString();
                if (strip == string.Empty)
                {
                    //IP没有的网关,我也不知道它是干嘛的
                    continue;
                }
                string gwId = HdlGatewayLogic.Current.GetGatewayId(ZbGateway.GateWayList[i]);
                //重复添加检测
                if (this.dicGatewayId.ContainsKey(gwId) == false)
                {
                    //允许五次检测
                    this.dicGatewayId[gwId] = 5;
                    listId.Add(gwId);
                }
                else if (this.dicGatewayId[gwId] > 0)
                {
                    //如果前一次检测失败了的话,它的次数-1
                    this.dicGatewayId[gwId] = this.dicGatewayId[gwId] - 1;
                    listId.Add(gwId);
                }
            }
            if (listId.Count == 0)
            {
                //没有新的网关,或者次数已经用完
                return true;
            }
            for (int i = 0; i < listId.Count; i++)
            {
                ZbGateway way = ZbGateway.GateWayList.Find((obj) => HdlGatewayLogic.Current.GetGatewayId(obj) == listId[i]);
                if (way == null)
                {
                    continue;
                }
                //网关绑定模式
                GatewayBindMode mode = GatewayBindMode.BindAgain;
                if (way.getGatewayBaseInfo.HomeId == Common.Config.Instance.HomeId)
                {
                    //已经绑定过了
                    mode = GatewayBindMode.Binded;
                }
                else if (HdlGatewayLogic.Current.HomeIdIsEmpty(way) == true)
                {
                    //第一次绑定,也就是网关住宅ID为空
                    mode = GatewayBindMode.First;
                }
                //本地是否有这个网关
                bool isExist = HdlGatewayLogic.Current.IsGatewayExist(way);
 
                //如果
                if (mode != GatewayBindMode.BindAgain)
                {
                    //添加搜索到的网关到缓存(执行网关保存操作)
                    ShowErrorMode showMode = this.dicGatewayId[listId[i]] == 0 ? ShowErrorMode.YES : ShowErrorMode.NO;
                    var result = await this.DoSaveGateway(way, showMode, mode);
                    if (result == false)
                    {
                        //当使用完次数之后,并且本地不存在的,才显示出来
                        if (this.dicGatewayId[listId[i]] == 0 && isExist == false)
                        {
                            Application.RunOnMainThread(() =>
                            {
                                //添加失败的网关到画面
                                this.AddFailRowLayout(way);
                            });
                        }
                        continue;
                    }
                }
                //如果它已经完全成功了的话,则将它的剩余次数置零
                this.dicGatewayId[listId[i]] = 0;
                if (isExist == true)
                {
                    //已经绑定过了的,则不再显示
                    continue;
                }
 
                if (mode != GatewayBindMode.BindAgain)
                {
                    //我觉得这里需要获取一下新网关的设备列表
                    await Common.LocalDevice.Current.SetDeviceToMemmoryByGateway(way);
                }
 
                Application.RunOnMainThread(() =>
                {
                    if (this.Parent != null)
                    {
                        //添加搜索到的网关到画面
                        this.AddRowLayout(way, mode);
                    }
                });
            }
            return true;
        }
 
        #endregion
 
        #region ■ 添加网关行控件_____________________
 
        /// <summary>
        /// 添加搜索到的网关到画面
        /// </summary>
        /// <param name="zbGateway">Zb gateway.</param>
        /// <param name="mode">网关绑定模式</param>
        private void AddRowLayout(ZbGateway zbGateway, GatewayBindMode mode)
        {
            if (listView == null)
            {
                return;
            }
            //网关列表控件
            var gatewayRow = new GatewayRowControl(zbGateway);
            listView.AddChidren(gatewayRow);
            gatewayRow.InitControl(69);
            //不需要在线控件
            gatewayRow.btnOnline.RemoveFromParent();
            gatewayRow.btnOnline = null;
            gatewayRow.frameTable.ButtonClickEvent += (sender, e) =>
            {
                //打开网关编辑界面
                this.OpenEditorGatewayForm(gatewayRow, mode);
            };
            //向右图标
            gatewayRow.frameTable.AddRightArrow();
 
            //绑定
            var btnBind = gatewayRow.frameTable.AddMostRightView("", 300);
            if (mode != GatewayBindMode.BindAgain)
            {
                //已绑定
                btnBind.TextID = R.MyInternationalizationString.uBinded;
                btnBind.TextColor = UserCenterColor.Current.Green;
            }
            else
            {
                //需重新绑定
                btnBind.TextID = R.MyInternationalizationString.uNeedReBinding;
                btnBind.TextColor = UserCenterColor.Current.Red;
 
                //这里只是临时追加,后面可以会移动到别的地方
                var btnConfirm = new NormalViewControl(Application.GetRealWidth(184), gatewayRow.Height, false);
                btnConfirm.Text = "网关识别";
                gatewayRow.AddRightView(btnConfirm);
                btnConfirm.MouseUpEventHandler += (sender, e) =>
                {
                    HdlGatewayLogic.Current.SetTestCommand(zbGateway);
                };
            }
            gatewayRow.AddTag("btnBind", btnBind);
        }
 
        /// <summary>
        /// 添加搜索到的网关到画面的行
        /// </summary>
        /// <param name="zbGateway">Zb gateway.</param>
        private void AddFailRowLayout(ZbGateway zbGateway)
        {
            if (listView == null)
            {
                return;
            }
            //网关列表控件
            var gatewayRow = new GatewayRowControl(zbGateway);
            listView.AddChidren(gatewayRow);
            gatewayRow.InitControl(69);
            //不需要在线控件
            gatewayRow.btnOnline.RemoveFromParent();
            gatewayRow.btnOnline = null;
 
            //智能跳过
            var btnBind = gatewayRow.frameTable.AddMostRightView("", 300);
            btnBind.TextID = R.MyInternationalizationString.uIntelligentSkip;
            btnBind.TextColor = UserCenterColor.Current.Red;
        }
 
        #endregion
 
        #region ■ 执行网关保存_______________________
 
        /// <summary>
        /// 执行网关保存
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <param name="mode">是否显示错误</param>
        /// <param name="bindMode">绑定方式</param>
        /// <returns></returns>
        private async Task<bool> DoSaveGateway(ZbGateway zbGateway, ShowErrorMode mode, GatewayBindMode bindMode)
        {
            //添加搜索到的网关到缓存
            //1:正常  -1:异常  0:当前的网关绑定在了当前账号下的不同住宅里面
            int result = 0;
            if (bindMode == GatewayBindMode.BindAgain)
            {
                result = await HdlGatewayLogic.Current.ReBindNewGateway(zbGateway);
            }
            else
            {
                result = await HdlGatewayLogic.Current.AddNewGateway(zbGateway, mode);
            }
            if (result == -1)
            {
                return false;
            }
 
            //前的网关绑定在了当前账号下的不同住宅里面
            if (result == 0)
            {
                if (mode == ShowErrorMode.YES)
                {
                    //网关绑定在当前账号下的其他住宅里\r\n请解除绑定后再试
                    string msg = Language.StringByID(R.MyInternationalizationString.uTheGatewayInOtherResidenceMsg);
                    if (msg.Contains("{0}") == true)
                    {
                        msg = string.Format(msg, "\r\n");
                    }
                    this.ShowMassage(ShowMsgType.Tip, msg);
                }
                return false;
            }
            return true;
        }
 
        #endregion
 
        #region ■ 打开编辑界面_______________________
 
        /// <summary>
        /// 打开网关编辑界面
        /// </summary>
        /// <param name="viewRow"></param>
        /// <param name="mode"></param>
        private void OpenEditorGatewayForm(GatewayRowControl viewRow, GatewayBindMode mode)
        {
            //已经绑定了,就不用再显示提示
            if (mode == GatewayBindMode.BindAgain && viewRow.GetTagByKey("btnBind") != null)
            {
                //是否重新绑定网关?
                string msg = Language.StringByID(R.MyInternationalizationString.uRebindGatewayMsg);
                this.ShowMassage(ShowMsgType.Confirm, msg, () =>
                {
                    this.ShowConfirmMsgBeforShowForm(viewRow);
                });
            }
            else
            {
                //打开网关名称编辑画面
                var form = new GatewayInfoAddForm();
                form.AddForm(viewRow.zbGateway);
                form.ActionGatewayReName += ((way) =>
                {
                    viewRow.RefreshControl(way);
                });
            }
        }
 
        /// <summary>
        /// 在打开编辑画面之前,弹出确认窗口(重新绑定专用)
        /// </summary>
        /// <param name="viewRow"></param>
        private async void ShowConfirmMsgBeforShowForm(GatewayRowControl viewRow)
        {
            var realway = ZbGateway.GateWayList.Find((obj) =>
             HdlGatewayLogic.Current.GetGatewayId(obj) == HdlGatewayLogic.Current.GetGatewayId(viewRow.zbGateway));
 
            //显示进度条
            this.ShowProgressBar();
 
            var result = await this.DoSaveGateway(realway, ShowErrorMode.YES, GatewayBindMode.BindAgain);
            if (result == false)
            {
                //关闭进度条
                this.CloseProgressBar();
                return;
            }
            //获取设备列表中,请稍后
            this.SetProgressValue(Language.StringByID(R.MyInternationalizationString.uDeviceIsGettingPleaseWait));
            //我觉得这里需要获取一下新网关的设备列表
            result = await Common.LocalDevice.Current.SetDeviceToMemmoryByGateway(realway);
            //关闭进度条
            this.CloseProgressBar();
 
            Application.RunOnMainThread(() =>
            {
                //已绑定
                var btnBind = (NormalViewControl)viewRow.GetTagByKey("btnBind");
                btnBind.TextID = R.MyInternationalizationString.uBinded;
                btnBind.TextColor = UserCenterColor.Current.Green;
                viewRow.RemoveTag("btnBind");
 
                //打开网关名称编辑画面
                var form = new GatewayInfoAddForm();
                form.AddForm(viewRow.zbGateway);
                form.ActionGatewayReName += ((way) =>
                {
                    viewRow.RefreshControl(way);
                });
            });
        }
 
        #endregion
 
        #region ■ 按钮事件___________________________
 
        /// <summary>
        /// 停止按钮按下
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        private void btnStop_MouseClick(object sender, MouseEventArgs e)
        {
            //存在误按的可能,画面开启的2秒前,禁止按下停止按钮
            if (this.searchTime >= 58 || this.Parent == null)
            {
                return;
            }
            //超时
            if (e == null && listView.ChildrenCount == 0)
            {
                //没有发现新网关,请检查网关链接是否正常
                string msg = Language.StringByID(R.MyInternationalizationString.uNotFoundNewGatewayPleaseCheckMsg);
                this.ShowMassage(ShowMsgType.Tip, msg);
            }
            Application.RunOnMainThread(() =>
            {
                this.IsThreadAction = false;
                if (frameTransparent != null)
                {
                    frameTransparent.Visible = false;
                }
                if (listView != null)
                {
                    listView.Height = bodyFrameLayout.Height - Application.GetRealHeight(18);
                }
                this.searchTime = 60;
            });
        }
 
        #endregion
 
        #region ■ 界面关闭___________________________
 
        /// <summary>
        /// 画面关闭
        /// </summary>
        public override void CloseForm()
        {
            this.IsThreadAction = false;
 
            ZigBee.Common.Application.IsSearchingGateway = false;
            //断开没有执行绑定的网关的mqtt
            var list = new List<ZbGateway>();
            for (int i = 0; i < ZbGateway.GateWayList.Count; i++)
            {
                if (HdlGatewayLogic.Current.IsGatewayExist(ZbGateway.GateWayList[i]) == false)
                {
                    list.Add(ZbGateway.GateWayList[i]);
                }
            }
            if (list.Count > 0)
            {
                foreach (var way in list)
                {
                    ZbGateway.GateWayList.RemoveAll((obj) => HdlGatewayLogic.Current.GetGatewayId(obj) == HdlGatewayLogic.Current.GetGatewayId(way));
                    way.DisConnect("Search");
                }
            }
            if (UserCenterResourse.listActionFormId.Contains("GatewayManagementForm") == false)
            {
                //刷新主页
                UserView.UserPage.Instance.Fresh();
            }
 
            base.CloseForm();
        }
 
        #endregion
 
        #region ■ 一般方法___________________________
 
        #endregion
    }
}