wxr
2020-09-09 c3e1b733fc45bd9f0b88bfb560cfa87a270b079b
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
///*
//更新了EMQ连接方式
//*/
//using System.Collections.Generic;
//using System;
//using MQTTnet.Client;
//using System.Threading.Tasks;
//using Shared;
//using MQTTnet;
//using System.Text;
//using System.Security.Cryptography;
 
//namespace HDL_ON
//{
//    public static class MqttCommon
//    {
//        /// <summary>
//        /// 是否提示 远程连接的错误信息 
//        /// </summary>
//        public static bool IfDEBUG = false;
 
 
//        static string mqttEncryptKey = "";
//        //static string checkGatewayTopicBase64 = "";
 
//        static readonly string PushNotifySqueeze = "/Push/NotifySqueeze";
//        static string RandomKey = "";
 
//        static string GetRandomKey()
//        {
//            if (string.IsNullOrEmpty(RandomKey))
//            {
//                //随机2位字符串
//                RandomKey = Utlis.CreateRandomString(2);
//            }
 
//            return RandomKey;
 
//        }
 
//        /// <summary>
//        /// 是否获取MQTT参数成功
//        /// </summary>
//        //public static bool MqttInfoConfig.Instance.IfGetMqttInfoSuccess = false;
//        //static RemoteMACInfo CurRemoteMACInfo = null;
//        //static MqttInfo mMqttInfo = null;
 
//        ///// <summary>
//        ///// 手机标识
//        ///// </summary>
//        //static Guid currentGuid = Guid.NewGuid ();
//        //static bool thisShowTip = true;
//        //static string mqttRequestParToken="";
 
 
//        /// <summary>
//        /// 远程MqttClient
//        /// </summary>
//        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
 
 
//        /// <summary>
//        /// 推送标识
//        /// </summary>
//        static string PushSignStr = System.DateTime.Now.Ticks.ToString();
 
//        /// <summary>
//        /// 断开远程Mqtt的链接
//        /// </summary>
//        static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s = "")
//        {
//            try
//            {
//                if (remoteIsConnected)
//                {
//                    remoteIsConnected = false;
//                    isSubscribeSuccess = false;
//                    MainPage.Log($"Remote主动断开_{s}");
//                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
//                    await RemoteMqttClient.DisconnectAsync();
 
//                    if (CommonPage.IsRemote)
//                    {
//                        //不是无网络
//                        if (UserConfig.Instance.internetStatus != 0)
//                        {
//                            Utlis.ShowAppLinkStatus(AppLinkStatus.CloudUnlink);
//                        }
//                    }
//                }
//            }
//            catch (Exception e)
//            {
//                MainPage.Log($"Remote断开通讯连接出异常:{e.Message}");
//            }
//        }
 
//        /// <summary>
//        /// 断开远程Mqtt的链接
//        /// </summary>
//        static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
//        {
//            try
//            {
//                //if (remoteIsConnected) {
//                remoteIsConnected = false;
//                isSubscribeSuccess = false;
//                MainPage.Log($"RemoteStart主动断开_{s}");
//                await RemoteMqttClient.DisconnectAsync();
 
//                //}
//            }
//            catch (Exception e)
//            {
//                MainPage.Log($"RemoteStart断开通讯连接出异常:{e.Message}");
//            }
 
//        }
 
 
//        /// <summary>
//        /// 断开mqtt连接
//        /// </summary>
//        /// <param name="s">断开原因</param>
//        /// <param name="reset">是否需要去中心服务器 重新获取参数</param>
//        /// <returns></returns>
//        public static async Task DisConnectRemote(string s = "", bool reset = true)
//        {
//            if (reset)
//            {
//                bNeedStartTip = true;
//                bNeedConnectTip = true;
//                MqttInfoConfig.Instance.IfGetMqttInfoSuccess = false;
//            }
//            await DisConnectRemoteMqttClient(s);
//        }
 
//        //static DateTime dateTime = DateTime.MinValue;
//        /// <summary>
//        /// 外网的MQTT是否正在连接
//        /// </summary>
//        public static bool remoteMqttIsConnecting;
//        static bool remoteIsConnected;
 
//        static MqttCommon()
//        {
//            InitMqtt();
//        }
 
//        public static bool IsInitMqtt = false;
 
//        static void InitMqtt()
//        {
//            new System.Threading.Thread(async () =>
//            {
//                while (true)
//                {
//                    try
//                    {
//                        System.Threading.Thread.Sleep(200);
//                        //if (!MainPage.LoginUser.IsLogin) {
//                        //    continue;
//                        //}
//                        if (!CommonPage.IsRemote) continue;
 
//                        //#if Android
//                        if (BusSocket.IsEnterBackground) continue;
//                        //#endif
 
//                        await StartCloudMqtt();
//                        await SubscribeTopics();
//                    }
//                    catch { }
//                }
//            })
//            { IsBackground = true }.Start();
//        }
 
//        public static void InitState()
//        {
//            IfNeedReadAllDeviceStatus = true;
//            bNeedStartTip = true;
//            bNeedConnectTip = true;
//            IsGatewayOnline = false;
//            StartCloudMqtt();
 
//        }
 
//        static bool isSubscribeSuccess;
//        static async Task SubscribeTopics()
//        {
//            if (remoteIsConnected && !isSubscribeSuccess)
//            {
//                try
//                {
 
//                    //var topicFilterPush = new TopicFilter { QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce,
//                    //    Topic = $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.clientId}/Push/NotifySqueeze" };
 
//                    //2020-05-14 订阅主题质量改为0
//                    var topicFilterBusGateWayToClient = new TopicFilter()
//                    {
//                        Topic = $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.macMark}/#",
//                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
//                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
//                    };
 
//                    var topicFilterPush2 = new TopicFilter
//                    {
//                        Topic = $"/BusGateWayToClient/{MainPage.LoginUser.ID}" + PushNotifySqueeze,
//                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce,
//                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
//                    };
 
 
 
 
//                    Utlis.WriteLine("开始订阅!");
//                    var result = await RemoteMqttClient.SubscribeAsync(new TopicFilter[] { topicFilterBusGateWayToClient, topicFilterPush2 });
//                    if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
//                    {
//                        isSubscribeSuccess = true;
//                        Utlis.WriteLine("订阅成功!");
//                        MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.SubscriptionSuccessful));
 
//                        MqttRemoteSend(new byte[] { 0 }, 3);
 
//                        //读取搜索网关,判断网关是否在线
//                        CheckGatewaysIfOnline();
 
//                        //连接成功后检测是否需要通过远程获取Key
//                        CheckIfNeedGetLocalPasswordFromRemote();
//                    }
 
 
//                }
//                catch (Exception ex)
//                {
//                    Console.WriteLine("订阅catch:" + ex.Message.ToString());
//                }
//            }
//        }
 
//        static DateTime mFlagDateTime;
 
//        //static readonly object SendLocker = new object ();
//        /// <summary>
//        /// 启动远程Mqtt
//        /// </summary>
//        public static async Task StartCloudMqtt()
//        {
 
//            if (UserConfig.Instance.internetStatus == 0)
//            {
//                return;
//            }
 
//            if (!MainPage.LoginUser.IsLogin)
//            {
//                return;
//            }
 
 
//            ////60S后强制重置isConnectiong状态,防止isConnectiong一直为true状态
//            //if (mFlagDateTime.AddSeconds (60).Ticks <= System.DateTime.Now.Ticks) {
//            //    mFlagDateTime = DateTime.Now;
//            //    if (remoteMqttIsConnecting) {
//            //        MainPage.Log ("60s》remoteMqttIsConnecting true ");
//            //        remoteMqttIsConnecting = false;
//            //    }
//            //}
 
//            //MainPage.Log ($"remoteMqttIsConnecting: " + remoteMqttIsConnecting.ToString());
 
//            //追加:没有远程连接的权限
//            if (remoteMqttIsConnecting || remoteIsConnected)
//            {
//                return;
//            }
 
//            //lock (SendLocker) {
//            //    remoteMqttIsConnecting = true;
//            //}
//            remoteMqttIsConnecting = true;
//#if DEBUG
//            MainPage.Log($"StartCloudMqtt: 开始");
//#endif
 
//            await Task.Factory.StartNew(async () =>
//            {
//                try
//                {
//                    //lock (RemoteMqttClient) {
//                    //    //表示后面将进行连接
//                    //    remoteMqttIsConnecting = true;
 
//                    #region 初始化远程Mqtt
 
//                    RemoteMqttClient = new MqttFactory().CreateMqttClient();
 
 
//                    //(1)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理
//                    if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
//                    {
//                        RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
//                        {
//                            try
//                            {
//                                var topic = e.ApplicationMessage.Topic;
//                                //Utlis.WriteLine ("回复Topic={0}", topic);
//                                //if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.clientId}/Push/NotifySqueeze") {
 
//                                //    var mMes = CommonPage.MyEncodingUTF8.GetString (e.ApplicationMessage.Payload);
//                                //    //收到挤下线主题
//                                //    ReceiveNotifySqueezeAsync (mMes);
//                                //} else
 
//                                if (topic == $"/BusGateWayToClient/{MainPage.LoginUser.ID}" + PushNotifySqueeze)
//                                {
//                                    var mMes = CommonPage.MyEncodingUTF8.GetString(e.ApplicationMessage.Payload);
//                                    //新挤下线主题方案 收到挤下线主题
//                                    ReceiveNotifySqueezeAsync(mMes);
//                                }
//                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange")
//                                {//网关上线,需要更新aeskey
//                                    //收到网关上线消息主题
//                                    ReceiveNotifyBusGateWayInfoChange();
//                                }
//                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.macMark}/NotifyGateWayOffline")
//                                {//网关掉线                                                                                                                    //----第二步:读取账号下面的网关列表
//                                    ReceiveNotifyGateWayOffline();
//                                }
//                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.macMark}/Common/CheckGateway")
//                                {
 
//                                    var ss = CommonPage.MyEncodingUTF8.GetString(e.ApplicationMessage.Payload);
//                                    ReceiveCheckGateway(ss);
//                                }
//                                else
//                                {
 
//                                    SetGatewayOnlineResetCheck();
 
//                                    var packet = new Packet();
 
//                                    if (!string.IsNullOrEmpty(mqttEncryptKey))
//                                    {
//                                        packet.Bytes = Shared.Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
//                                    }
//                                    else
//                                    {
//                                        packet.Bytes = e.ApplicationMessage.Payload;
//                                    }
//                                    packet.IsLocal = false;
//                                    packet.Manager();
//                                }
//                            }
//                            catch { }
//                        });
//                    }
 
//                    //(2)DisconnectedHandler
//                    if (RemoteMqttClient.DisconnectedHandler == null)
//                    {
//                        RemoteMqttClient.UseDisconnectedHandler(async (e) =>
//                        {
//                            MainPage.Log($"远程连接断开");
//                            isSubscribeSuccess = false;
//                            await DisConnectRemoteMqttClient("UseDisconnectedHandler");
 
//                        });
//                    }
//                    //(3)ConnectedHandler
//                    if (RemoteMqttClient.ConnectedHandler == null)
//                    {
//                        RemoteMqttClient.UseConnectedHandler(async (e) =>
//                        {
//                            IfNeedReadAllDeviceStatus = true;
//                            bNeedStartTip = true;//
//                            bNeedConnectTip = true;
//                            MainPage.Log($"============>Mqtt远程连接成功");
//                            SendPushSignOut();
 
 
//                            //if (CommonPage.IsRemote) {
//                            //    Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
//                            //}
//                            //if (MqttInfoConfig.Instance.CurRemoteMACInfo != null) {
//                            //    IsGatewayOnline = MqttInfoConfig.Instance.CurRemoteMACInfo.isValid != "InValid";
//                            //    if (!IsGatewayOnline) {
//                            //        //网关不在线
//                            //        if (CommonPage.IsRemote) {
//                            //            Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
//                            //            MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline));
//                            //            //发送一次CheckGateway主题
//                            //            MqttRemoteSend (new byte [] { 0 }, 3);
//                            //        }
//                            //    } else {
//                            //        //网关在线
//                            //        //重新一次所有设备状态
//                            //        CheckIfNeedReadAllDeviceStatus ();
//                            //        //
//                            //        //MqttRemoteSend (new byte [] { 0 }, 3);
//                            //        if (CommonPage.IsRemote) {
//                            //            MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
//                            //        }
//                            //    }
//                            //}
 
//                            if (CommonPage.IsRemote)
//                            {
//                                Utlis.ShowAppLinkStatus(AppLinkStatus.CloudLink);
//                                MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
//                                //
//                                //MqttRemoteSend (new byte [] { 0 }, 3);
//                                ////读取搜索网关,判断网关是否在线
//                                //CheckGatewaysIfOnline ();
//                                ////连接成功后检测是否需要通过远程获取Key
//                                //CheckIfNeedGetLocalPasswordFromRemote ();
//                            }
 
//                        });
//                    }
//                    #endregion
 
//                    //}
 
//                    //(4)===========开始连接过程==========
//                    //MainPage.Log ($"CheckMQTTConnectAsync");
//                    //之前已经获取参数成功过
//                    if (MqttInfoConfig.Instance.IfGetMqttInfoSuccess)
//                    {
//                        //判断是否需要重新获取
//                        await CheckMQTTConnectAsync();
//                    }
//                    else
//                    {
//                        //开始获取远程连接参数
//                        await StartMQTTGetInfo();
//                    }
 
//                }
//                catch (Exception ex)
//                {
//                    MainPage.Log($"error:" + ex.Message);
//                    if (IfDEBUG)
//                    {
//                        MainPage.ShowAlertOnMainThread("error: " + ex.Message);
//                    }
//                }
//                finally
//                {
//                    //最终要释放连接状态
//                    remoteMqttIsConnecting = false;
 
//                    //lock (SendLocker) {
//                    //    remoteMqttIsConnecting = false;
//                    //}
 
//                    //连接成功才关闭Loading
//                    if (remoteIsConnected)
//                    {
//                        MainPage.LoadingTipHide();
//                        ERRORCount = 0;
//                    }
//                    else
//                    {
//                        ERRORCount++;
//                        //每5次重新提示一次
//                        if (ERRORCount > 5)
//                        {
//                            ERRORCount = 0;
//                            MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.RemoteFailure));
//                            MainPage.LoadingTipHide();
 
//                        }
//                    }
 
//#if DEBUG
//                    MainPage.Log($"StartCloudMqtt: 结束");
//#endif
//                }
 
//            });
//        }
 
//        //static bool 
 
 
//        /// <summary>
//        /// 检查网关是否在线线程
//        /// </summary>
//        static System.Threading.Thread CheckGatewaysThead;
 
//        /// <summary>
//        /// 检查网关是否在线
//        /// </summary>
//        static void CheckGatewaysIfOnline()
//        {
//            if (GatewayCommon == null) return;
 
//            try
//            {
 
//                if (CheckGatewaysThead != null)
//                    CheckGatewaysThead.Abort();
 
//                CheckGatewaysThead = new System.Threading.Thread(() =>
//                {
//                    var returnBytes = Control.ControlBytesSendHasReturn(Command.ReadGateway, GatewayCommon.SubnetID, GatewayCommon.DeviceID, new byte[] { (byte)new Random().Next(255), (byte)new Random().Next(255) });
//                    if (CommonPage.IsRemote)
//                    {
//                        if (returnBytes == null)
//                        {
//                            Application.RunOnMainThread(() =>
//                            {
//                                IsGatewayOnline = false;
//                                Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
//                                MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline));
//                                //发送一次CheckGateway主题
//                                MqttRemoteSend(new byte[] { 0 }, 3);
//                            });
//                        }
//                        else
//                        {
//                            IsGatewayOnline = true;
//                            Utlis.ShowAppLinkStatus(AppLinkStatus.CloudLink);
//                            Console.WriteLine("ReadGateway success");
//                            CheckIfNeedReadAllDeviceStatus();
//                        }
//                    }
//                })
//                { IsBackground = true };
 
//                CheckGatewaysThead.Start();
//            }
//            catch
//            {
 
//            }
//        }
 
 
//        /// <summary>
//        /// 检测是否需要发送刷新获取所有设备的命令
//        /// </summary>
//        static void CheckIfNeedReadAllDeviceStatus()
//        {
//            if (IfNeedReadAllDeviceStatus)
//            {
//                Utlis.WriteLine("ReadAllDeviceStatus");
//                IfNeedReadAllDeviceStatus = false;
//                Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus();
//            }
 
//        }
 
 
 
//        //连接错误次数统计
//        static int ERRORCount = 0;
 
//        /// <summary>
//        /// 是否需要提示
//        /// </summary>
//        static bool bNeedConnectTip = true;
 
//        /// <summary>
//        /// 从开始到连接成功,只提示1次
//        /// </summary>
//        static bool bNeedStartTip = true;
//        /// <summary>
//        /// 正在获取连接参数...
//        /// </summary>
//        static void ShowStartTip()
//        {
//            if (bNeedStartTip)
//            {
//                bNeedStartTip = false;
//                if (CommonPage.IsRemote)
//                {
//                    MainPage.LoadingTipShow(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GettingRemoteConnectionInfo));
//                }
//            }
 
//            //if (CommonPage.IsRemote) {
//            //    //MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GettingRemoteConnectionInfo));
//            //    MainPage.LoadingTipShow (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GettingRemoteConnectionInfo));
//            //}
//        }
 
//        /// <summary>
//        /// 检测之前获取的Mac与当前住宅MAC是否一致 不一致从新获取
//        /// </summary>
//        /// <returns></returns>
//        static async Task CheckMQTTConnectAsync()
//        {
//            try
//            {
//                if (MqttInfoConfig.Instance.CurRemoteMACInfo != null && MqttInfoConfig.Instance.CurRemoteMACInfo.mac == UserConfig.Instance.GatewayMAC)
//                {
//                    await MQTTConnectAsync();
//                }
//                else
//                {
//                    //Mac 变化了重新获取参数
//                    await StartMQTTGetInfo();
//                }
//            }
//            catch
//            {
//                MqttInfoConfig.Instance.IfGetMqttInfoSuccess = false;
//            }
 
//        }
 
//        /// <summary>
//        /// 开始获取Mqtt 远程参数
//        /// </summary>
//        /// <returns></returns>
//        static async Task StartMQTTGetInfo()
//        {
//            ShowStartTip();
 
//            if (!CommonPage.IsRemote)
//            {
//                return;
//            }
 
//            //--判断是当前是否分享的住宅
//            if (!UserConfig.Instance.CurrentRegion.IsOthreShare)
//            {
//                //主账号获取MQTT 远程链接信息,并连接
//                await GetMqttInfoAndMQTTConnectAsync();
//            }
//            else
//            {
//                //如果是分享过来的住宅 走下面流程
//                //--第一步:获取当前住分享宅网关信息并连接MQTT
//                await GetSingleHomeGatewayPaggerAndMQTTConnectAsync();
//            }
//        }
 
 
//        /// <summary>
//        /// 连接MQTT
//        /// </summary>
//        static async Task MQTTConnectAsync()
//        {
 
//            if (!CommonPage.IsRemote)
//            {
//                return;
//            }
 
//            if (MqttInfoConfig.Instance.CurRemoteMACInfo != null && MqttInfoConfig.Instance.mMqttInfo != null)
//            {
//                if (bNeedConnectTip)
//                {
//                    bNeedConnectTip = false;
//                    MainPage.LoadingTipShow(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GetSuccessfullyStartConnecting));
//                }
 
//                try
//                {
 
//                    var url = MqttInfoConfig.Instance.mMqttInfo.connEmqDomainPort;
 
//                    //#if DEBUG
 
//                    //                    var zdURL = "15.185.137.39";
//                    //                    if (url.Contains (zdURL)) {
//                    //                        url = url.Replace (zdURL,"106.53.216.186");
//                    //                    }
 
//                    //#endif
 
//                    var clientId = MqttInfoConfig.Instance.mMqttInfo.connEmqClientId;
//                    var username = MqttInfoConfig.Instance.mMqttInfo.connEmqUserName;
//                    var passwordRemote = MqttInfoConfig.Instance.mMqttInfo.connEmqPwd;
//                    MqttInfoConfig.Instance.CurRemoteMACInfo.clientId = clientId;
//                    //MqttInfoConfig.Instance.CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
//                    //获取参数成功,保存到本地并标记为true
 
//                    MqttInfoConfig.Instance.IfGetMqttInfoSuccess = true;
//                    MqttInfoConfig.Instance.Save();
 
//                    //Console.WriteLine ("Connect url: " + url);
//                    mqttEncryptKey = MqttInfoConfig.Instance.CurRemoteMACInfo.isNewBusproGateway ? MqttInfoConfig.Instance.CurRemoteMACInfo.aesKey : "";
 
//                    var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
//                                        .WithClientId(clientId)
//                                        .WithTcpServer(url.Split(':')[1].Substring("//".Length), int.Parse(url.Split(':')[2]))
//                                        .WithCredentials(username, passwordRemote)
//                                        .WithCleanSession()
//                                        .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
//                                        //.WithCommunicationTimeout (new TimeSpan (0, 0, 10))
//                                        .WithCommunicationTimeout(new TimeSpan(0, 0, 5))
//                                        //.WithCommunicationTimeout (new TimeSpan (0, 1, 0))
//                                        .Build();
 
//                    await DisConnectRemoteMqttClient("StartRemoteMqtt");
 
//                    //await DisConnectRemoteMqttClientWhenStart ("StartRemoteMqtt");
 
//                    var mResult = await RemoteMqttClient.ConnectAsync(options1);
 
//                    if (mResult.ResultCode == MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success)
//                    {
//                        remoteIsConnected = true;
//                        IsDisConnectingWithSendCatch = false;
//                        UnsupportedProtocolVersionCount = 0;
//                    }
//                    else
//                    {
//                        //重新中心服务器获取参数标记
//                        MqttInfoConfig.Instance.IfGetMqttInfoSuccess = false;
//                    }
 
//                }
//                catch (Exception ex)
//                {
//                    if (ex.Message == UnsupportedProtocolVersion)
//                    {
//                        UnsupportedProtocolVersionCount++;
//                        if (UnsupportedProtocolVersionCount > 5)
//                        {
//                            UnsupportedProtocolVersionCount = 0;
//                            //连续异常5次,重新中心服务器获取参数标记
//                            MqttInfoConfig.Instance.IfGetMqttInfoSuccess = false;
//                        }
 
 
//                        Console.WriteLine("Connect error UN: " + ex.Message);
//                    }
//                    else if (ex.Message == MqttCommunicationTimedOutException)
//                    {
//                        Console.WriteLine("Connect error TimedOut: " + ex.Message);
//                    }
//                    else
//                    {
//                        //重新中心服务器获取参数标记
//                        MqttInfoConfig.Instance.IfGetMqttInfoSuccess = false;
//                        Console.WriteLine("Connect error: " + ex.Message);
//                    }
 
//                    //Console.WriteLine ("Connect error: " + ex.Message);
//                    if (IfDEBUG)
//                    {
//                        MainPage.ShowAlertOnMainThread("Connect error: " + ex.Message);
//                    }
//                }
//                finally
//                {
 
//                }
 
//            }
//            else
//            {
//                MqttInfoConfig.Instance.IfGetMqttInfoSuccess = false;
//            }
 
//        }
 
//        static int UnsupportedProtocolVersionCount = 0;
//        static readonly string MqttCommunicationTimedOutException = "Exception of type 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' was thrown.";
//        //
//        static readonly string UnsupportedProtocolVersion = "Connecting with MQTT server failed (UnsupportedProtocolVersion).";
 
 
 
//        /// <summary>
//        /// 收到网关上线消息
//        /// </summary>
//        static void ReceiveNotifyBusGateWayInfoChange()
//        {
//            try
//            {
//                SetGatewayOnlineResetCheck();
//                if (CommonPage.IsRemote)
//                {
//                    //#if DEBUG
//                    MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GatewayLoginOnline));
//                    //#endif
//                    CheckIfNeedReadAllDeviceStatus();
//                }
 
//                GetSingleHomeGatewayPaggerAndMQTTConnectAsync(false);
 
//            }
//            catch { }
//        }
 
//        /// <summary>
//        /// 收到网关掉线信息
//        /// </summary>
//        static void ReceiveNotifyGateWayOffline()
//        {
//            MainPage.Log("============>Mqtt GateWayOffline");
//            IsGatewayOnline = false;
//            if (CommonPage.IsRemote)
//            {
//                Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
//                MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GatewayOffline));
 
//            }
//        }
 
 
//        /// <summary>
//        /// 收到挤下线推送
//        /// </summary>
//        static void ReceiveNotifySqueezeAsync(string mMes)
//        {
 
//            if (mMes == PushSignStr) return;//是自己的登录推送不处理
 
//            //断开远程连接
//            CommonPage.IsRemote = false;
//            if (!MainPage.LoginUser.IsLogin)
//            {
//                return;
//            }
 
//            DisConnectRemoteMqttClient("挤下线");
 
//            MainPage.LoginUser.LastTime = DateTime.MinValue;
//            MainPage.LoginUser.SaveUserInfo();
//            Room.Lists.Clear();
//            ////删除推送数据
//            //var webclient = new System.Net.WebClient ();
//            //webclient.Headers.Add (System.Net.HttpRequestHeader.Authorization, MainPage.LoginUser.LoginTokenString);
//            //webclient.DownloadStringAsync (new Uri ("https://global.hdlcontrol.com/HangZhouHdlCloudApi/ZigbeeUsers/SignOut"));
 
 
 
//            Application.RunOnMainThread(() =>
//            {
//                Utlis.ShowAppLinkStatus(AppLinkStatus.WiFi);
//                new Shared.SimpleControl.Phone.AccountLogin(MainPage.LoginUser.AccountString, "").Show();
//                SharedMethod.SharedMethod.CurPageLayout = null;
//                //CommonPage.IsRemote = false;
 
//                MainPage.LoadingTipHide();
//                MainPage.Loading.Hide();
 
//                new Alert(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.Tip), Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.LoggedOnOtherDevices),
//                    Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.Close)).Show();
//            });
 
//            //2020-06-30 删除推送数据
//            ForceUpdateUtlis.Current.SignOut();
//#if HDL
//            if (!String.IsNullOrEmpty (MainPage.LoginUser.AllVisionRegisterDevUserNameGuid)) {
//                com.freeview.global.Video.Logout ();
//            }///BusGateWayToClient/320c1fea-1866-4708-8277-e2321a4dd236/NotifyGateWayInfoChange
//#endif
 
 
//        }
 
//        /// <summary>
//        /// 收到CheckGateway主题
//        /// </summary>
//        static void ReceiveCheckGateway(string mMes)
//        {
//            if (!CommonPage.IsRemote) return;
 
//            Utlis.WriteLine("ReceiveCheckGateway!");
 
//            if (MqttInfoConfig.Instance.CurRemoteMACInfo.isNewBusproGateway)
//            {
//                SetGatewayOnlineResetCheck();
//            }
//            else
//            {
 
//            }
 
//            //CheckIfNeedReadAllDeviceStatus ();
 
//            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack>(mMes);
//            if (obj == null)
//            {
//                //SetGatewayOnlineResetCheck ();
//                return;
//            }
//            switch (obj.StateCode)
//            {
//                case "HDLUdpDataForwardServerMqttClientNoOnLine":
//                case "NoOnline":
//                case "NetworkAnomaly"://不在线
//                    IsGatewayOnline = false;
//                    MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline));
//                    Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
 
//                    break;
//                case "NoRecord"://MAC不正确
//                    IsGatewayOnline = false;
//                    MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.MACError));
//                    Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
//                    break;
//                case "Success":
//                    SetGatewayOnlineResetCheck();
//                    IsGatewayOnline = true;
//                    //MainPage.AddTip (UserConfig.Instance.CurrentRegion.Name + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
//                    break;
//                default:
//                    IsGatewayOnline = false;
//                    MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.LinkLoser));
//                    Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
//                    break;
//            }
 
//        }
//        static RemoteMACInfo CurRemoteMACInfo;
 
//        /// <summary>
//        /// 
//        /// </summary>
//        /// <param name="message">附加数据包</param>
//        /// <param name="optionType">操作类型:0=网关控制;1=订阅网关数据;2=订阅网关上线数据</param>
//        /// <returns></returns>
//        public static async Task MqttRemoteSend(byte[] message, int optionType = 0)
//        {
//            //return;
 
//            try
//            {
//                string topicName;
//                switch (optionType)
//                {
//                    case 0:
//                        topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/ON";
//                        if (!string.IsNullOrEmpty(mqttEncryptKey))
//                        {
//                            message = Shared.Securitys.EncryptionService.AesEncryptPayload(message, mqttEncryptKey);
//                        }
//                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
//                        break;
//                    case 3:
//                        topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Instance.CurRemoteMACInfo.macMark}/Common/CheckGateway";
//                        MainPage.Log("CheckGateway");
//                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
//                        break;
//                    case 4://发布新方案的挤下线主题
//                        topicName = $"/BusGateWayToClient/{MainPage.LoginUser.ID}" + PushNotifySqueeze;
//                        //message = CommonPage.MyEncodingUTF8.GetBytes (PushSignStr);
//                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
//                        break;
//                }
//            }
//            catch (Exception e)
//            {
//                //Utlis.WriteLine ($"============>Mqtt MqttRemoteSend catch");
//                if (!IsDisConnectingWithSendCatch)
//                {
//                    IsDisConnectingWithSendCatch = true;
//                    await DisConnectRemoteMqttClient("SendCatch");
//                }
//            }
//        }
//        /// <summary>
//        /// SendCatch 后执行一次断开操作
//        /// </summary>
//        static bool IsDisConnectingWithSendCatch = false;
 
 
//        /// <summary>
//        /// 是否需要读取一次所有设备状态
//        /// </summary>
//        static bool IfNeedReadAllDeviceStatus = true;
//        public static bool IsGatewayOnline = true;
//        //static int CheckGatewayCount = 0;
//        //static DateTime mCheckGatewayTime;
 
 
//        /// <summary>
//        /// 设置网关在线标志,并重置CheckGateway参数
//        /// </summary>
//        static void SetGatewayOnlineResetCheck()
//        {
 
//            //mCheckGatewayTime = DateTime.Now;
//            //CheckGatewayCount = 0;
//            if (CommonPage.IsRemote)
//            {
//                if (!IsGatewayOnline)
//                {
//                    IsGatewayOnline = true;
//                    Utlis.ShowAppLinkStatus(AppLinkStatus.CloudLink);
//                }
//            }
//        }
 
 
//        /// <summary>
//        /// 主账号获取MQTT 远程链接信息,并连接
//        /// </summary>
//        /// <returns></returns>
//        static async Task GetMqttInfoAndMQTTConnectAsync()
//        {
//            var mqttInfoRequestPar = new GetConnMqttInfoObj()
//            {
//                LoginAccessToken = MainPage.LoginUser.LoginTokenString,
//                PlatformStr = GetRandomKey(),
//                PublishPayloadJsonStr = PushSignStr,
//                Mac = UserConfig.Instance.GatewayMAC,
//            };
//            var mqttInfoRequestResult = MainPage.RequestHttpsNew(API.GetConnMqttInfo, Newtonsoft.Json.JsonConvert.SerializeObject(mqttInfoRequestPar));
 
//            if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null)
//            {
//                try
//                {
//                    var mqttInfoRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo>(mqttInfoRequestResult.ResponseData.ToString());
 
//                    if (mqttInfoRequestResult_Obj != null)
//                    {
//                        MqttInfoConfig.Instance.mMqttInfo = mqttInfoRequestResult_Obj;
//                        string url = mqttInfoRequestResult_Obj.connEmqDomainPort;
//                        string clientId = mqttInfoRequestResult_Obj.connEmqClientId;
//                        string username = mqttInfoRequestResult_Obj.connEmqUserName;
//                        string passwordRemote = mqttInfoRequestResult_Obj.connEmqPwd;
//                        if (mqttInfoRequestResult_Obj.AccountAllGateways != null && mqttInfoRequestResult_Obj.AccountAllGateways.Count > 0)
//                        {
//                            //----第二步找出是否存在匹配当前住宅的mac,存在再进行远程。
//                            MqttInfoConfig.Instance.CurRemoteMACInfo = mqttInfoRequestResult_Obj.AccountAllGateways.Find((obj) => obj.mac == UserConfig.Instance.GatewayMAC);
//                            if (MqttInfoConfig.Instance.CurRemoteMACInfo != null)
//                            {
//                                //MqttInfoConfig.Instance.CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
//                                MqttInfoConfig.Instance.CurRemoteMACInfo.clientId = clientId;
//                                //----第三步 开始连接
//                                await MQTTConnectAsync();
 
//                            }
//                        }
//                        else
//                        {
//                            //Utlis.WriteLine ("============>Please wait, failed to get gateway parameters.");
//                        }
 
//                    }
//                    else
//                    {
//                        //Utlis.WriteLine ("============>Please wait, failed to get user parameters.");
//                    }
//                }
//                catch { }
//            }
//            else
//            {
//                //Utlis.WriteLine ("Please wait, failed to get parameters.");
//                //MainPage.AddTip ("Please wait, failed to get parameters.");
//            }
 
//        }
 
//    }
//}