黄学彪
2020-12-16 0d9f64668fd7350d6a21fd157e32009a96d98134
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
using System;
using System.Collections.Generic;
using System.Text;
using ZigBee.Device;
 
namespace Shared.Phone.UserCenter.Device
{
    /// <summary>
    /// 搜索设备的界面
    /// </summary>
    public class DeviceSearchForm : EditorCommonForm
    {
        #region ■ 变量声明___________________________
 
        /// <summary>
        /// 新上报的设备
        /// </summary>
        private List<CommonDevice> listNewDevice = new List<CommonDevice>();
        /// <summary>
        /// 显示设备线程是否已经开启
        /// </summary>
        private bool isDeviceThreadStart = false;
        /// <summary>
        /// 等待设备的回馈的超时时间(单位:百毫秒)
        /// </summary>
        private int waitDeviceTimeOut = 20;
        /// <summary>
        /// 主题超时的线程是否开启
        /// </summary>
        private bool isTopicTimeOutThreadStart = false;
        /// <summary>
        /// 主题间的超时时间 -100:中断线程(单位:秒)
        /// </summary>
        private int topTimeOut = 120;
        /// <summary>
        /// 超时最大时间
        /// </summary>
        private int topMaxTime = 120;
        /// <summary>
        /// 画面ID,标记它由哪个界面调用并打开的
        /// </summary>
        private string targetFormId = string.Empty;
        /// <summary>
        /// 网关ID
        /// </summary>
        private string gatewayId = string.Empty;
        /// <summary>
        /// 真实网关
        /// </summary>
        private ZbGateway realGateway = null;
        /// <summary>
        /// 进度条控件
        /// </summary>
        private ProgressRowBar btnProgressBar = null;
        /// <summary>
        /// 网关是否允许入网的标识
        /// </summary>
        private bool gatewayCanAddDevice = false;
 
        #endregion
 
        #region ■ 初始化_____________________________
 
        /// <summary>
        /// 画面显示(底层会固定调用此方法,借以完成画面创建)
        /// </summary>
        /// <param name="i_formId">画面ID,标记它由哪个界面调用并打开的</param>
        public void ShowForm(string i_formId)
        {
            this.targetFormId = i_formId;
 
            //设置标题信息
            base.SetTitleText(Language.StringByID(R.MyInternationalizationString.uAddDevice));
 
            this.gatewayId = HdlGatewayResourse.NowSelectGatewayId;
            HdlGatewayLogic.Current.GetRealGateway(ref this.realGateway, this.gatewayId);
 
            //初始化中部控件
            this.InitMiddleFrame();
        }
 
        /// <summary>
        /// 初始化中部控件
        /// </summary>
        private void InitMiddleFrame()
        {
            //清空bodyFrame
            this.ClearBodyFrame();
 
            //图片
            var framePic = new FrameLayout();
            framePic.Width = this.GetPictrueRealSize(878);
            framePic.Height = this.GetPictrueRealSize(478);
            framePic.Y = Application.GetRealHeight(251);
            framePic.Gravity = Gravity.CenterHorizontal;
            framePic.BackgroundImagePath = "Instruct/DeviceSearch.png";
            bodyFrameLayout.AddChidren(framePic);
 
            //正在搜索设备,请稍候…
            var btnSearch = new NormalViewControl(bodyFrameLayout.Width, Application.GetRealHeight(58), false);
            btnSearch.TextAlignment = TextAlignment.Center;
            btnSearch.TextID = R.MyInternationalizationString.uDeviceSearching;
            btnSearch.Y = Application.GetRealHeight(1037);
            btnSearch.TextColor = UserCenterColor.Current.TextGrayColor3;
            bodyFrameLayout.AddChidren(btnSearch);
 
            //进度条
            this.btnProgressBar = new ProgressRowBar(559, 29);
            btnProgressBar.ProgressBarGoback = false;
            btnProgressBar.Gravity = Gravity.CenterHorizontal;
            btnProgressBar.Y = Application.GetRealHeight(861);
            bodyFrameLayout.AddChidren(btnProgressBar);
            btnProgressBar.StartMode1(true);
 
            if (this.realGateway != null)
            {
                //允许设备入网
                this.StartDeviceCanAddToGateway(false);
                //添加监视设备新上报的事件
                this.realGateway.GwResDataAction += this.AdjustGatewayResultData;
            }
            //开启连接的假想动画效果线程
            this.StartConcetionAnimeteThread(framePic);
        }
 
        #endregion
 
        #region ■ 新设备入网接收_____________________
 
        /// <summary>
        /// 处理网关主题上报
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="resultData">上报数据</param>
        private void AdjustGatewayResultData(string topic, string resultData)
        {
            //检测主题(-1:异常 0:不是相关的主题 1:设备最后的主题上报 2:设备最终上报之前的主题)
            var result = this.CheckIsDeviceComming(topic, resultData);
            if (result == -1)
            {
                //停止接收
                this.realGateway.GwResDataAction -= this.AdjustGatewayResultData;
 
                HdlThreadLogic.Current.RunMain(() =>
                {
                    this.CloseForm();
                });
                return;
            }
            else if (result == 0) { return; }
            else if (result == 2)
            {
                //开启主题间隔超时线程
                this.StartTopicTimeOutThread();
                return;
            }
 
            var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
            CommonDevice.DeviceInfoData info = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceInfoData>(jobject["Data"].ToString());
            if (info.DriveCode != 0)
            {
                //不需要虚拟设备
                return;
            }
            //根据设备Type创建对应的设备对象
            var device = HdlDeviceCommonLogic.Current.NewDeviceObjectByDeviceId((DeviceType)jobject.Value<int>("Device_ID"), jobject.Value<int>("Epoint"));
            if (device == null)
            {
                return;
            }
            device.DeviceInfo = info;
 
            //给新设备设置主键属性
            HdlDeviceCommonLogic.Current.SetNewDeviceMainKeys(device, jobject);
            device.CurrentGateWayId = this.realGateway.GwId;
            //将DeviceInfo的属性设置到主属性中
            HdlDeviceCommonLogic.Current.SetDeviceInfoToMain(device, device);
 
            //添加设备的缓存
            device.IsOnline = 1;
            HdlDeviceCommonLogic.Current.AddDeviceToMemory(ref device);
 
            //刷新超时时间
            this.waitDeviceTimeOut = 20;
 
            //不需要200端点的那个设备  2020.01.13 变更:ota也加进来
            this.listNewDevice.Add(device);
 
            //有新设备,开启显示设备信息界面的线程(里面会等待三秒这样)
            this.StartShowDeviceAddSuccessFormThread();
        }
 
        #endregion
 
        #region ■ 显示设备信息画面___________________
 
        /// <summary>
        /// 开启显示设备信息界面的线程
        /// </summary>
        private void StartShowDeviceAddSuccessFormThread()
        {
            if (this.isDeviceThreadStart == true)
            {
                //线程已经开启
                return;
            }
            this.isDeviceThreadStart = true;
 
            HdlThreadLogic.Current.RunThread(() =>
            {
                while (this.waitDeviceTimeOut >= 0)
                {
                    //等待下一个回路
                    System.Threading.Thread.Sleep(100);
                    this.waitDeviceTimeOut--;
                }
                //停止接收
                this.realGateway.GwResDataAction -= this.AdjustGatewayResultData;
                System.Threading.Thread.Sleep(200);
 
                var listDevice = new List<CommonDevice>();
                for (int i = 0; i < this.listNewDevice.Count; i++)
                {
                    var device = this.listNewDevice[i];
                    if (device.DeviceAddr != this.listNewDevice[0].DeviceAddr)
                    {
                        continue;
                    }
                    listDevice.Add(device);
                    //重新变更UI
                    if (device is OTADevice)
                    {
                        continue;
                    }
                    device.IconPath = string.Empty;
                    device.ReSave();
 
                    //设置设备功能类型 (不能在接收回路的地方写入,不然网关可能会超负荷)
                    HdlDeviceCommonLogic.Current.RefreshDeviceFunctionType(device, device, true);
                    System.Threading.Thread.Sleep(200);
                    //获取设备的固定属性
                    if (HdlDeviceAttributeLogic.Current.ReadDeviceAllFixedAttribute(device) == true)
                    {
                        System.Threading.Thread.Sleep(200);
                    }
                }
 
                //读取设备的其他信息
                this.ReadDeviceOtherInfo(listDevice);
 
                //目前就弄一个
                HdlThreadLogic.Current.RunMain(() =>
                {
                    //显示设备信息画面
                    this.ShowDeviceAddSuccessForm(listDevice);
                });
            });
        }
 
        /// <summary>
        /// 显示设备信息画面
        /// </summary>
        /// <param name="listMacDevice">新设备列表</param>
        private void ShowDeviceAddSuccessForm(List<CommonDevice> listMacDevice)
        {
            if (this.Parent == null)
            {
                return;
            }
            //关闭自身
            this.CloseForm();
            if (this.targetFormId != string.Empty)
            {
                //再关闭设备入网指导界面
                HdlFormLogic.Current.CloseFormByFormName(this.targetFormId);
            }
 
            //添加设备
            var form = new DeviceAddSuccessForm();
            form.AddForm(listMacDevice[0].DeviceAddr);
        }
 
        #endregion
 
        #region ■ 假想动画___________________________
 
        /// <summary>
        /// 开启连接的假想动画效果线程
        /// </summary>
        private void StartConcetionAnimeteThread(FrameLayout framePic)
        {
            int iconSize = this.GetPictrueRealSize(23);
 
            var listPoint = new List<int>();
            for (int i = 0; i < 9; i++)
            {
                //X轴+Index*(图标大小+间距)
                listPoint.Add(this.GetPictrueRealSize(300) + i * (iconSize + this.GetPictrueRealSize(10)));
            }
 
            var btnRound = new PicViewControl(iconSize, iconSize, false);
            btnRound.Radius = (uint)iconSize / 2;
            btnRound.BackgroundColor = UserCenterColor.Current.ConcetionRoundColor;
            btnRound.X = listPoint[0];
            btnRound.Y = this.GetPictrueRealSize(225);
            framePic.AddChidren(btnRound);
 
            HdlThreadLogic.Current.RunThread(() =>
            {
                int index = 1;
                int timeCount = 0;
                while (this.Parent != null)
                {
                    System.Threading.Thread.Sleep(500);
 
                    //网关允许设备入网后才开始计时
                    if (this.gatewayCanAddDevice == true)
                    {
                        timeCount++;
                        if (timeCount >= 360)
                        {
                            this.gatewayCanAddDevice = false;
                            //再次发送允许设备入网
                            this.StartDeviceCanAddToGateway(true);
                            timeCount = 0;
                        }
                    }
                    HdlThreadLogic.Current.RunMain(() =>
                    {
                        if (btnRound != null)
                        {
                            btnRound.X = listPoint[index];
                            index++;
                            if (index == listPoint.Count)
                            {
                                index = 0;
                            }
                        }
                    });
                }
            });
        }
 
        #endregion
 
        #region ■ 检测主题___________________________
 
        /// <summary>
        /// 检测主题(-1:异常 0:不是相关的主题 1:设备最后的主题上报 2:设备最终上报之前的主题)
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="resultData"></param>
        /// <returns></returns>
        private int CheckIsDeviceComming(string topic, string resultData)
        {
            if (topic == gatewayId + "/Device/SearchNewDevice")
            {
                //网关回复设备已经可以入网
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<SearchNewDeviceResult>(jobject["Data"].ToString());
                if (info.time > 0)
                {
                    this.gatewayCanAddDevice = true;
                }
                return 0;
            }
            else if (topic == gatewayId + "/Device/DeviceAnnounce_Respon")
            {
                this.topTimeOut = topMaxTime;
 
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceAnnounceInfo>(jobject["Data"].ToString());
                if (info.IsNew == 6 || info.IsNew == 7)
                {
                    return 0;
                }
                //网关告知客户端有设备声明
                this.btnProgressBar.SetValue(1, 6);
                return 2;
            }
            else if (topic == gatewayId + "/Device/DeviceGetActiveEP_Respon")
            {
                this.topTimeOut = topMaxTime;
                //网关告知客户端获取设备活动端点信息
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceResultInfo>(jobject["Data"].ToString());
                if (info.Result != 0)
                {
                    //出现未知错误,请重新入网
                    //this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndReAccessNetwork));
                    HdlLogLogic.Current.WriteLog(-1, resultData);
                    return 2;
                }
                //设置进度值
                this.btnProgressBar.SetValue(2, 6);
                return 2;
            }
            else if (topic == gatewayId + "/Device/DeviceGetActiveEPSimpleDesc_Respon")
            {
                this.topTimeOut = topMaxTime;
                //网关告知客户端获取设备所有活动端点简单描述符信息
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceResultInfo>(jobject["Data"].ToString());
                if (info.Result != 0)
                {
                    //出现未知错误,请重新入网
                    //this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndReAccessNetwork));
                    HdlLogLogic.Current.WriteLog(-1, resultData);
                    return 2;
                }
                //设置进度值
                this.btnProgressBar.SetValue(3, 6);
                return 2;
            }
            else if (topic == gatewayId + "/Device/DeviceGetDefaultBind_Respon")
            {
                this.topTimeOut = topMaxTime;
                //网关告知客户端获取设备默认绑定表信息
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceResultInfo>(jobject["Data"].ToString());
                if (info.Result != 0)
                {
                    //出现未知错误,请重新入网
                    //this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndReAccessNetwork));
                    HdlLogLogic.Current.WriteLog(-1, resultData);
                    return 2;
                }
                //设置进度值
                this.btnProgressBar.SetValue(4, 6);
                return 2;
            }
            else if (topic == gatewayId + "/Device/DeviceAutoBindZBCoord_Respon")
            {
                this.topTimeOut = topMaxTime;
                //网关告知客户端设备自动绑定协调器信息
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceResultInfo>(jobject["Data"].ToString());
                if (info.Result != 0)
                {
                    //出现未知错误,请重新入网
                    //this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndReAccessNetwork));
                    HdlLogLogic.Current.WriteLog(-1, resultData);
                    return 2;
                }
                //设置进度值
                this.btnProgressBar.SetValue(5, 6);
                return 2;
            }
            else if (topic == gatewayId + "/DeviceInComingRespon")
            {
                this.topTimeOut = topMaxTime;
 
                //设备入网时,有时候网关会上报虚拟设备
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(resultData);
                CommonDevice.DeviceInfoData info = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceInfoData>(jobject["Data"].ToString());
                if (info.DriveCode != 0)
                {
                    //不需要虚拟设备
                    return 0;
                }
                //网关最终上报节点设备信息
                this.btnProgressBar.SetValue(6, 6);
                return 1;
            }
            return 0;
        }
 
        /// <summary>
        /// 开启主题间的超时线程
        /// </summary>
        private void StartTopicTimeOutThread()
        {
            if (this.isTopicTimeOutThreadStart == true)
            {
                return;
            }
            this.isTopicTimeOutThreadStart = true;
            HdlThreadLogic.Current.RunThread(() =>
            {
                while (this.Parent != null && this.topTimeOut >= 0)
                {
                    //等待下一个主题
                    System.Threading.Thread.Sleep(1000);
                    this.topTimeOut--;
                }
                if (this.topTimeOut < 0)
                {
                    //响应超时,请重新入网
                    this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndReAccessNetwork));
                    HdlThreadLogic.Current.RunMain(() =>
                    {
                        //关闭界面
                        this.CloseForm();
                    });
                }
            });
        }
 
        #endregion
 
        #region ■ 允许设备入网_______________________
 
        /// <summary>
        /// 允许设备入网
        /// </summary>
        /// <param name="close"></param>
        private void StartDeviceCanAddToGateway(bool close)
        {
            HdlThreadLogic.Current.RunThread(() =>
            {
                if (close == true)
                {
                    //关闭入网模式
                    this.realGateway.AddNewDeviceToGateway(0);
                    System.Threading.Thread.Sleep(2000);
                }
                while (gatewayCanAddDevice == false && this.Parent != null)
                {
                    //让网关允许入网
                    this.realGateway.AddNewDeviceToGateway(180);
                    System.Threading.Thread.Sleep(6000);
                }
            });
        }
 
        #endregion
 
        #region ■ 画面关闭___________________________
 
        /// <summary>
        /// 画面关闭
        /// </summary>
        public override void CloseFormBefore()
        {
            if (this.realGateway != null)
            {
                //停止接收
                this.realGateway.GwResDataAction -= this.AdjustGatewayResultData;
 
                HdlThreadLogic.Current.RunThread(() =>
                {
                    System.Threading.Thread.Sleep(1200);
                    //关闭入网模式
                    this.realGateway.AddNewDeviceToGateway(0);
                });
            }
            base.CloseFormBefore();
        }
 
        #endregion
 
        #region ■ 一般方法___________________________
 
        /// <summary>
        /// 读取设备的其他信息
        /// </summary>
        /// <param name="listDevice"></param>
        private void ReadDeviceOtherInfo(List<CommonDevice> listDevice)
        {
            var myTypeInfo = HdlDeviceCommonLogic.Current.GetMyDeviceEnumInfo(listDevice);
            if (myTypeInfo.BeloneType == DeviceBeloneType.A窗帘 && listDevice[0] is Rollershade)
            {
                HdlThreadLogic.Current.RunThread(async () =>
                {
                    for (int i = 1; i <= 3; i++)
                    {
                        //重置窗帘
                        var result = await HdlDeviceCurtainLogic.Current.RestoreCurtain((Rollershade)listDevice[0], i != 3 ? ShowErrorMode.NO : ShowErrorMode.YES);
                        if (result == true)
                        {
                            return;
                        }
                        await System.Threading.Tasks.Task.Delay(1000);
                    }
                });
            }
        }
 
        #endregion
 
        #region ■ 结构体_____________________________
 
        /// <summary>
        /// 网关推送的设备结果信息
        /// </summary>
        private class DeviceResultInfo
        {
            /// <summary>
            /// 结果(0:成功,以外都是失败)
            /// </summary>
            public int Result = -1;
        }
 
        /// <summary>
        /// 网关告知客户端有设备声明
        /// </summary>
        private class DeviceAnnounceInfo
        {
            /// <summary>
            /// 蓝才刚说 6和7 这两个是设备重启上报的,目前暂时不能显示到入网步骤那里的
            /// </summary>
            public int IsNew = -1;
        }
 
        /// <summary>
        /// 网关回复允许设备入网
        /// </summary>
        private class SearchNewDeviceResult
        {
            /// <summary>
            /// 允许设备入网的时间
            /// </summary>
            public int time = 0;
        }
 
        #endregion
    }
}