From 4a61a132ce09b1fd42fd80fcbff1855bad4c0f48 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期三, 15 一月 2020 11:15:24 +0800
Subject: [PATCH] 2020-01-15 1.优化。
---
Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs | 745 ++++++++++++++++++++++++++++++++++-----------------------
1 files changed, 444 insertions(+), 301 deletions(-)
diff --git a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
index 97e1c46..7d6ebf0 100644
--- a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
+++ b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
@@ -20,6 +20,7 @@
static string mqttEncryptKey = "";
static string checkGatewayTopicBase64 = "";
static RemoteMACInfo CurRemoteMACInfo = null;
+ static MqttInfo mMqttInfo = null;
/// <summary>
/// 鎵嬫満鏍囪瘑
@@ -37,8 +38,8 @@
/// </summary>
public static IMqttClient RemoteMqttClient = new MqttFactory ().CreateMqttClient ();
- static bool thisShowTip = true;
- static string mqttRequestParToken="";
+ //static bool thisShowTip = true;
+ static string mqttRequestParToken = "";
/// <summary>
/// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
@@ -48,15 +49,25 @@
try {
if (remoteIsConnected) {
remoteIsConnected = false;
- System.Console.WriteLine ($"Remote涓诲姩鏂紑_{s}");
+ System.Console.WriteLine ($"============>MqttRemote涓诲姩鏂紑_{s}");
//await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
await RemoteMqttClient.DisconnectAsync ();
}
} catch (Exception e) {
- System.Console.WriteLine ($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+ System.Console.WriteLine ($"============>MqttRemote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
}
}
static DateTime dateTime = DateTime.MinValue;
+
+ /// <summary>
+ /// 鎺ㄩ�佹爣璇�
+ /// </summary>
+ static string PushSignStr = System.DateTime.Now.Ticks.ToString ();
+
+
+
+
+
/// <summary>
/// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
/// </summary>
@@ -68,297 +79,258 @@
public static async System.Threading.Tasks.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 (!MainPage.LoginUser.IsLogin) {
- return;
- }
- //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
- if (remoteMqttIsConnecting
- || remoteIsConnected) {
- return;
- }
+ //Application.RunOnMainThread (() => {
+ // if (5 < (DateTime.Now - dateTime).TotalSeconds) {
+ // return;
+ // }
+ // //MainPage.Loading.Start (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.Connecting));
+ // dateTime = DateTime.Now;
+ //});
+ if (!MainPage.LoginUser.IsLogin) {
+ return;
+ }
+ //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
+ if (remoteMqttIsConnecting
+ || remoteIsConnected) {
+ System.Console.WriteLine ($"============>MqttremoteMqttIsConnecting:{remoteMqttIsConnecting} remoteIsConnected:{remoteIsConnected} ");
- await System.Threading.Tasks.Task.Factory.StartNew (async () =>
- {
- try {
- lock (RemoteMqttClient) {
- //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
- remoteMqttIsConnecting = true;
+ return;
+ }
- #region 鍒濆鍖栬繙绋婱qtt
- //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
- if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) {
- RemoteMqttClient.UseApplicationMessageReceivedHandler ((e) => {
- try {
- if (!RemoteMqttClient.IsConnected || !CommonPage.IsRemote) {
+ await System.Threading.Tasks.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);
+
+ //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;
}
- var aesDecryptTopic = e.ApplicationMessage.Topic;
- var aesDecryptPayload = e.ApplicationMessage.Payload;
- //Console.WriteLine ("Topic={0}", aesDecryptTopic);
-
-
- //if (aesDecryptTopic == $"NotifyBusGateWayInfoChagne/{CurRemoteMACInfo.md5_mac_string}") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
- //2020-01-11 淇敼璁㈤槄涓婚鍦板潃
- if (aesDecryptTopic == $"BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
- Console.WriteLine ("缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey");
- //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
- 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) {
- CurRemoteMACInfo.aesKey = gatewayListRequestResult_Obj.pageData [0].aesKey;
- mqttEncryptKey = CurRemoteMACInfo.aesKey;
- }
- }
-
- 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);
- }
-
- }
- var packet = new Packet ();
- packet.Bytes = aesDecryptPayload;
- packet.Manager ();
- } catch { }
- });
- }
-
- if (RemoteMqttClient.DisconnectedHandler == null) {
- RemoteMqttClient.UseDisconnectedHandler (async (e) => {
- System.Console.WriteLine ($"杩滅▼杩炴帴鏂紑");
- await DisConnectRemoteMqttClient ("StartRemoteMqtt.DisconnectedHandler");
- //await StartRemoteMqtt();
- if (thisShowTip) {
- if (CommonPage.IsRemote) {
- Application.RunOnMainThread (() => {
- MainPage.Loading.Hide ();
- //Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
- });
- }
- } else {
- thisShowTip = true;
- }
- });
- }
- if (RemoteMqttClient.ConnectedHandler == null) {
- RemoteMqttClient.UseConnectedHandler (async (e) => {
- //Shared.Application.RunOnMainThread (() => {
- // Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = 0xAA69E64A;
- //});
- Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
- System.Console.WriteLine ($"杩滅▼杩炴帴鎴愬姛");
- if (CommonPage.IsRemote) {
- Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
- }
-
- //MainPage.WiFiStatus = "CrabtreeAdd/CloudLink.png";
- //UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
- if (CurRemoteMACInfo != null) {
- if (CurRemoteMACInfo.isValid == "InValid") {
- MainPage.AddTip ("Remote failed,gateway offline");
- Application.RunOnMainThread (() => {
- MainPage.Loading.Hide ();
- //Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
- });
- } else {
- MqttRemoteSend (new byte [] { 0 }, 3);
+ switch (obj.StateCode) {
+ case "HDLUdpDataForwardServerMqttClientNoOnLine":
+ case "NoOnline":
+ case "NetworkAnomaly"://涓嶅湪绾�
+ MainPage.AddTip ("Gateway offline");
//Application.RunOnMainThread (() => {
- // MainPage.Loading.Hide ();
- // Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = 0xAA69E64A;
- // Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
+ // Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
//});
- //MainPage.AddTip (UserConfig.Instance.CurrentRegion.RegionName + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+ 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;
}
- }
-
- });
- }
- #endregion
- }
-
- try {
- try {
- //鏂紑鍚庨噸鏂伴摼鎺ラ渶瑕侀噸鏂扮櫥褰曡幏鍙栬繛鎺ョ殑瀵嗙爜
- var requestObj = new LoginObj () { Account = MainPage.LoginUser.AccountString.ToLower (), Password = MainPage.LoginUser.Password };
- var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj);
- var tempResult = MainPage.RequestHttps (API.Login, requestJson);
- if (tempResult == null) {
- Application.RunOnMainThread (() => {
- MainPage.Loading.Hide ();
- //Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
- });
- return;
- }
- var responsePack = tempResult.ResponseData;
- var dictrionaryResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (tempResult.ResponseData.ToString ());
- var mqttRequestPar = Newtonsoft.Json.JsonConvert.DeserializeObject<UserLoginRes> (tempResult.ResponseData.ToString ());
- mqttRequestParToken = mqttRequestPar.Token;
- //杩樻湁绉嶆儏鍐垫槸鍚屼竴涓狪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;
- }
-
- 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 requestObj3 = new GatewayByRegionListObj () { RegionID = UserConfig.Instance.CurrentRegion.Id };
- 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 ());
- //2020-01-11
- UserConfig.Instance.SetNowHomeGateways (infoResult.PageData);
- } else {
- //鎻愮ず閿欒
- //GetSingleHomeGatewayPagger
- }
-
- if (tempResult == null) {
- Application.RunOnMainThread (() => {
- MainPage.Loading.Hide ();
- //Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
- });
- return;
- }
- try {
- //--绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟
- var mqttInfoUrl = $"{MainPage.RequestHttpsHostMqtt}/Center/Center/GetConnMqttInfo";//鑾峰彇杩炴帴杩滅▼浜戠Emq Mqtt 鏈嶅姟鍣ㄨ繛鎺ヤ俊鎭�
- var mqttInfoRequestPar = new RemoteRequestParameters () { LoginAccessToken = mqttRequestParToken, RequestVersion = MainPage.RequestVersion, RequestProtocolType = 0, RequestSource = 1 };
- var mqttInfoRequestResult = MainPage.RequestHttps ("", Newtonsoft.Json.JsonConvert.SerializeObject (mqttInfoRequestPar), mqttInfoUrl);
- if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) {
- var mqttInfoRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ());
- if (mqttInfoRequestResult_Obj != null) {
- url = mqttInfoRequestResult_Obj.connEmqDomainPort;
- clientId = mqttInfoRequestResult_Obj.connEmqClientId;
- username = mqttInfoRequestResult_Obj.connEmqUserName;
- passwordRemote = mqttInfoRequestResult_Obj.connEmqPwd;
- //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
- 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.CheckHomeGateways ()) {
- CurRemoteMACInfo = gatewayListRequestResult_Obj.pageData.Find ((obj) => obj.mac == UserConfig.Instance.CurrentRegion.HomeGateways[0].GatewayUniqueId);
- CurRemoteMACInfo = gatewayListRequestResult_Obj.pageData [0];
- if (CurRemoteMACInfo != null) {
- CurRemoteMACInfo.LoginAccessToken = mqttRequestPar.Token;
- 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 ();
-
- await DisConnectRemoteMqttClient ("StartRemoteMqtt");
- await RemoteMqttClient.ConnectAsync (options1);
- remoteIsConnected = true;
- await MqttRemoteSend (new byte [] { 0 }, 1);
- await MqttRemoteSend (new byte [] { 0 }, 2);
- }
- }
-
+ Application.RunOnMainThread (() => {
+ UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
+ });
+ } else {
+ if (!string.IsNullOrEmpty (mqttEncryptKey)) {
+ aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey);
}
}
- } catch (Exception ex) {
- Console.WriteLine (ex.Message);
- }
- } 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 (remoteMqttIsConnecting.ToString (), ex.Message, "Close");
- a.Show ();
-#endif
- });
- } finally {
- Application.RunOnMainThread (() => {
- MainPage.Loading.Hide ();
- });
- }
- } catch { } finally {
- //鏈�缁堣閲婃斁杩炴帴鐘舵��
- remoteMqttIsConnecting = false;
+ var packet = new Packet ();
+ packet.IsLocal = false;
+ packet.Bytes = aesDecryptPayload;
+ packet.Manager ();
+ } catch { }
+ });
}
- } catch (Exception ex) {
- System.Console.WriteLine ($"杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
+
+ if (RemoteMqttClient.DisconnectedHandler == null) {
+ RemoteMqttClient.UseDisconnectedHandler (async (e) => {
+ System.Console.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑");
+ 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 ();
+ //});
+ } else {
+ MqttRemoteSend (new byte [] { 0 }, 3);
+ }
+ }
+
+ });
+ }
+ #endregion
}
- });
+ try {
+
+ 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 ();
+
+ }
+
+ }
+ }
+
+
+
+ } catch (Exception ex) {
+ Console.WriteLine (ex.Message);
+ }
+ } catch (Exception ex) {
+ System.Console.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
+ } finally {
+ //鏈�缁堣閲婃斁杩炴帴鐘舵��
+ remoteMqttIsConnecting = false;
+ }
+ });
}
+
+ /// <summary>
+ /// 杩炴帴MQTT
+ /// </summary>
+ 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;
+
+ 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 ();
+
+ 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);
+
+ }
+ }
+
+ //public static async System.Threading.Tasks.Task InitMqtt () {
+
+ // while (true) {
+ // await StartCloudMqtt ();
+ // System.Threading.Thread.Sleep (100);
+ // }
+ //}
+
/// <summary>
///
/// </summary>
/// <param name="message">闄勫姞鏁版嵁鍖�</param>
- /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁</param>
+ /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁;3=璁㈤槄缃戝叧鏄惁鍦ㄧ嚎涓婚 4=璁㈤槄鎸や笅绾夸富棰� </param>
/// <returns></returns>
public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
{
@@ -376,30 +348,30 @@
//base64鍔犲瘑
var m = new MqttApplicationMessage { Topic = topicName, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
//if (remoteIsConnected) {
- try {
- await RemoteMqttClient.PublishAsync (m);
- } catch (Exception e) {
- await DisConnectRemoteMqttClient (e.Message);
- await StartCloudMqtt ();
- if (remoteIsConnected) {
- await RemoteMqttClient.PublishAsync (m);
- }
+ try {
+ RemoteMqttClient.PublishAsync (m);
+ } catch (Exception e) {
+ await DisConnectRemoteMqttClient (e.Message);
+ await StartCloudMqtt ();
+ if (remoteIsConnected) {
+ RemoteMqttClient.PublishAsync (m);
}
+ }
//}
break;
case 1:
topicName = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/#";
//if (remoteIsConnected) {
- try {
+ try {
+ await RemoteMqttClient.SubscribeAsync (topicName);
+ } catch (Exception e) {
+ await DisConnectRemoteMqttClient (e.Message);
+ await StartCloudMqtt ();
+ if (remoteIsConnected) {
await RemoteMqttClient.SubscribeAsync (topicName);
- } catch (Exception e) {
- await DisConnectRemoteMqttClient (e.Message);
- await StartCloudMqtt ();
- if (remoteIsConnected) {
- await RemoteMqttClient.SubscribeAsync (topicName);
- }
}
- // }
+ }
+ // }
break;
case 2:
var macStr = CurRemoteMACInfo.mac.ToUpper ();
@@ -418,23 +390,23 @@
//topicName = $"/NotifyBusGateWayInfoChagne/{CurRemoteMACInfo.md5_mac_string}";
//2020-01-11 淇敼璁㈤槄涓婚鍦板潃
- topicName = $"BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange";
+ topicName = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange";
//if (remoteIsConnected) {
try {
+ await RemoteMqttClient.SubscribeAsync (topicName);
+ } catch (Exception e) {
+ await DisConnectRemoteMqttClient (e.Message);
+ await StartCloudMqtt ();
+ if (remoteIsConnected) {
await RemoteMqttClient.SubscribeAsync (topicName);
- } catch (Exception e) {
- await DisConnectRemoteMqttClient (e.Message);
- await StartCloudMqtt ();
- if (remoteIsConnected) {
- await RemoteMqttClient.SubscribeAsync (topicName);
- }
}
+ }
//}
break;
case 3:
topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
-
+
var m1 = new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
try {
@@ -446,12 +418,181 @@
await StartCloudMqtt ();
}
break;
+
+ case 4:
+ //2020-01-13 淇敼鎸や笅绾夸富棰�
+ topicName = $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze";
+ //if (remoteIsConnected) {
+ try {
+ await RemoteMqttClient.SubscribeAsync (topicName);
+ } catch (Exception e) {
+ await DisConnectRemoteMqttClient (e.Message);
+ await StartCloudMqtt ();
+ if (remoteIsConnected) {
+ await RemoteMqttClient.SubscribeAsync (topicName);
+ }
+ }
+
+ //}
+ break;
}
+
+
} catch (Exception e) {
}
}
+
+
+ /// <summary>
+ /// 鍒嗕韩浣忓畢 鑾峰彇褰撳墠浣忓畢缃戝叧淇℃伅骞朵笖杩炴帴MQTT 鎴栬�呭埛鏂�
+ /// 2020-01-11
+ /// </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
@@ -461,8 +602,10 @@
public string LoginAccessToken;
public int RequestProtocolType;
+
public string Mac = "";
public string GroupName = "";
+
}
public class MqttRemoteInfo
--
Gitblit v1.8.0