JLChen
2020-02-28 9137222ece9b978eb97b5598f2eee6e070bcf9d6
Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
@@ -119,25 +119,26 @@
        /// <summary>
        /// 断开远程Mqtt的链接
        /// <summary>
        /// 断开远程Mqtt的链接
        /// </summary>
        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient (string s = "")
        {
            try {
                if (remoteIsConnected) {
                    remoteIsConnected = false;
                    System.Console.WriteLine ($"============>MqttRemote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient (string s = "")
        {
            try {
                if (remoteIsConnected) {
                    remoteIsConnected = false;
                    System.Console.WriteLine ($"============>MqttRemote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    await RemoteMqttClient.DisconnectAsync ();
                    if (CommonPage.IsRemote) {
                        Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
                    }
                }
                    System.Console.WriteLine ($"============>MqttRemoteDisConnectRemoteMqttClient");
                }
            } catch (Exception e) {
                System.Console.WriteLine ($"============>MqttRemote断开通讯连接出异常:{e.Message}");
            }
                System.Console.WriteLine ($"============>MqttRemote断开通讯连接出异常:{e.Message}");
            }
        }
        static DateTime dateTime = DateTime.MinValue;
@@ -267,7 +268,6 @@
                            RemoteMqttClient.UseConnectedHandler (async (e) => {
                                IfNeedReadAllDeviceStatus = true;
                                System.Console.WriteLine ($"============>Mqtt远程连接成功");
                                if (CommonPage.IsRemote) {
                                    Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
@@ -395,6 +395,7 @@
                await DisConnectRemoteMqttClient ("StartRemoteMqtt");
                await RemoteMqttClient.ConnectAsync (options1);
                remoteIsConnected = true;
                IsDisConnectingWithSendCatch = false;
                //await MqttRemoteSend (new byte [] { 0 }, 1);
                //await MqttRemoteSend (new byte [] { 0 }, 2);
                //await MqttRemoteSend (new byte [] { 0 }, 4);
@@ -402,67 +403,112 @@
            }
        }
        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="message">附加数据包</param>
        ///// <param name="optionType">操作类型:0=网关控制;1=订阅网关数据;2=订阅网关上线数据;3=订阅网关是否在线主题  4=订阅挤下线主题 </param>
        ///// <returns></returns>
        //public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
        //{
        //    try {
        //        if (!remoteIsConnected) {
        //            System.Console.WriteLine ($"============>Mqtt 未连接 取消发送");
        //            return;
        //        }
        //        var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid;
        //        switch (optionType) {
        //        case 0:
        //            var messageSend = message;
        //            if (string.IsNullOrEmpty (mqttEncryptKey)) {
        //                topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
        //            } else {
        //                topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/NewON";
        //                messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
        //            }
        //            //base64加密
        //            var m = new MqttApplicationMessage { Topic = topicName, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
        //            //if (remoteIsConnected) {
        //            try {
        //                RemoteMqttClient.PublishAsync (m);
        //            } catch (Exception e) {
        //                //await DisConnectRemoteMqttClient (e.Message);
        //                //await StartCloudMqtt ();
        //                //if (remoteIsConnected) {
        //                //    RemoteMqttClient.PublishAsync (m);
        //                //}
        //            }
        //            //}
        //            break;
        //        case 3:
        //            topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
        //            var m1 = new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
        //            try {
        //                Console.WriteLine ("CheckGateway");
        //                RemoteMqttClient.PublishAsync (m1);
        //            } catch (Exception e) {
        //                Console.WriteLine ($"CheckGateway Fail:{e.Message}");
        //                //await DisConnectRemoteMqttClient (e.Message);
        //                //await StartCloudMqtt ();
        //            }
        //            break;
        //        }
        //    } catch (Exception e) {
        //    }
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message">附加数据包</param>
        /// <param name="optionType">操作类型:0=网关控制;1=订阅网关数据;2=订阅网关上线数据;3=订阅网关是否在线主题  4=订阅挤下线主题 </param>
        /// <param name="optionType">操作类型:0=网关控制;1=订阅网关数据;2=订阅网关上线数据</param>
        /// <returns></returns>
        public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
        {
            try {
                if (!remoteIsConnected) {
                    System.Console.WriteLine ($"============>Mqtt 未连接 取消发送");
                    return;
                }
                //if (!remoteIsConnected) {
                //    System.Console.WriteLine ($"============>Mqtt 未连接 取消发送");
                //    return;
                //}
                var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid;
                string topicName;
                switch (optionType) {
                case 0:
                    var messageSend = message;
                    if (string.IsNullOrEmpty (mqttEncryptKey)) {
                        topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
                    } else {
                        topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/NewON";
                        messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
                    topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/ON";
                    if (!string.IsNullOrEmpty (mqttEncryptKey)) {
                        message = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
                    }
                    //base64加密
                    var m = new MqttApplicationMessage { Topic = topicName, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
                    //if (remoteIsConnected) {
                    try {
                         RemoteMqttClient.PublishAsync (m);
                    } catch (Exception e) {
                        //await DisConnectRemoteMqttClient (e.Message);
                        //await StartCloudMqtt ();
                        //if (remoteIsConnected) {
                        //    RemoteMqttClient.PublishAsync (m);
                        //}
                    }
                    //}
                    await RemoteMqttClient.PublishAsync (new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                    break;
                case 3:
                    topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
                    var m1 = new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
                    try {
                        Console.WriteLine ("CheckGateway");
                         RemoteMqttClient.PublishAsync (m1);
                    } catch (Exception e) {
                        Console.WriteLine ($"CheckGateway Fail:{e.Message}");
                        //await DisConnectRemoteMqttClient (e.Message);
                        //await StartCloudMqtt ();
                    }
                    Console.WriteLine ("CheckGateway");
                    await RemoteMqttClient.PublishAsync (new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                    break;
                }
            } catch (Exception e) {
                // System.Console.WriteLine ($"============>Mqtt MqttRemoteSend catch");
                 if (!IsDisConnectingWithSendCatch) {
                    IsDisConnectingWithSendCatch = true;
                    await DisConnectRemoteMqttClient ("MqttRemoteSendCatch");
                }
            }
        }
        /// <summary>
        /// SendCatch 后执行一次断开操作
        /// </summary>
        static bool IsDisConnectingWithSendCatch = false;
        /// <summary>
        /// 分享住宅 获取当前住宅网关信息并且连接MQTT 或者刷新