JLChen
2021-01-05 f500e14c0a994487070380c50c85e0929cbc8e63
Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
@@ -17,6 +17,11 @@
{
    public static class MqttCommon
    {
        /// <summary>
        /// 是否提示 远程连接的错误信息
        /// </summary>
        public static bool IfDEBUG = false;
        static string mqttEncryptKey = "";
        static string checkGatewayTopicBase64 = "";
        static RemoteMACInfo CurRemoteMACInfo = null;
@@ -57,8 +62,10 @@
            new System.Threading.Thread (async () => {
                while (true) {
                    try {
                        System.Threading.Thread.Sleep (100);
                        System.Threading.Thread.Sleep (200);
                        if (!CommonPage.IsRemote) continue;
                        if (Control.IsEnterBackground) continue;
                        await StartCloudMqtt ();
                        await CheckingSubscribeTopics ();
@@ -67,6 +74,15 @@
                }
            }) { IsBackground = true }.Start ();
        }
        public static void InitState ()
        {
            IfNeedReadAllDeviceStatus = true;
            bNeedStartTip = true;
            IsGatewayOnline = false;
            StartCloudMqtt ();
        }
        /// <summary>
        /// 是否订阅成功
@@ -83,6 +99,7 @@
            }
            try {
                if (!isSubscribeTopicSuccess) {
                    var topicFilterCommon = new TopicFilter () {
                        Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/#",
@@ -107,12 +124,30 @@
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                    };
                    var topicFilters = new TopicFilter [] { topicFilterCommon, topicFilterGateWayInfoChange, topicFilterNotifySqueeze, topicFilterNotifyGateWayOffline };
                    var result = await RemoteMqttClient.SubscribeAsync (topicFilters);
                    if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2) {
                        isSubscribeTopicSuccess = true;
                    }
                    ////2020-06-22 通用主题
                    //var topicFilterMacMark = new TopicFilter () {
                    //    Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/#",
                    //    QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                    //};
                    ////挤下线主题
                    //var topicFilterNotifySqueeze = new TopicFilter () {
                    //    Topic = $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze",
                    //    QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                    //};
                    //var topicFilters = new TopicFilter [] { topicFilterMacMark, topicFilterNotifySqueeze };
                    //var result = await RemoteMqttClient.SubscribeAsync (topicFilters);
                    //if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2) {
                    //    isSubscribeTopicSuccess = true;
                    //}
                }
            } catch (Exception ex) {
@@ -135,7 +170,7 @@
                    if (CommonPage.IsRemote) {
                        Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
                    }
                    Utlis.WriteLine ($"============>MqttRemoteDisConnectRemoteMqttClient");
                    //Utlis.WriteLine ($"============>MqttRemoteDisConnectRemoteMqttClient");
                }
            } catch (Exception e) {
@@ -153,7 +188,7 @@
        /// <summary>
        /// 外网的MQTT是否正在连接
        /// </summary>
        static bool remoteMqttIsConnecting;
        public static bool remoteMqttIsConnecting;
        static bool remoteIsConnected;
        /// <summary>
        /// 启动远程Mqtt
@@ -176,6 +211,9 @@
                    //表示后面将进行连接
                    #region 初始化远程Mqtt
                    //2020-06-22 增加
                    RemoteMqttClient = new MqttFactory ().CreateMqttClient ();
                    //(3)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理
                    if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) {
                        RemoteMqttClient.UseApplicationMessageReceivedHandler (async (e) => {
@@ -224,7 +262,7 @@
                    }
                    if (RemoteMqttClient.ConnectedHandler == null) {
                        RemoteMqttClient.UseConnectedHandler (async (e) => {
                            IfNeedReadAllDeviceStatus = true;
                            //IfNeedReadAllDeviceStatus = true;
                            mCheckGatewayTime = DateTime.Now;
                            CheckGatewayCount = 0;
                            bNeedStartTip = true;
@@ -273,10 +311,21 @@
                    }
                } catch (Exception ex) {
                    Utlis.WriteLine ($"============>Mqtt 远程连接通讯连接出异常:{ex.Message}");
                    //Utlis.WriteLine ($"============>Mqtt 远程连接通讯连接出异常:{ex.Message}");
                    MainPage.LoadingTipShow ("Connect error, trying to reconnect.");
                    if (IfDEBUG) {
                        MainPage.ShowAlertOnMainThread ("error: " + ex.Message);
                    }
                } finally {
                    //最终要释放连接状态
                    remoteMqttIsConnecting = false;
                    MainPage.LoadingTipHide ();
                    //MainPage.LoadingHide ();
                }
            });
        }
@@ -315,16 +364,25 @@
                                //----第三步 开始连接
                                await MQTTConnectAsync ();
                            } else {
                                Utlis.WriteLine ("============>Mqtt CurRemoteMACInfo null");
                                //Utlis.WriteLine ("============>Mqtt CurRemoteMACInfo null");
                                MainPage.LoadingTipShow ("Please wait, failed to get gateway parameters.");
                            }
                        }
                    } else {
                        Utlis.WriteLine ("============>Mqtt mqttInfoRequestResult_Obj null");
                        //Utlis.WriteLine ("============>Mqtt mqttInfoRequestResult_Obj null");
                        MainPage.LoadingTipShow ("Please wait, failed to get user parameters.");
                        //MainPage.LoadingTipShow ("Please wait, failed to get parameters.");
                    }
                } catch { }
                } catch {
                }
            } else {
                Utlis.WriteLine ("============>Mqtt GetInfo 失败");
                //Utlis.WriteLine ("============>Mqtt GetInfo 失败");
                MainPage.AddTip ("Please wait, failed to get parameters.");
                //MainPage.LoadingTipShow ("Please wait, failed to get parameters.");
            }
        }
@@ -350,6 +408,8 @@
                    mMqttInfo = mqttInfoRequestResult_info;
                    //--第二步:获取当前住分享宅网关信息并连接MQTT
                    await GetSingleHomeGatewayPaggerAndMQTTConnectAsync ();
                } else {
                    MainPage.LoadingTipShow ("Please wait, failed to get user parameters.");
                }
            }
        }
@@ -363,7 +423,10 @@
             
                //获取参数成功,开始连接...
                MainPage.AddTip ("Successfully obtained parameters, starting to connect...");
                //MainPage.AddTip ("Successfully obtained parameters, starting to connect...");
                MainPage.LoadingTipShow ("Please wait, connecting remotely...");
                //try {
                //    var url = mMqttInfo.connEmqDomainPort;
                //    var clientId = mMqttInfo.connEmqClientId;
@@ -389,7 +452,7 @@
                //    Console.WriteLine ("Connect error: " + ex.Message);
                //}
                string mes = "";
                //string mes = "";
                try {
                    var url = mMqttInfo.connEmqDomainPort;
@@ -397,7 +460,7 @@
                    var username = mMqttInfo.connEmqUserName;
                    var passwordRemote = mMqttInfo.connEmqPwd;
                    mes = "step1.Set Data";
                    //mes = "step1.Set Data";
                    CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
                    mqttEncryptKey = CurRemoteMACInfo.aesKey;
                    var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder ()
@@ -408,14 +471,16 @@
                                        // .WithCommunicationTimeout (new TimeSpan (0, 0, 20))
                                        .Build ();
                    mes = "step2.DisConnect";
                    //mes = "step2.DisConnect";
                    await DisConnectRemoteMqttClient ("StartRemoteMqtt");
                    //MainPage.AddTip ("Start to connect...");
                    mes = "step3.Start to connect";
                    //mes = "step3.Start to connect";
                    await RemoteMqttClient.ConnectAsync (options1);
                    mes = "step4.Connected Success";
                    //mes = "step4.Connected Success";
                    remoteIsConnected = true;
                    IsDisConnectingWithSendCatch = false;
                    MainPage.LoadingTipShow ("Remote connection succeeded.");
                    //MainPage.AddTip ("Connection succeeded!");
                    //await MqttRemoteSend (new byte [] { 0 }, 1);
@@ -423,12 +488,17 @@
                    //await MqttRemoteSend (new byte [] { 0 }, 4);
                } catch (Exception ex) {
                    mes = ex.Message;
                    //mes = ex.Message;
                    //options1 异常提示
                    //Console.WriteLine("Connect error: " + ex.Message);
                    //MainPage.ShowAlertOnMainThread ("Connect error: " + ex.Message);
                    //Console.WriteLine ("Connect error: " + ex.Message);
                    MainPage.LoadingTipShow ("Connect error.");
                    if (IfDEBUG) {
                        MainPage.ShowAlertOnMainThread ("Connect error: " + ex.Message);
                    }
                } finally {
                    MainPage.ShowAlertOnMainThread ("finally: " + mes);
                    //MainPage.ShowAlertOnMainThread ("finally: " + mes);
                    //MainPage.AddTip ("finally: " + mes);
                }
@@ -447,7 +517,8 @@
            if (bNeedStartTip) {
                bNeedStartTip = false;
                if (CommonPage.IsRemote) {
                    MainPage.AddTip ("Getting remote connection parameters...");
                    //MainPage.AddTip ("Getting remote connection parameters...");
                    MainPage.LoadingTipShow ("Please wait, getting connection parameters...");
                }
            }
        }
@@ -545,6 +616,8 @@
                    if (mGatewayRes != null) {
                        CurRemoteMACInfo.aesKey = mGatewayRes.AesKey;
                        mqttEncryptKey = CurRemoteMACInfo.aesKey;
                    } else {
                        MainPage.LoadingTipShow ("Please wait, failed to get gateway parameters.");
                    }
                }