From ed3bfb7462d44747230437717e8673a5192f833f Mon Sep 17 00:00:00 2001
From: 陈嘉乐 <cjl@hdlchina.com.cn>
Date: 星期一, 30 十一月 2020 20:34:51 +0800
Subject: [PATCH] 2020-11-30-2

---
 HDL_ON/DAL/Net/Mqtt_Cloud.cs |  463 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 463 insertions(+), 0 deletions(-)

diff --git a/HDL_ON/DAL/Net/Mqtt_Cloud.cs b/HDL_ON/DAL/Net/Mqtt_Cloud.cs
new file mode 100644
index 0000000..ea35f24
--- /dev/null
+++ b/HDL_ON/DAL/Net/Mqtt_Cloud.cs
@@ -0,0 +1,463 @@
+锘縰sing System;
+using MQTTnet.Client;
+using System.Threading.Tasks;
+using Shared;
+using MQTTnet;
+using System.Text;
+using HDL_ON.Entity;
+
+namespace HDL_ON.DAL.Net
+{
+    public static class Mqtt_Cloud
+    {
+        static string mqttEncryptKey = "";
+        static string checkGatewayTopicBase64 = "";
+        static RemoteMACInfo CurRemoteMACInfo = null;
+
+        /// <summary>
+        /// 鎵嬫満鏍囪瘑
+        /// </summary>
+        static Guid currentGuid = Guid.NewGuid();
+
+        /// <summary>
+        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
+        /// </summary>
+        /// <summary>
+        /// 杩滅▼MqttClient
+        /// </summary>
+        /// <summary>
+        /// 杩滅▼MqttClient
+        /// </summary>
+        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
+
+        static bool thisShowTip = true;
+        //static string mqttRequestParToken="";
+        /// <summary>
+        /// 鎺ㄩ�佹爣璇�
+        /// </summary>
+        static string PushSignStr = System.DateTime.Now.Ticks.ToString();
+
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// </summary>
+        public static async Task DisConnectRemoteMqttClient(string s = "")
+        {
+            try
+            {
+                if (remoteIsConnected)
+                {
+                    remoteIsConnected = false;
+                    MainPage.Log($"Remote涓诲姩鏂紑_{s}");
+                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
+                    await RemoteMqttClient.DisconnectAsync();
+                }
+            }
+            catch (Exception e)
+            {
+                System.Console.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
+        }
+        static DateTime dateTime = DateTime.MinValue;
+        /// <summary>
+        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
+        /// </summary>
+        static bool remoteMqttIsConnecting;
+        static bool remoteIsConnected;
+
+        static Mqtt_Cloud()
+        {
+            InitMqtt();
+        }
+
+        public static bool IsInitMqtt = false;
+
+        static void InitMqtt()
+        {
+            new System.Threading.Thread(async () => {
+                while (true)
+                {
+                    try
+                    {
+                        System.Threading.Thread.Sleep(1000);
+                        if (!MainPage.IsRemote) continue;
+
+                        await StartCloudMqtt();
+                        await SubscribeTopics();
+                    }
+                    catch { }
+                }
+            })
+            { IsBackground = true }.Start();
+        }
+
+        static bool isSubscribeSuccess;
+        static async Task SubscribeTopics()
+        {
+            if (remoteIsConnected && !isSubscribeSuccess)
+            {
+                try
+                {
+                    var topicFilter1 = new TopicFilter { QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange" };
+                    var topicFilter2 = new TopicFilter { QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce, Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/#" };
+                    var topicFilter3 = new TopicFilter { QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.clientId}/Push/NotifySqueeze" };
+                    var result = await RemoteMqttClient.SubscribeAsync(new TopicFilter[] { topicFilter1, topicFilter2, topicFilter3 });
+                    if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2)
+                    {
+                        isSubscribeSuccess = true;
+                    }
+                }
+                catch { }
+            }
+        }
+        /// <summary>
+        /// 鍚姩杩滅▼Mqtt
+        /// </summary>
+        public static async Task StartCloudMqtt()
+        {
+            //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
+            if (remoteMqttIsConnecting
+               || remoteIsConnected || !MainPage.LoginUser.IsLogin)
+            {
+                return;
+            }
+
+            await Task.Factory.StartNew(async () => {
+                //try {
+                lock (RemoteMqttClient)
+                {
+                    //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+                    remoteMqttIsConnecting = true;
+
+                    #region 鍒濆鍖栬繙绋婱qtt
+                    //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
+                    if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
+                    {
+                        RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => {
+                            try
+                            {
+                                var topic = e.ApplicationMessage.Topic;
+                                //Console.WriteLine ("鍥炲Topic={0}", topic);
+                                if (topic == $"/BusGateWayToClient/{CurRemoteMACInfo.clientId}/Push/NotifySqueeze")
+                                {
+                                    var mMes = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                                    //鏀跺埌鎸や笅绾夸富棰�
+                                    ReceiveNotifySqueezeAsync(mMes);
+                                }
+                                else if (topic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange")
+                                {
+                                    //缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
+                                    //鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚
+                                    //ReceiveNotifyBusGateWayInfoChange();
+                                }
+                                else if (topic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/CheckGateway")
+                                {
+                                    var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                                    ReceiveCheckGateway(ss);
+                                }
+                                else
+                                {
+                                    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.Manager();
+                                }
+                            }
+                            catch { }
+                        });
+                    }
+
+                    if (RemoteMqttClient.DisconnectedHandler == null)
+                    {
+                        RemoteMqttClient.UseDisconnectedHandler(async (e) => {
+                            System.Console.WriteLine($"杩滅▼杩炴帴鏂紑");
+                            isSubscribeSuccess = false;
+                            await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler");
+                            if (MainPage.IsRemote)
+                            {
+                                Application.RunOnMainThread(() => {
+                                    //杩滅▼杩炴帴鎴愬姛
+                                });
+                            }
+                        });
+                    }
+                    if (RemoteMqttClient.ConnectedHandler == null)
+                    {
+                        RemoteMqttClient.UseConnectedHandler(async (e) => {
+                            System.Console.WriteLine($"杩滅▼杩炴帴鎴愬姛");
+                            MainPage.IsRemote = true;
+                            Application.RunOnMainThread(() => {
+                                //杩滅▼杩炴帴鎴愬姛
+                                MainPage.IsRemote = true;
+                            });
+                            //鍒锋柊鐘舵��
+                            if (CurRemoteMACInfo != null)
+                            {
+                                if (CurRemoteMACInfo.isValid == "InValid")
+                                {
+                                    //杩滅▼澶辫触
+                                    MainPage.IsRemote = false;
+                                }
+                                else
+                                {
+                                    MqttRemoteSend(new byte[] { 0 }, 3);
+                                }
+                            }
+                        });
+                    }
+                    #endregion
+                }
+
+                try
+                {
+
+                    //--绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟 鎻愪氦MAC 鏈嶅姟鍣ㄨ嚜鍔ㄥ垽鏂槸鍚︿负鏂扮綉鍏筹紝杩斿洖鏄惁闇�瑕佽嚜鍔ㄥ垏鎹㈣繙绋嬭繛鎺ョ殑鏈嶅姟鍣�
+                    var mqttInfoRequestPar = new RemoteRequestParameters()
+                    {
+                        PlatformStr = "ON",
+                        LoginAccessToken = MainPage.LoginUser.loginTokenString,
+                        RequestVersion = MainPage.VersionString,
+                        RequestProtocolType = 0,
+                        RequestSource = 1,
+                        HdlGatewayGatewayType = 0,
+                        PublishPayloadJsonStr = PushSignStr,
+                        Mac = HDL_ON.Entity.DB_ResidenceData.residenceData.residenceGatewayMAC,
+                    };
+                    var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(mqttInfoRequestPar);
+                    var mqttInfoRequestResult = new HDL_ON.DAL.Server.HttpServerRequest().RequestMqttInfo(jsonString);
+
+                    if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null)
+                    {
+                        try
+                        {
+                            var mqttInfoRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo>(mqttInfoRequestResult.ResponseData.ToString());
+
+                            if (mqttInfoRequestResult_Obj != null)
+                            {
+                                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锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
+                                    foreach (var curRegionMac in DB_ResidenceData.residenceData.residecenInfo.homeGateways)
+                                    {
+                                        CurRemoteMACInfo = mqttInfoRequestResult_Obj.AccountAllGateways.Find((obj) => obj.mac == curRegionMac.GatewayUniqueId);
+                                        if (CurRemoteMACInfo != null)
+                                        {
+                                            break;
+                                        }
+                                    }
+                                    if (CurRemoteMACInfo != null)
+                                    {
+                                        CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.loginTokenString;
+                                        CurRemoteMACInfo.clientId = clientId;
+                                        mqttEncryptKey = CurRemoteMACInfo.isNewBusproGateway ? 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()
+                                                            .WithCommunicationTimeout(new TimeSpan(0, 0, 20))
+                                                            .Build();
+
+                                        await DisConnectRemoteMqttClient("StartRemoteMqtt");
+                                        await RemoteMqttClient.ConnectAsync(options1);
+                                        remoteIsConnected = true;
+                                        IsDisConnectingWithSendCatch = false;
+
+                                    }
+                                }
+
+                            }
+                        }
+                        catch { }
+                    }
+
+                }
+                catch (Exception e)
+                {
+
+                }
+                finally
+                {
+                    //鏈�缁堣閲婃斁杩炴帴鐘舵��
+                    remoteMqttIsConnecting = false;
+                }
+
+            });
+        }
+
+
+
+        ///// <summary>
+        ///// 鏀跺埌缃戝叧涓婄嚎娑堟伅
+        ///// </summary>
+        //static void ReceiveNotifyBusGateWayInfoChange()
+        //{
+        //    var gatewayListUrl = @"https://developer.hdlcontrol.com/Center/Center/GetGatewayPagger"; //App銆丅uspro杞欢鐧诲綍鍚庤幏鍙栫綉鍏冲垪琛� http 璇锋眰
+        //    var gatewayListRequestPar = new RemoteRequestParameters() { Mac = CurRemoteMACInfo.mac, LoginAccessToken = MainPage.LoginUser.loginTokenString, RequestVersion = "RequestVersion1", RequestProtocolType = 0, RequestSource = 1 };
+        //    var gatewayListRequestResult = MainPage.RequestHttps("", Newtonsoft.Json.JsonConvert.SerializeObject(gatewayListRequestPar), false, false, gatewayListUrl);
+        //    var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo>(gatewayListRequestResult.ResponseData.ToString());
+        //    if (gatewayListRequestResult_Obj != null && gatewayListRequestResult_Obj.pageData.Count > 0)
+        //    {
+        //        CurRemoteMACInfo.aesKey = gatewayListRequestResult_Obj.pageData[0].aesKey;
+        //        mqttEncryptKey = CurRemoteMACInfo.isNewBusproGateway ? CurRemoteMACInfo.aesKey : "";
+        //    }
+        //}
+
+        /// <summary>
+        /// 鏀跺埌鎸や笅绾挎帹閫�
+        /// </summary>
+        static void ReceiveNotifySqueezeAsync(string mMes)
+        {
+            if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
+            //鏂紑杩滅▼杩炴帴
+            MainPage.IsRemote = false;
+            if (!MainPage.LoginUser.IsLogin)
+            {
+                return;
+            }
+            MainPage.LoginUser.lastTime = DateTime.MinValue;
+            MainPage.LoginUser.SaveUserInfo();
+
+            string oldRegionRootPath = FileUtils.CreateRegionBackup(DB_ResidenceData.residenceData.CurReginID.ToString());
+            new System.Threading.Thread(() =>
+            {
+                try
+                {
+                    var backuplist = FileUtils.ReadFiles();
+                    FileUtils.DeleteRegionFiles(oldRegionRootPath);
+                    //绉诲姩鏂囦欢
+                    foreach (var fileName in backuplist)
+                    {
+                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileUtils.RootPath + fileName);
+                        if (fileName == "headImage.png")
+                        {
+                            continue;
+                        }
+                        if (fileInfo.Exists)
+                        {
+                            fileInfo.MoveTo(oldRegionRootPath + fileName);
+                            MainPage.Log("move file : " + fileName);
+                        }
+                    }
+                    //鍒犻櫎鏈湴鏂囦欢
+                    foreach (var fileName in backuplist)
+                    {
+                        if (fileName == "headImage.png")
+                        {
+                            continue;
+                        }
+                        FileUtils.DeleteFile(fileName);
+                    }
+                }
+                catch (Exception ex)
+                {
+                    MainPage.Log(ex.Message);
+                }
+                finally
+                {
+                }
+            })
+            { IsBackground = true }.Start();
+
+
+            //鍒犻櫎鎺ㄩ�佹暟鎹�
+            DisConnectRemoteMqttClient("鎸や笅绾�");
+            Application.RunOnMainThread(() =>
+            {
+                MainPage.GoLoginPage(MainPage.LoginUser);
+            });
+        }
+
+        /// <summary>
+        /// 鏀跺埌CheckGateway涓婚
+        /// </summary>
+        static void ReceiveCheckGateway(string mMes)
+        {
+            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack>(mMes);
+            if (obj == null)
+            {
+                return;
+            }
+            switch (obj.StateCode)
+            {
+                case "HDLUdpDataForwardServerMqttClientNoOnLine":
+                case "NoOnline":
+                case "NetworkAnomaly"://涓嶅湪绾�
+                    Application.RunOnMainThread(() =>
+                    {
+                        new HDL_ON.UI.PublicAssmebly().TipMsgAutoClose(Language.StringByID(StringId.RemoteFailedGatewayOffline), true);
+                    });
+                    break;
+                case "NoRecord"://MAC涓嶆纭�
+                    Application.RunOnMainThread(() => {
+                        new HDL_ON.UI.PublicAssmebly().TipMsgAutoClose(Language.StringByID(StringId.MACError), true);
+                    });
+                    break;
+                case "Success":
+                    break;
+                default:
+                    Application.RunOnMainThread(() => {
+                        new HDL_ON.UI.PublicAssmebly().TipMsgAutoClose(Language.StringByID(StringId.LinkLoser), true);
+                    });
+                    break;
+            }
+
+        }
+
+        /// <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)
+        {
+            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/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
+                        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("SendCatch");
+                }
+            }
+        }
+        /// <summary>
+        /// SendCatch 鍚庢墽琛屼竴娆℃柇寮�鎿嶄綔
+        /// </summary>
+        static bool IsDisConnectingWithSendCatch = false;
+
+    }
+}
+

--
Gitblit v1.8.0