From 5a5a2b696866f947b6025d26c3302e8ffef46435 Mon Sep 17 00:00:00 2001 From: JLChen <551775569@qq.com> Date: 星期一, 11 一月 2021 16:11:20 +0800 Subject: [PATCH] 2021-01-11 1.更新MQTT连接和本地搜索网关方法。2.子账号相关接口完善 --- Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs | 1765 +++++++++++++++++++++++++--------------------------------- 1 files changed, 758 insertions(+), 1,007 deletions(-) diff --git a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs index 2536317..761d256 100644 --- a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs +++ b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs @@ -11,341 +11,559 @@ using System.Text; using System.Security.Cryptography; using System.IO; -using Shared.SimpleControl.Phone; namespace SmartHome { public static class MqttCommon { + /// <summary> + /// 鏄惁鎻愮ず 杩滅▼杩炴帴鐨勯敊璇俊鎭� + /// </summary> + public static bool IfDEBUG = false; + + /// <summary> + /// 鍔犲瘑閫氳KEY + /// </summary> static string mqttEncryptKey = ""; - static string checkGatewayTopicBase64 = ""; - static RemoteMACInfo CurRemoteMACInfo = null; - static MqttInfo mMqttInfo = null; + //static string checkGatewayTopicBase64 = ""; /// <summary> - /// 鎵嬫満鏍囪瘑 + /// 鎸や笅绾夸富棰� /// </summary> - static Guid currentGuid = Guid.NewGuid (); + static readonly string PushNotifySqueeze = "/Push/NotifySqueeze"; + + ///// <summary> + ///// 鎸や笅绾夸富棰� + ///// </summary> + //static readonly string TopicToApp = "/Push/NotifySqueeze"; + /// <summary> - /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴 + /// 闅忔満Key /// </summary> - /// <summary> - /// 杩滅▼MqttClient - /// </summary> + static string RandomKey = ""; + + static string GetRandomKey () + { + if (string.IsNullOrEmpty (RandomKey)) { + //闅忔満2浣嶅瓧绗︿覆 + RandomKey = Utlis.CreateRandomString (2); + } + + return RandomKey; + + } + /// <summary> /// 杩滅▼MqttClient /// </summary> public static IMqttClient RemoteMqttClient = new MqttFactory ().CreateMqttClient (); - //static bool thisShowTip = true; - static string mqttRequestParToken = ""; - - static MqttCommon () - { - InitMqtt (); - } - - public static async System.Threading.Tasks.Task InitMqtt () - { - new System.Threading.Thread (async () => { - while (true) { - System.Threading.Thread.Sleep (100); - if (!CommonPage.IsRemote) continue; - - await StartCloudMqtt (); - await CheckingSubscribeTopics (); - - } - }) { IsBackground = true }.Start (); - } - - /// <summary> - /// 鏄惁璁㈤槄鎴愬姛 - /// </summary> - static bool isSubscribeTopicSuccess = false; - /// <summary> - /// 妫�鏌ヤ富棰樻槸鍚﹁闃呭け璐� - /// </summary> - /// <returns></returns> - static async Task CheckingSubscribeTopics () - { - if (!remoteIsConnected) { - return; - } - try { - if (!isSubscribeTopicSuccess) { - - var topicFilterCommon = new TopicFilter () { - Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/#", - QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce - }; - - //缃戝叧閲嶆柊鐧诲綍涓婚 - var topicFilterGateWayInfoChange = new TopicFilter () { - Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange", - QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce - }; - - //鎸や笅绾夸富棰� - var topicFilterNotifySqueeze = new TopicFilter () { - Topic = $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze", - QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce - }; - - - - var topicFilters = new TopicFilter [] { topicFilterCommon, topicFilterGateWayInfoChange, topicFilterNotifySqueeze }; - var result = await RemoteMqttClient.SubscribeAsync (topicFilters); - if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2) { - isSubscribeTopicSuccess = true; - } - } - } catch (Exception e) { - - } - } - - - - /// <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); - await RemoteMqttClient.DisconnectAsync (); - } - } catch (Exception e) { - System.Console.WriteLine ($"============>MqttRemote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); - } - } - static DateTime dateTime = DateTime.MinValue; /// <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; + Shared.Utlis.WriteLine ($"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) { + Shared.Utlis.WriteLine ($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); + } + } + + /// <summary> + /// 鏂紑杩滅▼Mqtt鐨勯摼鎺� + /// </summary> + static async Task DisConnectRemoteMqttClientWhenStart (string s = "") + { + try { + //if (remoteIsConnected) { + remoteIsConnected = false; + isSubscribeSuccess = false; + Shared.Utlis.WriteLine ($"RemoteStart涓诲姩鏂紑_{s}"); + await RemoteMqttClient.DisconnectAsync (); + + //} + } catch (Exception e) { + Shared.Utlis.WriteLine ($"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; + CommonConfig.Current.IfGetMqttInfoSuccess = false; + } + await DisConnectRemoteMqttClient (s); + } - + //static DateTime dateTime = DateTime.MinValue; /// <summary> /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴 /// </summary> - static bool remoteMqttIsConnecting; + public static bool remoteMqttIsConnecting; static bool remoteIsConnected; + + static MqttCommon () + { + InitMqtt (); + } + + public static bool IsInitMqtt = false; + + ///// <summary> + ///// 娴嬭瘯 + ///// 瀹氭椂鍙戦�� 000E + ///// </summary> + ///// <returns></returns> + //static void InitCheckGateway () + //{ + // new System.Threading.Thread (async () => { + // while (true) { + // try { + + // if (!CommonPage.IsRemote) { + // if (GatewayCommon != null) { + // Control.ControlBytesSend (Command.ReadRemark, GatewayCommon.SubnetID, GatewayCommon.DeviceID, new byte [] { }); + // Console.WriteLine ("鍙戦��000E "); + // } + // } + // System.Threading.Thread.Sleep (55000); + // } catch { } + + // } + // }) { IsBackground = true }.Start (); + //} + + + //static Thread MQTTThread; + + //static void InitMqtt () + //{ + + // remoteMqttIsConnecting = false; + // if (MQTTThread != null) + // MQTTThread.Abort (); + + // MQTTThread = new System.Threading.Thread (async () => { + // while (true) { + // try { + // System.Threading.Thread.Sleep (200); + // //if (!MainPage.LoginUser.IsLogin) { + // // continue; + // //} + // if (!CommonPage.IsRemote) continue; + + // await StartCloudMqtt (); + // await SubscribeTopics (); + // } catch { } + // } + // }) { IsBackground = true }; + + // MQTTThread.Start (); + //} + + static void InitMqtt () + { + new System.Threading.Thread (async () => { + while (true) { + try { + System.Threading.Thread.Sleep (500); + //if (!MainPage.LoginUser.IsLogin) { + // continue; + //} + + if (!CommonPage.IsRemote) continue; + + if (Control.IsEnterBackground) continue; + + await StartCloudMqtt (); + await SubscribeTopics (); + } catch { } + } + }) { IsBackground = true }.Start (); + } + + /// <summary> + /// 鍒濆鍖栫姸鎬� + /// </summary> + 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/{CommonConfig.Instance.CurRemoteMACInfo.clientId}/Push/NotifySqueeze" }; + + //2020-05-14 璁㈤槄涓婚璐ㄩ噺鏀逛负0 + var topicFilterBusGateWayToClient = new MqttTopicFilter () { + Topic = $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/#", + QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce + //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce + }; + + var topicFilterPush2 = new MqttTopicFilter { + Topic = $"/BusGateWayToClient/{MainPage.LoginUser.ID}/#", + QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce, + //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce + }; + + Utlis.WriteLine ("寮�濮嬭闃咃紒"); + var result = await RemoteMqttClient.SubscribeAsync (new MqttTopicFilter [] { topicFilterBusGateWayToClient, topicFilterPush2 }); + if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0) { + isSubscribeSuccess = true; + Utlis.WriteLine ("璁㈤槄鎴愬姛锛�"); + + 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 System.Threading.Tasks.Task StartCloudMqtt () + public static async Task StartCloudMqtt () { - //Application.RunOnMainThread (() => { - // if (5 < (DateTime.Now - dateTime).TotalSeconds) { - // return; - // } - // //MainPage.Loading.Start (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.Connecting)); - // dateTime = DateTime.Now; - //}); + if (UserConfig.Instance.internetStatus == 0) { + return; + } + if (!MainPage.LoginUser.IsLogin) { return; } - //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺 - if (remoteMqttIsConnecting - || remoteIsConnected) { - //System.Console.WriteLine ($"============>MqttremoteMqttIsConnecting:{remoteMqttIsConnecting} remoteIsConnected:{remoteIsConnected} "); + //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺 + if (remoteMqttIsConnecting || remoteIsConnected) { return; } + //lock (SendLocker) { + // remoteMqttIsConnecting = true; + //} remoteMqttIsConnecting = true; - await System.Threading.Tasks.Task.Factory.StartNew (async () => { +#if DEBUG + Shared.Utlis.WriteLine ($"StartCloudMqtt: 寮�濮�"); +#endif + + await Task.Factory.StartNew (async () => { try { //lock (RemoteMqttClient) { - //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� + // //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� + // remoteMqttIsConnecting = true; - #region 鍒濆鍖栬繙绋婱qtt - //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 - if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) { - RemoteMqttClient.UseApplicationMessageReceivedHandler (async (e) => { - try { - if (!RemoteMqttClient.IsConnected || !CommonPage.IsRemote) { - return; - } - var aesDecryptTopic = e.ApplicationMessage.Topic; - var aesDecryptPayload = e.ApplicationMessage.Payload; - //Console.WriteLine ("Topic={0}", aesDecryptTopic); + #region 鍒濆鍖栬繙绋婱qtt - //if (aesDecryptTopic == $"NotifyBusGateWayInfoChagne/{CurRemoteMACInfo.md5_mac_string}") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey - //2020-01-11 淇敼璁㈤槄涓婚鍦板潃 - if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛� - await ReceiveNotifyBusGateWayInfoChange (); - } else if (aesDecryptTopic == $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze") {//璁㈤槄鎸や笅绾块棶棰� - await ReceiveNotifySqueezeAsync (aesDecryptPayload); - }else if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/CheckGateway") { - MainPage.WiFiStatus = "CrabtreeAdd/CloudUnlink.png"; - // = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON"; - var ss = CommonPage.MyEncodingUTF8.GetString (aesDecryptPayload); - var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack> (ss); - if (obj == null) { - return; - } - switch (obj.StateCode) { - case "HDLUdpDataForwardServerMqttClientNoOnLine": - case "NoOnline": - case "NetworkAnomaly"://涓嶅湪绾� - MainPage.AddTip ("Gateway offline"); - //Application.RunOnMainThread (() => { - // Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - //}); - break; - case "NoRecord"://MAC涓嶆纭� - MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.MACError)); - //Application.RunOnMainThread (() => { - // Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - //}); - break; - case "Success": - MainPage.AddTip (UserConfig.Instance.CurrentRegion.Name + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess)); - MainPage.WiFiStatus = "CrabtreeAdd/CloudLink.png"; - break; - default: - MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkLoser)); - //Application.RunOnMainThread (() => { - // Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - //}); - break; - } - Application.RunOnMainThread (() => { - UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus; - }); - } else { - if (!string.IsNullOrEmpty (mqttEncryptKey)) { - aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey); - } + RemoteMqttClient = new MqttFactory ().CreateMqttClient (); - } + + //(1)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 + if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) { + RemoteMqttClient.UseApplicationMessageReceivedHandler ((e) => { + try { + var topic = e.ApplicationMessage.Topic; + if (topic == $"/BusGateWayToClient/{MainPage.LoginUser.ID}" + PushNotifySqueeze) { + var mMes = CommonPage.MyEncodingUTF8.GetString (e.ApplicationMessage.Payload); + //鏂版尋涓嬬嚎涓婚鏂规 鏀跺埌鎸や笅绾夸富棰� + ReceiveNotifySqueezeAsync (mMes); + } else if (topic == $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/NotifyBusGateWayInfoChange") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey + //鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚 + ReceiveNotifyBusGateWayInfoChange (); + } else if (topic == $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/NotifyGateWayOffline") {//缃戝叧鎺夌嚎 //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛� + ReceiveNotifyGateWayOffline (); + } else if (topic == $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway") { + var ss = CommonPage.MyEncodingUTF8.GetString (e.ApplicationMessage.Payload); + ReceiveCheckGateway (ss); + } else { + + SetGatewayOnlineResetCheck (); + var packet = new Packet (); - packet.IsLocal = false; - packet.Bytes = aesDecryptPayload; - packet.Manager (); - } catch { } - }); - } - if (RemoteMqttClient.DisconnectedHandler == null) { - RemoteMqttClient.UseDisconnectedHandler (async (e) => { - System.Console.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑"); - isSubscribeTopicSuccess = false; - await DisConnectRemoteMqttClient ("StartRemoteMqtt.DisconnectedHandler"); - //await StartRemoteMqtt(); - //if (thisShowTip) { - // if (CommonPage.IsRemote) { - // Application.RunOnMainThread (() => { - // MainPage.Loading.Hide (); - // }); - // } - //} else { - // thisShowTip = true; - //} - }); - } - if (RemoteMqttClient.ConnectedHandler == null) { - RemoteMqttClient.UseConnectedHandler (async (e) => { - - Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus (); - System.Console.WriteLine ($"============>Mqtt杩滅▼杩炴帴鎴愬姛"); - if (CommonPage.IsRemote) { - Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink); - } - - if (CurRemoteMACInfo != null) { - if (CurRemoteMACInfo.isValid == "InValid") { - MainPage.AddTip ("Remote failed,gateway offline"); - //Application.RunOnMainThread (() => { - // MainPage.Loading.Hide (); - //}); + if (!string.IsNullOrEmpty (mqttEncryptKey)) { + packet.Bytes = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey); } else { - MqttRemoteSend (new byte [] { 0 }, 3); + packet.Bytes = e.ApplicationMessage.Payload; } + packet.IsLocal = false; + packet.Manager (); } + } catch { } + }); + } - }); - } - #endregion + //(2)DisconnectedHandler + if (RemoteMqttClient.DisconnectedHandler == null) { + RemoteMqttClient.UseDisconnectedHandler (async (e) => { + Shared.Utlis.WriteLine ($"杩滅▼杩炴帴鏂紑"); + isSubscribeSuccess = false; + await DisConnectRemoteMqttClient ("UseDisconnectedHandler"); + + }); + } + //(3)ConnectedHandler + if (RemoteMqttClient.ConnectedHandler == null) { + RemoteMqttClient.UseConnectedHandler (async (e) => { + IfNeedReadAllDeviceStatus = true; + bNeedStartTip = true;// + bNeedConnectTip = true; + Shared.Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鎴愬姛"); + SendPushSignOut (); + + //if (CommonPage.IsRemote) { + // //Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink); + // MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess)); + //} + }); + } + #endregion //} - mqttRequestParToken = MainPage.LoginUser.LoginTokenString; - //--绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟 - var mqttInfoRequestResult = new ResponsePack () { StateCode = "" }; - //--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢 - if (!UserConfig.Instance.CurrentRegion.IsOthreShare) { - var mqttInfoUrl = $"{MainPage.RequestHttpsHost}/EmqMqtt/GetConnMqttInfo";//鑾峰彇杩炴帴杩滅▼浜戠Emq Mqtt 鏈嶅姟鍣ㄨ繛鎺ヤ俊鎭� - var mqttInfoRequestPar = new GetConnMqttInfoObj () { - LoginAccessToken = mqttRequestParToken, - PlatformStr = "L1", - PublishPayloadJsonStr = PushSignStr, - }; - mqttInfoRequestResult = MainPage.RequestHttps ("", Newtonsoft.Json.JsonConvert.SerializeObject (mqttInfoRequestPar), mqttInfoUrl); - if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) { - var mqttInfoRequestResult_info = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ()); - if (mqttInfoRequestResult_info != null) { - mMqttInfo = mqttInfoRequestResult_info; - //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛� - var gatewayListUrl = $"{MainPage.RequestHttpsHostMqtt}/Center/Center/GetGatewayPagger"; //App銆丅uspro杞欢鐧诲綍鍚庤幏鍙栫綉鍏冲垪琛� http 璇锋眰 - var gatewayListRequestPar = new RemoteRequestParameters () { LoginAccessToken = mqttRequestParToken, RequestVersion = "RequestVersion1", RequestProtocolType = 0, RequestSource = 1 }; - var gatewayListRequestResult = MainPage.RequestHttps ("", Newtonsoft.Json.JsonConvert.SerializeObject (gatewayListRequestPar), gatewayListUrl); - var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo> (gatewayListRequestResult.ResponseData.ToString ()); - //--鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆� - if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) { - CurRemoteMACInfo = gatewayListRequestResult_Obj.pageData.Find ((obj) => obj.mac == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId); - //CurRemoteMACInfo = gatewayListRequestResult_Obj.pageData [0]; - await MQTTConnectAsync (); - - } else { - System.Console.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧"); - } - - } - - } - } else { - //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋� - var mqttInfoRequestPar = new ShareMemberConnMqttInfoObj () { - LoginAccessToken = mqttRequestParToken, - PlatformStr = "L1", - PublishPayloadJsonStr = PushSignStr, - MainUserDistributedMark = UserConfig.Instance.CurrentRegion.MainUserDistributedMark, - HomeId = UserConfig.Instance.CurrentRegion.Id - }; - mqttInfoRequestResult = MainPage.RequestHttps (API.ShareMemberConnMqttInfo, Newtonsoft.Json.JsonConvert.SerializeObject (mqttInfoRequestPar)); - //--绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟 - if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) { - var mqttInfoRequestResult_info = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ()); - if (mqttInfoRequestResult_info != null) { - mMqttInfo = mqttInfoRequestResult_info; - //--绗簩姝ワ細鑾峰彇褰撳墠浣忓垎浜畢缃戝叧淇℃伅骞惰繛鎺QTT - await GetSingleHomeGatewayPaggerAndMQTTConnectAsync (); - - } - - } - } + //(4)===========寮�濮嬭繛鎺ヨ繃绋�========== + //涔嬪墠宸茬粡鑾峰彇鍙傛暟鎴愬姛杩� + if (CommonConfig.Current.IfGetMqttInfoSuccess) { + //鍒ゆ柇鏄惁闇�瑕侀噸鏂拌幏鍙� + await CheckMQTTConnectAsync (); + } else { + //寮�濮嬭幏鍙栬繙绋嬭繛鎺ュ弬鏁� + await StartMQTTGetInfo (); + } } catch (Exception ex) { - System.Console.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); + Shared.Utlis.WriteLine ($"error:" + ex.Message); + if (IfDEBUG) { + MainPage.ShowAlertOnMainThread ("error: " + ex.Message); + } } finally { //鏈�缁堣閲婃斁杩炴帴鐘舵�� remoteMqttIsConnecting = false; + + //lock (SendLocker) { + // remoteMqttIsConnecting = false; + //} + + //杩炴帴鎴愬姛鎵嶅叧闂璍oading + 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 + Shared.Utlis.WriteLine ($"StartCloudMqtt: 缁撴潫"); +#endif } + }); } + + //static bool + + + /// <summary> + /// 妫�鏌ョ綉鍏虫槸鍚﹀湪绾跨嚎绋� + /// </summary> + static System.Threading.Thread CheckGatewaysThead; + /// <summary> + /// 缃戝叧瀵硅薄 + /// </summary> + public static Common GatewayCommon; + /// <summary> + /// 妫�鏌ョ綉鍏虫槸鍚﹀湪绾� + /// </summary> + static void CheckGatewaysIfOnline () + { + if (GatewayCommon == null) return; + + try { + //鎻愮ず鎼滅储缃戝叧涓� + MainPage.LoadingTipShow (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.CheckingGatewayIsOnline)); + + 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) }); + //闅愯棌鎻愮ず + MainPage.LoadingTipHide (); + if (CommonPage.IsRemote) { + if (returnBytes == null) { + Application.RunOnMainThread (() => { + IsGatewayOnline = false; + Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline); + MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline)); + //鍙戦�佷竴娆heckGateway涓婚 + MqttRemoteSend (new byte [] { 0 }, 3); + }); + } else { + MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess)); + + 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> + /// 姝e湪鑾峰彇杩炴帴鍙傛暟... + /// </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涓庡綋鍓嶄綇瀹匨AC鏄惁涓�鑷� 涓嶄竴鑷翠粠鏂拌幏鍙� + /// </summary> + /// <returns></returns> + static async Task CheckMQTTConnectAsync () + { + try { + if (CommonConfig.Current.HomeGatewayInfo != null && CommonConfig.Current.HomeGatewayInfo.mac == UserConfig.Instance.GatewayMAC) { + await MQTTConnectAsync (); + } else { + //Mac 鍙樺寲浜嗛噸鏂拌幏鍙栧弬鏁� + await StartMQTTGetInfo (); + } + } catch { + CommonConfig.Current.IfGetMqttInfoSuccess = false; + } + + } + + /// <summary> + /// 寮�濮嬭幏鍙朚qtt 杩滅▼鍙傛暟 + /// </summary> + /// <returns></returns> + static async Task StartMQTTGetInfo () + { + ShowStartTip (); + + if (!CommonPage.IsRemote) { + return; + } + + await GetMqttInfoAndMQTTConnectAsync (); + + ////--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢 + //if (!UserConfig.Instance.CurrentRegion.IsOthreShare) { + // //涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴 + // await GetMqttInfoAndMQTTConnectAsync (); + //} else { + // //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋� + // //--绗竴姝ワ細鑾峰彇褰撳墠浣忓垎浜畢缃戝叧淇℃伅骞惰繛鎺QTT + // await GetSingleHomeGatewayPaggerAndMQTTConnectAsync (); + //} + } + /// <summary> /// 杩炴帴MQTT @@ -353,287 +571,317 @@ static async Task MQTTConnectAsync () { - if (CurRemoteMACInfo != null && mMqttInfo != null) { - var url = mMqttInfo.connEmqDomainPort; - var clientId = mMqttInfo.connEmqClientId; - var username = mMqttInfo.connEmqUserName; - var passwordRemote = mMqttInfo.connEmqPwd; + if (!CommonPage.IsRemote) { + return; + } - CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.LoginTokenString; - mqttEncryptKey = 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 (); + if (CommonConfig.Current.HomeGatewayInfo != null && CommonConfig.Current.mMqttInfo != null) { + if (bNeedConnectTip) { + bNeedConnectTip = false; + MainPage.LoadingTipShow (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GetSuccessfullyStartConnecting)); + } - await DisConnectRemoteMqttClient ("StartRemoteMqtt"); - await RemoteMqttClient.ConnectAsync (options1); - remoteIsConnected = true; - //await MqttRemoteSend (new byte [] { 0 }, 1); - //await MqttRemoteSend (new byte [] { 0 }, 2); - //await MqttRemoteSend (new byte [] { 0 }, 4); + try { + + var url = CommonConfig.Current.mMqttInfo.url; + + //url = HttpUtil.GetProxyEMQUrl (url); + //#if DEBUG + // url = HttpUtil.GetProxyEMQUrl (url); + + //#endif + var clientId = CommonConfig.Current.mMqttInfo.clientId; + var username = CommonConfig.Current.mMqttInfo.userName; + var passwordRemote = CommonConfig.Current.mMqttInfo.passWord; + //鑾峰彇鍙傛暟鎴愬姛锛屼繚瀛樺埌鏈湴骞舵爣璁颁负true + CommonConfig.Current.IfGetMqttInfoSuccess = true; + CommonConfig.Current.Save (); + + mqttEncryptKey = CommonConfig.Current.HomeGatewayInfo.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"); + + var mResult = await RemoteMqttClient.ConnectAsync (options1); + + if (mResult.ResultCode == MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success) { + remoteIsConnected = true; + IsDisConnectingWithSendCatch = false; + UnsupportedProtocolVersionCount = 0; + } else { + //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁� + CommonConfig.Current.IfGetMqttInfoSuccess = false; + } + + } catch (Exception ex) { + + if (ex.Message == MqttCommunicationTimedOutException) { + Console.WriteLine ("Connect error TimedOut: " + ex.Message); + } else { + //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁� + CommonConfig.Current.IfGetMqttInfoSuccess = false; + Console.WriteLine ("Connect error: " + ex.Message); + } + + //Console.WriteLine ("Connect error: " + ex.Message); + if (IfDEBUG) { + MainPage.ShowAlertOnMainThread ("Connect error: " + ex.Message); + } + } finally { + + } + + } else { + CommonConfig.Current.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 () + { + Shared.Utlis.WriteLine ("============>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 (); + + 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-08-11 鍒犻櫎鎺ㄩ�佹暟鎹� + //HDLRequest.Current.PushserivceSignOut (); + + //#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锛�"); + SetGatewayOnlineResetCheck (); + } + + /// <summary> + /// 鎺ㄩ�佹尋涓嬬嚎涓婚 + /// </summary> + static void SendPushSignOut () + { + byte [] message = CommonPage.MyEncodingUTF8.GetBytes (PushSignStr); + MqttRemoteSend (message, 4); + } + /// <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) { + //return; + try { - 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/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/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 (); - } + topicName = $"/ClientToBusGateWay/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway"; + Shared.Utlis.WriteLine ("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> + /// 涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴 + /// </summary> + /// <returns></returns> + static async Task GetMqttInfoAndMQTTConnectAsync () + { + var mqttInfoRequestResult_Obj = HttpServerRequest.Current.GetMqttRemoteInfo (GetRandomKey ()); + if (mqttInfoRequestResult_Obj != null) { + CommonConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj; + if (UserConfig.Instance.CheckHomeGatewaysNotEmpty()) { + //----绗簩姝ユ壘鍑烘槸鍚﹀瓨鍦ㄥ尮閰嶅綋鍓嶄綇瀹呯殑mac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆� + CommonConfig.Current.HomeGatewayInfo = UserConfig.Instance.HomeGateway; + if (CommonConfig.Current.HomeGatewayInfo != null) { + //----绗笁姝� 寮�濮嬭繛鎺� + await MQTTConnectAsync (); + } + } else { + Utlis.WriteLine ("============>杩樻病缁戝畾缃戝叧"); + } + + } else { + Utlis.WriteLine ("============>MqttInfo null"); } } /// <summary> /// 鍒嗕韩浣忓畢 鑾峰彇褰撳墠浣忓畢缃戝叧淇℃伅骞朵笖杩炴帴MQTT 鎴栬�呭埛鏂� - /// 2020-01-11 + /// 2020-03-17 /// </summary> static async Task GetSingleHomeGatewayPaggerAndMQTTConnectAsync (bool bNeedConnect = true) { - - var requestObj3 = new GetSingleHomeGatewayPaggerObj (); - requestObj3.ReqDto.LoginAccessToken = MainPage.LoginUser.LoginTokenString; - requestObj3.ReqDto.HomeId = UserConfig.Instance.CurrentRegion.Id; - requestObj3.ReqDto.PageSetting.Page = 1; - requestObj3.ReqDto.PageSetting.PageSize = 10; - string urlHead = MainPage.RequestHttpsHost; - if (requestObj3.IsOtherAccountCtrl) { - urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl; - requestObj3.ReqDto.LoginAccessToken = UserConfig.Instance.MasterAccountToken; - } - - var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3); - var revertObj3 = MainPage.RequestHttps (API.GetSingleHomeGatewayPagger, requestJson3, urlHead); - if (revertObj3.StateCode.ToUpper () == "SUCCESS") { - var infoResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGatewayResult> (revertObj3.ResponseData.ToString ()); - if (bNeedConnect) { - //2020-01-11 - UserConfig.Instance.SetNowHomeGateways (infoResult.PageData); - - //var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo> (revertObj3.ResponseData.ToString ()); - //--鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆� - if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) { - var mGatewayRes = infoResult.PageData.Find ((obj) => obj.GatewayUniqueId == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId); - if (mGatewayRes != null) { - CurRemoteMACInfo = new RemoteMACInfo (); - CurRemoteMACInfo.aesKey = mGatewayRes.AesKey; - CurRemoteMACInfo.mac = mGatewayRes.GatewayUniqueId; - CurRemoteMACInfo.macMark = mGatewayRes.MacMark; - CurRemoteMACInfo.isValid = mGatewayRes.MqttOnlineStatus ? "Valid" : "InValid"; - - await MQTTConnectAsync (); - } - - - } else { - System.Console.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧"); - } - } else { - var mGatewayRes = infoResult.PageData.Find ((obj) => obj.GatewayUniqueId == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId); - if (mGatewayRes != null) { - CurRemoteMACInfo.aesKey = mGatewayRes.AesKey; - mqttEncryptKey = CurRemoteMACInfo.aesKey; - } - - } - - - } - - + } - /// <summary> - /// 鏀跺埌缃戝叧涓婄嚎娑堟伅 - /// </summary> - static async Task ReceiveNotifyBusGateWayInfoChange () - { - //褰撳墠浣忓畢涓嶆槸鍒嗕韩鏉� - if (!UserConfig.Instance.CurrentRegion.IsOthreShare) { - - var gatewayListUrl = $"{MainPage.RequestHttpsHostMqtt}/Center/Center/GetGatewayPagger"; //App銆丅uspro杞欢鐧诲綍鍚庤幏鍙栫綉鍏冲垪琛� http 璇锋眰 - var gatewayListRequestPar = new RemoteRequestParameters () { Mac = CurRemoteMACInfo.mac, LoginAccessToken = mqttRequestParToken, RequestVersion = "RequestVersion1", RequestProtocolType = 0, RequestSource = 1 }; - var gatewayListRequestResult = MainPage.RequestHttps ("", Newtonsoft.Json.JsonConvert.SerializeObject (gatewayListRequestPar), gatewayListUrl); - var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo> (gatewayListRequestResult.ResponseData.ToString ()); - if (gatewayListRequestResult_Obj != null && gatewayListRequestResult_Obj.pageData.Count > 0) { - var mData = gatewayListRequestResult_Obj.pageData.Find ((obj) => obj.mac == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId); - if (mData != null) { - CurRemoteMACInfo.aesKey = mData.aesKey; - mqttEncryptKey = CurRemoteMACInfo.aesKey; - } - } - } else { - GetSingleHomeGatewayPaggerAndMQTTConnectAsync (false); - } - - } - - /// <summary> - /// 鏀跺埌鎸や笅绾挎帹閫� - /// </summary> - static async Task ReceiveNotifySqueezeAsync (byte [] mes) - { - Console.WriteLine ($"============>MqttNotifySqueeze: {ErrorCode.LoginInAnotherDevice}"); - var mMes = CommonPage.MyEncodingUTF8.GetString (mes); - if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊 - - - CommonPage.IsRemote = false; - - //if (MainPage.IsOtherDevicesLogin) return; - - if (!MainPage.LoginUser.IsLogin) { - return; - } - - MainPage.LoginUser.LastTime = DateTime.Now.AddDays (-30); - MainPage.LoginUser.SaveUserInfo (); - - DisConnectRemoteMqttClient ("LoginOut"); - - MainPage.ShowAlertOnMainThread (ErrorCode.LoginInAnotherDevice); - - Application.RunOnMainThread (() => { - MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png"; - UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus; - new AccountLogin ().Show (); - }); - - } } } -public class ShareMemberConnMqttInfoObj : GetConnMqttInfoObj -{ - - /// <summary> - /// 涓讳汉鐢ㄦ埛Id - /// </summary> - public string MainUserDistributedMark; - - /// <summary> - /// 鍒嗕韩鑰呬綇瀹匢d - /// </summary> - public string HomeId; - -} - -public class GetConnMqttInfoObj : BaseRequestObj -{ - /// <summary> - /// HdlGatewayGatewayType 缃戝叧绫诲瀷(0:涓�绔彛銆�1:BusproLinux 缃戝叧銆�2:Zigbee 缃戝叧銆�3:Knx缃戝叧) - /// </summary> - public int HdlGatewayGatewayType = 0; - /// <summary> - /// 璁惧绫诲瀷瀛楁 - /// </summary> - public string PlatformStr = ""; - /// <summary> - /// - /// </summary> - public string PublishPayloadJsonStr = ""; -} - -public class RemoteRequestParameters -{ - public string RequestVersion; - public int RequestSource; - public string LoginAccessToken; - public int RequestProtocolType; - - - public string Mac = ""; - public string GroupName = ""; - -} - -public class MqttRemoteInfo -{ - public List<RemoteMACInfo> pageData; - - public int pageIndex = 0; - public int pageSize = 10; - public int totalCount = 3; - public int totalPages = 1; - public bool hasPreviousPage = false; - public bool hasNextPage = false; -} public class MqttInfo { - public string connEmqDomainPort; - public string connEmqClientId; - public string connEmqUserName; - public string connEmqPwd; -} - -public class RemoteMACInfo -{ - public string mac; - public string macMark; - public string isValid; - public string aesKey; - public bool isNewBusproGateway; - public string groupName; - public string projectName; + /// <summary> + /// + /// </summary> + public string url; + /// <summary> + /// + /// </summary> + public string clientId; + /// <summary> + /// + /// </summary> public string userName; - - //app鑷畾涔夋暟鎹� - public string md5_mac_string; - public string LoginAccessToken; + /// <summary> + /// + /// </summary> + public string passWord; } namespace Shared.Securitys @@ -754,503 +1002,6 @@ #endregion - } -} - -/* -using System.Collections.Generic; -using System; -using MQTTnet.Client; -using System.Threading.Tasks; -using Shared; -using Shared.SimpleControl; -using MQTTnet; -using System.Text; -using System.Security.Cryptography; - -namespace SmartHome -{ - public static class MqttCommon - { - static string mqttEncryptKey = ""; - static string checkGatewayTopicBase64 = ""; - - /// <summary> - /// 鎵嬫満鏍囪瘑 - /// </summary> - static Guid currentGuid = Guid.NewGuid (); - - /// <summary> - /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴 - /// </summary> - static object isConnecting = false.ToString (); - /// <summary> - /// 杩滅▼MqttClient - /// </summary> - public static IMqttClient RemoteMqttClient; - - static bool thisShowTip = true; - - public static async Task Close (bool RemoveRemoteMqttClient = false) - { - try { - if (RemoteMqttClient != null) { - //thisShowTip = true; - await RemoteMqttClient.DisconnectAsync (); - } - if (RemoveRemoteMqttClient) { - RemoteMqttClient = null; - } - CommonPage.IsRemote = false; - Console.WriteLine ("Close Mqtt!!!"); - } catch { } - } - - static DateTime dateTime = DateTime.MinValue; - static int startCount = 0; - - //public static async Task ReSatart () - //{ - // await Close (); - // await RemoteMqttClient.ConnectAsync (options); - //} - - /// <summary> - /// 鍚姩杩滅▼Mqtt - /// </summary> - public static async System.Threading.Tasks.Task StartCloudMqtt () - { - - - Application.RunOnMainThread (() => { - if (5 < (DateTime.Now - dateTime).TotalSeconds) { - return; - } - dateTime = DateTime.Now; - }); - if (!MainPage.LoginUser.IsLogin) { - isConnecting = false.ToString (); - return; - } - while (isConnecting.ToString () == true.ToString ()) { - if (5 < (DateTime.Now - dateTime).TotalSeconds) { - break; - } - await System.Threading.Tasks.Task.Delay (500); - } - lock (isConnecting) { - if (isConnecting.ToString () == true.ToString ()) { - return; - } - isConnecting = true.ToString (); - if (RemoteMqttClient != null && RemoteMqttClient.IsConnected) { - MqttCheckGateway (); - return; - } - } - new System.Threading.Thread (async () => { - try { - if (RemoteMqttClient == null) { - var requestObj3 = new GatewayByRegionListObj () { RegionID = UserConfig.Instance.CurrentRegion.RegionID }; - var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3); - var revertObj3 = MainPage.RequestHttps ("GatewayByRegionList", requestJson3, true, false); - if (revertObj3.StateCode.ToUpper() == "SUCCESS") { - var responseDataObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GatewayRes>> (revertObj3.ResponseData.ToString ()); - var gatewayList = responseDataObj; - if (gatewayList != null && gatewayList.Count > 0) { - UserConfig.Instance.CurrentRegion.MAC = gatewayList [0].MAC; - UserConfig.Instance.SaveUserConfig (); - } - } else { - } - - //(2)鍒涘缓Mqtt瀹㈡埛绔� - RemoteMqttClient = new MqttFactory ().CreateMqttClient (); - //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 - RemoteMqttClient.UseApplicationMessageReceivedHandler (async e => { - if (isConnecting.ToString () == true.ToString ()) - isConnecting = false.ToString (); - var aesDecryptTopic = e.ApplicationMessage.Topic; - var aesDecryptPayload = e.ApplicationMessage.Payload; - if (aesDecryptTopic == "YouIpAndPortNoRecord" || aesDecryptTopic == "DecryptFail") {// --> 浣犲綋鍓嶇殑IP鍙婄鍙e湪浜戠涓嶅瓨鍦�,璇烽噸鏂扮櫥褰曡繛鎺ヤ笅! - await Close (true); - await MqttCheckGateway (); - } else if (aesDecryptTopic == @"/BeingSqueezedOffline") { - try { - Application.RunOnMainThread (() => { - MainPage.Loading.Start (""); - MainPage.LoginUser.LastTime = DateTime.MinValue; - MainPage.LoginUser.SaveUserInfo (); - Room.Lists.Clear (); - new Shared.SimpleControl.Phone.AccountLogin (MainPage.LoginUser.AccountString.ToLower (), "").Show (); - MainPage.LoginUser.LastTime = System.DateTime.MinValue; - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.LinkStatusTipColor; - if (CommonPage.IsRemote) { - SmartHome.MqttCommon.Close (true); - } - var webPush = new service.hdlcontrol.com_push.WebServicePush (); - webPush.DeleteToken_Push (UserConfig.Instance.tokenID); - }); - } catch (Exception ex) { - Console.WriteLine (ex.Message); - } finally { - Application.RunOnMainThread (() => { - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.LinkStatusTipColor; - 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 (); - }); - } -#if HDL - if (!String.IsNullOrEmpty (MainPage.LoginUser.AllVisionRegisterDevUserNameGuid)) { - com.freeview.global.Video.Logout (); - } -#endif - } else { - aesDecryptTopic = Shared.Securitys.EncryptionService.AesDecryptTopic (e.ApplicationMessage.Topic, mqttEncryptKey); - aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey); - } - if (aesDecryptTopic == @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/CheckGateway/" + UserConfig.Instance.GatewayMAC.Replace (".", "")) { - var ss = CommonPage.MyEncodingUTF8.GetString (aesDecryptPayload); - var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack> (ss); - if (obj == null) { - return; - } - switch (obj.StateCode) { - case "HDLUdpDataForwardServerMqttClientNoOnLine": - case "NoOnline": - case "NetworkAnomaly"://涓嶅湪绾� - MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline)); - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - }); - break; - case "NoRecord"://MAC涓嶆纭� - MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.MACError)); - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - }); - break; - case "Success": - CommonPage.IsRemote = true; - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = 0xAA69E64A; - Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus (); - }); - MainPage.AddTip (UserConfig.Instance.CurrentRegion.RegionName + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess)); - break; - default: - MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkLoser)); - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - }); - break; - } - } else { - var packet = new Packet (); - packet.Bytes = aesDecryptPayload; - packet.Manager (); - } - }); - - RemoteMqttClient.UseDisconnectedHandler (e => { - //Console.WriteLine ("RemoteMqttClient UseDisconnectedHandler"); - if (thisShowTip) { - if (CommonPage.IsRemote) { - //MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteConnectionDisconnected)); - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - }); - } - } else { - thisShowTip = true; - } - }); - RemoteMqttClient.UseConnectedHandler (async e => { - //Console.WriteLine ("RemoteMqttClient IsRemote"); - await MqttCheckGateway (); - }); - } - - var requestObj = new LoginObj () { Account = MainPage.LoginUser.AccountString.ToLower (), Password = MainPage.LoginUser.Password, Company = MainPage.SoftSmsType }; - var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj); - var tempResult = MainPage.RequestHttps ("Login", requestJson, false); - if (tempResult == null) { - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; - }); - System.Console.WriteLine ($"閲嶆柊杩炴帴杩滅▼閫氳澶辫触锛屽洜涓鸿幏鍙栨柊鐨凨EY澶辫触"); - return; - } - //var messgae = System.Text.Encoding.UTF8.GetString (tempResult); - - var responsePack = tempResult.ResponseData;// Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (messgae); - //if (responsePack == null || responsePack ["ResponseData"] == null) { - // Console.WriteLine ("鏂紑鍚庨噸鏂伴摼鎺ラ渶瑕侀噸鏂扮櫥褰曡幏鍙栬繛鎺ョ殑瀵嗙爜澶辫触"); - // return; - //} - var dictrionaryResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (tempResult.ResponseData.ToString ()); - //var dictrionaryResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (responsePack ["ResponseData"].ToString ()); - //////杩樻湁绉嶆儏鍐垫槸鍚屼竴涓狪D 鏈夊涓澶囩敤杩欎釜id杩炴帴锛堜細瀵艰嚧涓柇锛� - mqttEncryptKey = dictrionaryResult ["HdlOnMqttKey"]?.ToString (); - var url = dictrionaryResult ["ConnectMqttBrokerLoadSubDomain"]?.ToString (); - var clientId = dictrionaryResult ["ConnectMqttClientId"]?.ToString (); - var username = dictrionaryResult ["ConnectMqttBrokerUserName"]?.ToString (); - var passwordRemote = dictrionaryResult ["ConnectMqttBrokerPwd"]?.ToString (); - - if (clientId == null || username == null || passwordRemote == null) { - return; - } - - ////(1)杩炴帴鍒颁簯绔殑Mqtt瀹㈡埛绔繛鎺ュ弬鏁� - var options = 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, 10)) - .Build (); - - await Close (); - await RemoteMqttClient.ConnectAsync (options); - } catch (Exception ex) { - System.Console.WriteLine ("============>" + ex.Message); - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - isConnecting = false.ToString (); - - Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor; -#if DEBUG - Alert a = new Alert (isConnecting.ToString (), ex.Message, "Close"); - a.Show (); -#endif - if (MqttCommon.RemoteMqttClient != null) { - MqttCommon.RemoteMqttClient.Dispose (); - } - if (MqttCommon.RemoteMqttClient != null) { - MqttCommon.RemoteMqttClient = null; - } - }); - } finally { - isConnecting = false.ToString (); - Application.RunOnMainThread (() => { - MainPage.Loading.Hide (); - }); - } - }) { IsBackground = true }.Start (); - } - - /// <summary> - /// Logins the by PWDA sync. - /// </summary> - public static async System.Threading.Tasks.Task<byte []> LoginByPWDAsync (string account, string password, string source = "", int company = 0) - { - try { - var result = await MainPage.RequestHttpsResultAsync ("Login", - System.Text.Encoding.UTF8.GetBytes (Newtonsoft.Json.JsonConvert.SerializeObject (new Dictionary<string, object> { - ["Account"] = account, - ["Password"] = password, - ["Source"] = source, - ["Company"] = company - }))); - return result; - } catch { - return null; - } - } - - /// <summary> - /// 灏咮ase64瀛楃涓诧紝杞崲鎴愬悎娉曠殑Mqtt涓婚 - /// </summary> - /// <param name="baseSexFourEncStr"></param> - /// <returns></returns> - public static string BaseSexFourStrToMqttTopic (string baseSexFourEncStr) - { - baseSexFourEncStr = baseSexFourEncStr.Replace ("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]"); - baseSexFourEncStr = baseSexFourEncStr.Replace ("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]"); - return baseSexFourEncStr; - } - - public static async System.Threading.Tasks.Task MqttRemoteSend (byte [] message) - { - try { - if (RemoteMqttClient == null || !RemoteMqttClient.IsConnected) { - await StartCloudMqtt (); - } - if (!RemoteMqttClient.IsConnected) { - return; - } - var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid; - - //base64鍔犲瘑涓婚 - checkGatewayTopicBase64 = Shared.Securitys.EncryptionService.AesEncryptTopic (topicName, mqttEncryptKey); - - //BaseSexFourStrToMqttTopic - var topicNameSend = BaseSexFourStrToMqttTopic (checkGatewayTopicBase64); - - //base64鍔犲瘑涓讳綋 - var messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey); - - var m = new MqttApplicationMessage { Topic = topicNameSend, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }; - await RemoteMqttClient?.PublishAsync (m); - } catch (Exception e) { - isConnecting = false.ToString (); - } - } - - public static async Task MqttCheckGateway () - { - try { - if (RemoteMqttClient == null || !RemoteMqttClient.IsConnected) { - await StartCloudMqtt (); - } - if (!RemoteMqttClient.IsConnected) { - return; - } - var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/CheckGateway/" + UserConfig.Instance.GatewayMAC.Replace (".", ""); - Console.WriteLine ("MqttCheckGateway : " + topicName); - //base64鍔犲瘑涓婚 - var topicNameBase64 = Shared.Securitys.EncryptionService.AesEncryptTopic (topicName, mqttEncryptKey); - - //BaseSexFourStrToMqttTopic - var topicNameSend = BaseSexFourStrToMqttTopic (topicNameBase64); - - //base64鍔犲瘑涓婚 - var messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (new byte [] { 2, 1 }, mqttEncryptKey); - - var m = new MqttApplicationMessage { Topic = topicNameSend, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }; - await RemoteMqttClient?.PublishAsync (m); - } catch (Exception e) { - isConnecting = false.ToString (); - } - } - } -} - - - -namespace Shared.Securitys -{ - public partial class EncryptionService - { - - #region 鍔犲瘑 - /// <summary> - /// 鍔犲瘑涓婚涓築ase64 - /// </summary> - /// <param name="pToEncrypt"></param> - /// <param name="key"></param> - /// <returns></returns> - public static string AesEncryptTopic (string pToEncrypt, string key) - { - if (string.IsNullOrEmpty (pToEncrypt)) return null; - //闇�瑕佸姞瀵嗗唴瀹圭殑鏄庢枃娴� - Byte [] toEncryptArray = Encoding.UTF8.GetBytes (pToEncrypt); - - //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�) - RijndaelManaged rm = new RijndaelManaged { - Key = Encoding.UTF8.GetBytes (key), - IV = Encoding.UTF8.GetBytes (key), - Mode = CipherMode.CBC, - Padding = PaddingMode.PKCS7 - }; - - //鍒涘缓AES鍔犲瘑鍣ㄥ璞� - ICryptoTransform cTransform = rm.CreateEncryptor (); - - //浣跨敤AES灏嗘槑鏂囨祦杞垚瀵嗘枃瀛楄妭鏁扮粍 - Byte [] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length); - - //灏咥ES鐢熸垚鐨勫瘑鏂囧瓧鑺傛暟缁勮浆鎴怋ase64瀛楃涓� - return Convert.ToBase64String (resultArray, 0, resultArray.Length); - } - - - /// <summary> - /// 鍔犲瘑璐熻浇涓轰簩杩涘埗娴� - /// </summary> - /// <param name="toEncryptArray"></param> - /// <param name="key"></param> - /// <returns></returns> - public static byte [] AesEncryptPayload (byte [] toEncryptArray, string key) - { - //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�) - var rm = new RijndaelManaged { - Key = Encoding.UTF8.GetBytes (key), - IV = Encoding.UTF8.GetBytes (key), - Mode = CipherMode.CBC, - Padding = PaddingMode.PKCS7 - }; - - //鍒涘缓AES鍔犲瘑鍣ㄥ璞� - var cTransform = rm.CreateEncryptor (); - //浣跨敤AES灏嗘槑鏂囨祦杞垚瀵嗘枃瀛楄妭鏁扮粍 - return cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length); - } - #endregion - - - #region 瑙e瘑 - /// <summary> - /// 瑙e瘑涓婚鏁版嵁 - /// </summary> - /// <param name="pToDecrypt"></param> - /// <param name="key"></param> - /// <returns></returns> - public static string AesDecryptTopic (string pToDecrypt, string key) - { - //AES瀵嗘枃Base64杞垚瀛楃涓� - Byte [] toEncryptArray = Convert.FromBase64String (pToDecrypt); - - //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�) - RijndaelManaged rm = new RijndaelManaged { - Key = Encoding.UTF8.GetBytes (key), - IV = Encoding.UTF8.GetBytes (key), - Mode = CipherMode.CBC, - Padding = PaddingMode.PKCS7 - }; - - //鍒涘缓AES瑙e瘑鍣ㄥ璞� - ICryptoTransform cTransform = rm.CreateDecryptor (); - - //浣跨敤AES灏嗗瘑鏂囨祦杞垚鏄庢枃鐨勫瓧鑺傛暟缁� - Byte [] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length); - - //杞垚瀛楃涓� - return Encoding.UTF8.GetString (resultArray); - } - - /// <summary> - /// 閲囩敤Aes瑙e瘑璐熻浇鏁版嵁 - /// </summary> - /// <param name="toEncryptArray"></param> - /// <param name="key"></param> - /// <returns></returns> - public static byte [] AesDecryptPayload (byte [] toEncryptArray, string key) - { - //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�) - var rm = new RijndaelManaged { - Key = Encoding.UTF8.GetBytes (key), - IV = Encoding.UTF8.GetBytes (key), - Mode = CipherMode.CBC, - Padding = PaddingMode.PKCS7 - }; - - //鍒涘缓AES瑙e瘑鍣ㄥ璞� - var cTransform = rm.CreateDecryptor (); - - //浣跨敤AES灏嗗瘑鏂囨祦杞垚鏄庢枃鐨勫瓧鑺傛暟缁� - return cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length); - } - #endregion - } } -*/ -- Gitblit v1.8.0