From 3272ca5b51e19f7f8a827b0f68400570a547fe60 Mon Sep 17 00:00:00 2001 From: 陈嘉乐 <cjl@hdlchina.com.cn> Date: 星期二, 28 四月 2020 15:02:44 +0800 Subject: [PATCH] 2020-04-28-1 --- ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs | 610 ++++++++++++++++++++++++++++++++---------------------- 1 files changed, 361 insertions(+), 249 deletions(-) diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs index 48fbf24..a105443 100755 --- a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs +++ b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs @@ -60,6 +60,12 @@ /// <value><c>true</c> if is remote; otherwise, <c>false</c>.</value> public static bool IsRemote; + /// <summary> + /// 鏄惁鎷ユ湁杩滅▼杩炴帴鐨勬潈闄� + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public static bool AllowRemoteCtrl = true; + /// <summary> /// 缃戝叧淇濆瓨璺緞 /// </summary> @@ -137,12 +143,6 @@ public List<CommonDevice> DeviceList = new List<CommonDevice>(); /// <summary> - /// 鎵�鏈夌綉鍏充腑鐨勮澶囧垪琛� - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public List<CommonDevice> AllGatewayDeviceList = new List<CommonDevice>(); - - /// <summary> /// 缃戝叧涓満鏅垪琛� /// 涓�涓満鏅腑鍖呭惈鎵�鏈変俊鎭紝鍖呮嫭鍦烘櫙璁惧淇℃伅 /// </summary> @@ -154,34 +154,6 @@ /// </summary> [Newtonsoft.Json.JsonIgnore] public List<Scene.GetSceneDeviceListInfo> SceneDeviceList = new List<Scene.GetSceneDeviceListInfo>(); - - /// <summary> - /// 缃戝叧涓�昏緫鍒楄〃 - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public static List<Logic.GetLogicInfoResponseData> LogicList = new List<Logic.GetLogicInfoResponseData>(); - - /// <summary> - /// 缃戝叧涓環dl绉佹湁鎸夐敭缁戝畾鍒楄〃 - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public List<HDLbutton> HdlButtonList = new List<HDLbutton>(); - - //缃戝叧涓柊鐨勮澶囧垪琛� - [Newtonsoft.Json.JsonIgnore] - public List<CommonDevice> ListNewDeviceInfoData = new List<CommonDevice>(); - - /// <summary> - /// 绉佹湁鎸夐敭淇℃伅鍒楄〃 - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public System.Collections.Generic.Dictionary<string, HDLbutton> hdlButtonInfoList = new Dictionary<string, HDLbutton>(); - - /// <summary> - /// 浼犳劅鍣ㄤ俊鎭垪琛� - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public System.Collections.Generic.Dictionary<string, Scene.TaskListInfo> sceneTaskInfoList = new Dictionary<string, Scene.TaskListInfo>(); #region action variable /// <summary> @@ -603,7 +575,8 @@ var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } }; var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } }; jObject.Add("Data", data); - Send("GwSetHomeId", jObject.ToString()); + //浣忓畢ID鐨勮缃�,鍥哄畾浣跨敤灞�鍩熺綉,涓嶅瓨鍦ㄨ繙绋嬬殑璇存硶 + SendLocation("GwSetHomeId", System.Text.Encoding.UTF8.GetBytes(jObject.ToString())); } catch { } @@ -3047,22 +3020,6 @@ public static readonly System.Collections.Generic.List<IStatus> StatusList = new System.Collections.Generic.List<IStatus>(); /// <summary> - /// 璁惧鐘舵�佹洿鏂� - /// </summary> - /// <param name="commonDevice">Common device.</param> - public static void UpdateDeviceStatus(CommonDevice commonDevice) - { - if (commonDevice == null) - { - return; - } - for (int i = 0; i < StatusList.Count; i++) - { - StatusList[i].Changed(commonDevice); - } - } - - /// <summary> /// 璁惧淇℃伅鍙樺寲 /// <para>type锛氬鏋滀负 DeviceInComingRespon:璁惧鏂颁笂鎶�</para> /// <para>type锛氬鏋滀负 IASInfoReport:RemoveDeviceRespon</para> @@ -3090,27 +3047,46 @@ /// </summary> IMqttClient localMqttClient = new MqttFactory().CreateMqttClient(); bool localMqttIsConnecting; + public bool localIsConnected; /// <summary> /// 鎵嬫満鏍囪瘑 /// </summary> static Guid currentGuid = Guid.NewGuid(); + public async System.Threading.Tasks.Task SendAesKey() + { + if (PubKey != null) + { + IsEncry = false; + var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password); + var resultVerityfy = await SendAesKeyAsync(rsaString); + if (resultVerityfy == null) + { + resultVerityfy = await SendAesKeyAsync(rsaString); + } + + if (resultVerityfy != null && resultVerityfy.Result == 0) + { + IsEncry = true; + } + } + } + public async System.Threading.Tasks.Task StartLocalMqtt(string brokerName) - { + { + if (localMqttIsConnecting + || !Shared.Common.Config.Instance.IsLogin + || Shared.Common.Config.Instance.HomeId == "" + || localIsConnected) + { + return; + } await System.Threading.Tasks.Task.Factory.StartNew(async () => { try { lock (localMqttClient) { - if (localMqttIsConnecting - || !Shared.Common.Config.Instance.IsLogin - || Shared.Common.Config.Instance.HomeId == "" - || localMqttClient.IsConnected) - { - return; - } - //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� localMqttIsConnecting = true; @@ -3129,10 +3105,11 @@ if (localMqttClient.DisconnectedHandler == null) { - localMqttClient.UseDisconnectedHandler((e) => - { - IsEncry = false; + localMqttClient.UseDisconnectedHandler(async (e) => + { DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}"); + await DisConnectLocalMqttClient("StartLocalMqtt.DisconnectedHandler"); + //await StartLocalMqtt("ReConnect"); }); } if (localMqttClient.ConnectedHandler == null) @@ -3141,33 +3118,44 @@ { DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}"); IsRemote = false; - if (PubKey != null) - { - var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password); - var resultVerityfy = await SendAesKeyAsync(rsaString); - if (resultVerityfy == null) - { - resultVerityfy = await SendAesKeyAsync(rsaString); - } - if (resultVerityfy != null && resultVerityfy.Result == 0) - { - IsEncry = true; - } - } Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI); - System.Console.WriteLine($"褰撳墠鏄綉鍏砏i-Fi鍦ㄩ�氳_{System.DateTime.Now.ToString()}"); }); - } - } - - var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder() - .WithClientId(currentGuid.ToString()) - .WithTcpServer(brokerName, 1883) - .WithKeepAlivePeriod(TimeSpan.FromSeconds(20)) - .WithCleanSession() - .WithCredentials("", "") - .Build(); - await localMqttClient.ConnectAsync(options, CancellationToken.None); + } + + var dateTime = DateTime.Now; + + new System.Threading.Thread(async () => + { + try + { + if (localMqttClient.Options == null) + { + var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT杩炴帴鍙傛暟濉厖 + .WithClientId(currentGuid.ToString())//瀹㈡埛绔疘D + .WithTcpServer(brokerName, 1883)//TCP鏈嶅姟绔� 1883 锛屽嵆MQTT鏈嶅姟绔� + .WithCredentials("", "")//"", "")//鍑瘉 甯愬彿 瀵嗙爜 + .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //閲嶈繛瓒呮椂鏃堕棿锛岄粯璁�5s + .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //淇濇寔杩炴帴鏃堕棿锛岄粯璁�5s锛屽績璺冲寘 + .Build();// + await localMqttClient.ConnectAsync(options); + } + else + { + await DisConnectLocalMqttClient("StartLocalMqtt"); + await localMqttClient.ReconnectAsync(); + } + localIsConnected = true; + await SendAesKey(); + } + catch { } + dateTime = DateTime.MinValue; + }) + { IsBackground = true }.Start(); + while (dateTime != DateTime.MinValue) + { + System.Threading.Thread.Sleep(100); + } + } } catch (Exception ex) { @@ -3197,6 +3185,11 @@ /// <returns></returns> static async System.Threading.Tasks.Task initGateWayBaseInfomation() { + if (AllowRemoteCtrl == false) + { + //娌℃湁杩滅▼杩炴帴鐨勬潈闄� + return; + } string loginToken = Config.Instance.Token; if (Config.Instance.Home.IsOthreShare == true) { @@ -3239,11 +3232,13 @@ var statuCode = jobject["StateCode"].ToString(); if (statuCode != "Success") { - //Log鍑哄姏 - Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, "鎺ュ彛璁块棶澶辫触鈽咃細App/GetSingleHomeGatewayPagger " + statuCode); //搴忓垪鍖栧璞� var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pra2); - Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, "鍙傛暟锛歕r\n" + requestJson); + //Log鍑哄姏 + string errorMsg = "鎺ュ彛璁块棶澶辫触鈽咃細App/GetSingleHomeGatewayPagger " + statuCode + "\r\n"; + errorMsg += "鍙傛暟锛歕r\n" + requestJson; + Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, errorMsg); + return; } var responseData = jobject["ResponseData"]; @@ -3279,6 +3274,7 @@ /// 杩滅▼MqttClient /// </summary> public static IMqttClient RemoteMqttClient= new MqttFactory().CreateMqttClient(); + static bool remoteIsConnected; private int IsLogin = 0; [Newtonsoft.Json.JsonIgnore] static Action actionTemp; @@ -3288,22 +3284,23 @@ /// </summary> /// <returns>The start.</returns> /// <param name="brokerName">Broker name.</param> - public static async System.Threading.Tasks.Task StartCloudMqtt() - { + public static async System.Threading.Tasks.Task StartRemoteMqtt() + { + //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺 + if (AllowRemoteCtrl == false + || remoteMqttIsConnecting + || !Shared.Common.Config.Instance.IsLogin + || Shared.Common.Config.Instance.HomeId == "" + || remoteIsConnected) + { + return; + } await System.Threading.Tasks.Task.Factory.StartNew(async () => { try { lock (RemoteMqttClient) { - if (remoteMqttIsConnecting - || !Shared.Common.Config.Instance.IsLogin - || Shared.Common.Config.Instance.HomeId == "" - || RemoteMqttClient.IsConnected) - { - return; - } - //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� remoteMqttIsConnecting = true; @@ -3312,10 +3309,20 @@ if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) { RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => - { - if (!RemoteMqttClient.IsConnected || !IsRemote) - { - return; + { + //杩欓噷鏄壒娈婄殑涓婚 + if (e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze"//韪汉涓嬬嚎 + || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Deleted"//鍒嗕韩鍒犻櫎 + || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/DeletedShareData"//鍒嗕韩鍒犻櫎 + || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Update"//鎴愬憳鏉冮檺鍙樻洿 + || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + Config.Instance.Guid + "/PrimaryUserDelYou")//瀛愯处鍙疯鍒犻櫎 + { + mqttRemoteClient_MqttMsgPublishReceived(e); + return; + } + if (!RemoteMqttClient.IsConnected || !IsRemote) + { + return; } mqttRemoteClient_MqttMsgPublishReceived(e); }); @@ -3323,9 +3330,11 @@ if (RemoteMqttClient.DisconnectedHandler == null) { - RemoteMqttClient.UseDisconnectedHandler((e) => + RemoteMqttClient.UseDisconnectedHandler(async (e) => { DebugPrintLog($"杩滅▼杩炴帴鏂紑"); + await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler"); + //await StartRemoteMqtt(); }); } if (RemoteMqttClient.ConnectedHandler == null) @@ -3333,6 +3342,22 @@ RemoteMqttClient.UseConnectedHandler(async (e) => { DebugPrintLog($"杩滅▼杩炴帴鎴愬姛"); + + if (Config.Instance.Home.IsOthreShare == true) + { + //璁㈤槄涓�涓垚鍛樿鍒犻櫎鐨勪富棰� + string myGuid = Config.Instance.Guid; + await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Deleted"); + //璁㈤槄涓�涓垎浜暟鎹凡缁忓彉鏇寸殑涓婚 + await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/DeletedShareData"); + //璁㈤槄涓�涓瓙璐﹀彿琚垹闄ょ殑涓婚 + await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + myGuid + "/PrimaryUserDelYou"); + //璁㈤槄涓�涓垚鍛樻潈闄愬凡缁忓彉鏇寸殑涓婚 + await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Update"); + } + //璁㈤槄涓�涓尋涓嬬嚎鐨勪富棰� + await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze"); + await initGateWayBaseInfomation(); Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote); //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅 @@ -3378,24 +3403,51 @@ try { - var jsonData = new Dictionary<string, object> { ["RequestVersion"] = "RequestVersion", ["RequestSource"] = 0, ["LoginAccessToken"] = Config.Instance.Token, ["RequestProtocolType"] = 0 }; - var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData)); - - var result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token); - //{ - //"ResponseVersion": "RequestVersion1", - //"StateCode": "Success", - //"ErrorInfo": null, - //"ResponseData": { < !--濡備笅淇℃伅鍙兘浣跨敤涓�娆★紝鍗充究浣犺繛鎺ュけ璐�!-- > - // "ConnEmqDomainPort": "tcp://developer.hdlcontrol.com:1883", - // "ConnEmqClientId": "ZigbeeClientTcp_33094de8-34ba-4e38-93c2-ac8da16d0e68_Zigbee", - // "ConnEmqUserName": "33094de8-34ba-4e38-93c2-ac8da16d0e68", - // "ConnEmqPwd": "4a265b65-d6cc-4a" - //} - //} + byte[] result = null; + if (Config.Instance.Home.IsOthreShare == false) + { + //涓讳汉 + var jsonData = new Dictionary<string, object> + { + ["RequestVersion"] = CommonPage.RequestVersion, + ["RequestSource"] = 0, + ["LoginAccessToken"] = Config.Instance.Token, + ["RequestProtocolType"] = 0, + ["PlatformStr"] = "h",//杩欎袱涓�煎鏋滀笉璁剧疆,鍒欎簯绔笉鍙戝竷涓婚 + ["PublishPayloadJsonStr"] = "1" + }; + var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData)); + result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token); + } + else + { + //鍒嗕韩鐨� + var jsonData = new Dictionary<string, object> + { + ["RequestVersion"] = CommonPage.RequestVersion, + ["RequestSource"] = 0, + ["LoginAccessToken"] = Config.Instance.Token, + ["RequestProtocolType"] = 0, + ["MainUserDistributedMark"] = Config.Instance.Home.MainUserDistributedMark, + ["HomeId"] = Config.Instance.Home.Id, + ["PlatformStr"] = "h",//杩欎袱涓�煎鏋滀笉璁剧疆,鍒欎簯绔笉鍙戝竷涓婚 + ["PublishPayloadJsonStr"] = "1" + }; + var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData)); + result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/ShareMemberConnMqttInfo", bytes, Config.Instance.Token); + } if (result != null) { var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result)); + if (jobject["StateCode"].ToString() == "NotAllowRemoteCtrl") + { + //娌℃湁杩滅▼杩炴帴鐨勬潈闄� + AllowRemoteCtrl = false; + return; + } + //铏界劧涓嶇煡閬撳鎸や笅绾块偅涓�鍧楁湁娌℃湁鐢�,涓嶈繃鍏堣繖涔堝紕 + await System.Threading.Tasks.Task.Delay(1500); + var responseData = jobject["ResponseData"]; if (responseData != null) { @@ -3403,21 +3455,25 @@ var connEmqClientId = responseData["ConnEmqClientId"]?.ToString(); var connEmqUserName = responseData["ConnEmqUserName"]?.ToString(); var connEmqPwd = responseData["ConnEmqPwd"]?.ToString(); + //璁板綍璧峰綋鍓嶇殑瀹㈡埛绔疘D + Config.Instance.ConnEmqClientId = connEmqClientId; var connEmqDomainPorts = connEmqDomainPort.Replace("//", "").Split(':'); var domain = connEmqDomainPorts[1]; - var port = connEmqDomainPorts[2]; - - - var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder() - .WithClientId(connEmqClientId) - .WithTcpServer(domain, int.Parse(port)) - .WithCredentials(connEmqUserName, connEmqPwd) - .WithKeepAlivePeriod(TimeSpan.FromSeconds(20)) - .WithCleanSession() - .Build(); - await RemoteMqttClient.ConnectAsync(options); - + var port = connEmqDomainPorts[2]; + + var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder() + .WithClientId(connEmqClientId) + .WithTcpServer(domain, int.Parse(port)) + .WithCredentials(connEmqUserName, connEmqPwd) + .WithKeepAlivePeriod(TimeSpan.FromSeconds(20)) + .WithCleanSession() + //.WithCommunicationTimeout(TimeSpan.FromSeconds(10)) + .Build(); + await DisConnectRemoteMqttClient("StartRemoteMqtt"); + await RemoteMqttClient.ConnectAsync(options, CancellationToken.None); + + remoteIsConnected = true; } } } @@ -3438,28 +3494,42 @@ /// <summary> /// 鏂紑鏈嶅姟鍣ㄨ繛鎺� /// </summary> - public async System.Threading.Tasks.Task DisConnect(string s) + public async System.Threading.Tasks.Task DisConnectLocalMqttClient(string s) { try { - DebugPrintLog($"涓诲姩鏂紑_{s}"); - if (localMqttClient.IsConnected == true) + if (localIsConnected) { - await localMqttClient.DisconnectAsync(); - } + localIsConnected = false; + DebugPrintLog($"Local涓诲姩鏂紑_{s}"); + //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await localMqttClient.DisconnectAsync(); + } } catch (Exception ex) { - DebugPrintLog($"鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); + DebugPrintLog($"Local鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); } } /// <summary> /// 鏂紑杩滅▼Mqtt鐨勯摼鎺� /// </summary> - public static void DisRemoteMqttClientConnect() + public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s="") { - RemoteMqttClient.DisconnectAsync(); + try + { + if (remoteIsConnected) + { + remoteIsConnected = false; + DebugPrintLog($"Remote涓诲姩鏂紑_{s}"); + //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await RemoteMqttClient.DisconnectAsync(); + } + } + catch(Exception e) { + DebugPrintLog($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); + } } #endregion @@ -3492,35 +3562,35 @@ /// </summary> async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false) { - if (this.getGatewayBaseInfo?.gwID == null || !GateWayBaseInfomations.ContainsKey(this.getGatewayBaseInfo?.gwID)) - { - return; - } - var gateWayBaseInfomation = GateWayBaseInfomations[this.getGatewayBaseInfo?.gwID]; - ////(1)鐢熸垚[鐢ㄦ埛鍚�:瀵嗙爜] - //var userNameAndPwdStr = string.Concat(Shared.Common.Config.Instance.Guid, RemoteOperatorConsts.CAP_NUMBER, Shared.Common.Config.Instance.MD5PWD); - //DebugPrintLog($"userNameAndPwdStr锛歿userNameAndPwdStr} "); - - ////(2)灏�(1)杞垚Base64瀛楃涓�,鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜)] - //var userNameAndPwdStrBaseSexFour = Convert.ToBase64String(ZigBee.Common.CommonInfo.EncodingUTF8.GetBytes(userNameAndPwdStr)); - - ////(3)灏�(2)缁х画鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp] - //var userNameAndPwdStrBaseSexFourAndTimestamp = string.Concat(userNameAndPwdStrBaseSexFour, RemoteOperatorConsts.CAP_NUMBER, CurrentTimeStamp.ToString()); - - ////[Zigbee.Buspro]App/id(甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/杞彂缁欑綉鍏崇殑涓婚/XX/XX - ////(4)鐢熸垚涓婃姤涓婚锛屼富棰樻ā寮忛渶瑕佷负 /ZigbeeApp/id(涓诲瓙璋冭瘯甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/topicName "000204022022" GateWayId 000204022022 - //var reportTopic = string.Format("/{0}/{1}/{2}/{3}/{4}", RemoteOperatorConsts.ZIGBEE_APP_STARTS_WITH, Shared.Common.Config.Instance.Guid, userNameAndPwdStrBaseSexFourAndTimestamp, this.getGatewayBaseInfo?.gwID, topicName); - - ////鏂囦欢娴佷笉鐢ㄥ姞瀵� - //var topicEncStr = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(reportTopic), gateWayBaseInfomation.AesKey); - //topicEncStr = topicEncStr.Replace("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]").Replace("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]"); - //message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, gateWayBaseInfomation.AesKey)); - message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey); - var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.MacMark}/Common/{topicName}"; - //(6)鏋勫缓Mqtt闇�瑕佸彂甯冪殑鏁版嵁鍖�,鍙戝竷缁欎簯绔殑MqttBroker - if (RemoteMqttClient.IsConnected) - { - await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }); + try + { + if (this.getGatewayBaseInfo?.gwID == null || !GateWayBaseInfomations.ContainsKey(this.getGatewayBaseInfo?.gwID)) + { + return; + } + var gateWayBaseInfomation = GateWayBaseInfomations[this.getGatewayBaseInfo?.gwID]; + message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey); + var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.MacMark}/Common/{topicName}"; + //(6)鏋勫缓Mqtt闇�瑕佸彂甯冪殑鏁版嵁鍖�,鍙戝竷缁欎簯绔殑MqttBroker + if (remoteIsConnected) + { + try + { + await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }); + } + catch (Exception e) + { + await DisConnectRemoteMqttClient(e.Message); + await StartRemoteMqtt(); + if (remoteIsConnected) + { + await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }); + } + } + } + } + catch + { } } @@ -3547,25 +3617,34 @@ } else { - DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}"); - if (!localMqttClient.IsConnected) - { - await StartLocalMqtt(getGatewayBaseInfo.IpAddress); - } - + DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + if (IsEncry) { //鏂囦欢娴佷笉鐢ㄥ姞瀵� if (topic != "FileTransfer/SendFile") { - topic = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(topic), Password); - topic = topic.Replace("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]").Replace("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]"); - message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, password)); - DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰橈紙绉樻枃锛�:{topic}_褰撳墠绉橀挜{Password}_鍙戦�佸埌缃戝叧鐨勬暟鎹紙绉樻枃锛�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{System.DateTime.Now.ToString()}"); + message = SecuritySet.AesEncryptBytes(message, password); } - } - - await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + if (localIsConnected) + { + try + { + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + catch(Exception e) + { + DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}"); + await DisConnectLocalMqttClient(e.Message); + await StartLocalMqtt("ReConnect"); + if (localIsConnected) + { + DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + } + } } } catch (Exception ex) @@ -3588,8 +3667,58 @@ return; } await Send(topic, System.Text.Encoding.UTF8.GetBytes(message), retain); + } + + /// <summary> + /// 寮哄埗鎸囧畾浣跨敤鏈湴灞�鍩熺綉鍙戦�佹秷鎭埌鏈嶅姟鍣� + /// </summary> + /// <returns></returns> + /// <param name="topic"></param> + /// <param name="message"></param> + /// <param name="retain"></param> + public async Task SendLocation(string topic, byte[] message, bool retain = false) + { + try + { + if (Shared.Common.Config.Instance.HomeId == "") + { + return; + } + + DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + + if (IsEncry) + { + //鏂囦欢娴佷笉鐢ㄥ姞瀵� + if (topic != "FileTransfer/SendFile") + { + message = SecuritySet.AesEncryptBytes(message, password); + } + } + if (localIsConnected) + { + try + { + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + catch (Exception e) + { + DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}"); + await DisConnectLocalMqttClient(e.Message); + await StartLocalMqtt("ReConnect"); + if (localIsConnected) + { + DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + } + } + } + catch (Exception ex) + { + DebugPrintLog($"Send:{ex.Message}"); + } } - [Serializable] public class CloudTimeResponse @@ -3608,8 +3737,7 @@ { try { - var topic = e.ApplicationMessage.Topic.TrimStart('/'); - topic = topic.Replace("[[$-MQTT_TILT_SYMBOL_REPLACE-$]]", "/").Replace("[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]", "+"); + var topic = e.ApplicationMessage.Topic.TrimStart('/'); var payload = e.ApplicationMessage.Payload; var message = string.Empty; @@ -3624,7 +3752,7 @@ { return; } - if (topics[2]== "NotifyGateWayInfoChagne") { + if (topics[2]== "NotifyGateWayInfoChange") { initGateWayBaseInfomation(); return; } @@ -3671,39 +3799,36 @@ { try { - var topic = e.ApplicationMessage.Topic; - topic = topic.Replace("[[$-MQTT_TILT_SYMBOL_REPLACE-$]]", "/").Replace("[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]", "+"); - var message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); + var topic = e.ApplicationMessage.Topic; + string payloadString = ""; if (IsEncry) { //涓婚 - topic = Common.SecuritySet.AesDecrypt(System.Text.Encoding.UTF8.GetBytes(topic), Password); //涓嬭浇鐨勫瓧鑺傛祦涓嶉渶瑕佽В瀵� if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer") { if (topic.Split('/')[2] != "DownloadFile") { - message = Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Password); + payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password)); } } else if (topic == topic.Split('/')[0] + "/" + "SendAESKey_Respon") { }//鍥炲涓婚鏄鏂囷紝鏁版嵁鏄槑鏂� else { - message = Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Password); + payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password)); } } - -#if DEBUG - DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{message}_{System.DateTime.Now.ToString()}"); -#endif - ReceiveMessage(topic, message, e.ApplicationMessage.Payload); + else + { + payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); + } + DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{payloadString}"); + ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload); } catch (Exception ex) { -#if DEBUG DebugPrintLog($"鎺ユ敹缃戝叧鏁版嵁寮傚父:{ex.Message}"); -#endif } } @@ -3734,7 +3859,10 @@ epoint = topic.Split('/')[3]; cluID = topic.Split('/')[4]; attrId = topic.Split('/')[5]; - } + } + + //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) + Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message); var gwa = GateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == gatewayID); if (gwa == null) @@ -3766,9 +3894,6 @@ { jobject = Newtonsoft.Json.Linq.JObject.Parse(message); } - - //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) - Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, jobject); #region 杩滅▼,涓荤綉鍏充笂鎶ラ�氱煡 if (IsRemote) @@ -3841,8 +3966,7 @@ DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); gwa.ReportAction("DeviceInComingRespon", tempDevice.getNewDeviceInfo); } - UpdateDeviceInfo(tempDevice, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); + UpdateDeviceInfo(tempDevice, "DeviceInComingRespon"); } #endregion #region 璁惧鍦ㄧ嚎鐘舵�佹洿鏂板弽棣� @@ -3860,7 +3984,6 @@ if (infoTempDevice == null) { gwa.DeviceList.Add(tempDevice); - UpdateDeviceStatus(tempDevice); UpdateDeviceInfo(tempDevice, "OnlineStatusChange"); } else @@ -3870,7 +3993,6 @@ infoTempDevice.DeviceInfo.IsOnline = infoTempDevice.IsOnline; } UpdateDeviceInfo(infoTempDevice, "OnlineStatusChange"); - UpdateDeviceStatus(infoTempDevice); } } #endregion @@ -3896,7 +4018,6 @@ } else { - UpdateDeviceStatus(tempDevice); UpdateDeviceInfo(tempDevice, "RemoveDeviceRespon"); if (tempDevice.removeDeviceResponseData.Result == 0) { @@ -3924,7 +4045,6 @@ var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(tempDevice); UpdateDeviceInfo(tempDevice, "DeviceStatusReport"); } #endregion @@ -3946,7 +4066,6 @@ DebugPrintLog("DoorLockProgrammingEventNotificationCommand宸茬粡閫氱煡"); gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock); } - UpdateDeviceStatus(doorLock); UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand"); break; } @@ -3970,7 +4089,6 @@ DebugPrintLog("DoorLockProgrammingEventNotificationCommand宸茬粡閫氱煡"); gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock); } - UpdateDeviceStatus(doorLock); UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand"); break; } @@ -3992,8 +4110,6 @@ //ias.Save(); gwa.ReportAction("IASInfoReport", ias.iASInfo); } - - UpdateDeviceStatus(ias); UpdateDeviceInfo(ias, "IASInfoReport"); break; } @@ -4108,37 +4224,37 @@ #region 閫昏緫琚皟鐢ㄥ弽棣� else if (topic == gatewayID + "/" + "Logic/Execute_Respon") { - var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; - logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString()); + //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + //logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString()); - if (logic.logicExecuteRespo == null) - { - return; - } - //涓婃姤绫诲瀷閫氱煡 - if (gwa.ReportAction != null) - { - DebugPrintLog("LogicExecuteReport宸茬粡閫氱煡"); - gwa.ReportAction("LogicExecuteReport", logic.logicExecuteRespo); - } + //if (logic.logicExecuteRespo == null) + //{ + // return; + //} + ////涓婃姤绫诲瀷閫氱煡 + //if (gwa.ReportAction != null) + //{ + // DebugPrintLog("LogicExecuteReport宸茬粡閫氱煡"); + // gwa.ReportAction("LogicExecuteReport", logic.logicExecuteRespo); + //} } #endregion #region 鏃堕棿鐐规潯浠舵帹杩熸墽琛� else if (topic == gatewayID + "/" + "Logic/TimingWillArrive") { - var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; - logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString()); + //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + //logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString()); - if (logic.timingWillArriveData == null) - { - return; - } - //涓婃姤绫诲瀷閫氱煡 - if (gwa.ReportAction != null) - { - DebugPrintLog("TimingWillArrive宸茬粡閫氱煡"); - gwa.ReportAction("TimingWillArrive", logic.timingWillArriveData); - } + //if (logic.timingWillArriveData == null) + //{ + // return; + //} + ////涓婃姤绫诲瀷閫氱煡 + //if (gwa.ReportAction != null) + //{ + // DebugPrintLog("TimingWillArrive宸茬粡閫氱煡"); + // gwa.ReportAction("TimingWillArrive", logic.timingWillArriveData); + //} } #endregion #region 妯″紡瀹夐槻鍔ㄤ綔琚渶缁堟縺娲绘椂鍙戦�佹姤璀︿俊鎭� @@ -4212,22 +4328,18 @@ #region 璁惧璇锋眰APP鑾峰彇鍗囩骇鏁版嵁 else if (topic == gatewayID + "/" + "ZbDataPassthrough") { - var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") }; - gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString()); - if (gatewayTemp.clientDataPassthroughResponseData == null) - { - return; - } - //涓婃姤绫诲瀷閫氱煡 if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceRequestAcUpdateData"); - gwa.ReportAction("DeviceRequestAcUpdateData", gatewayTemp.clientDataPassthroughResponseData); + { + var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString()); + if (clientDataPassthrough != null) + { + DebugPrintLog("DeviceRequestAcUpdateData"); + gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough); + } } } #endregion - DebugPrintLog("缃戝叧杩斿洖鏁版嵁閫氱煡"); } catch (Exception ex) { -- Gitblit v1.8.0