From 66a9965c44ecc32a6696abca876ab9d1cd091584 Mon Sep 17 00:00:00 2001 From: gxc <guoxuecheng@guoxuechengdeMacBook-Pro.local> Date: 星期五, 28 二月 2020 15:25:13 +0800 Subject: [PATCH] 2020.2.28 --- ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs | 227 ++++++++++++++++++++++++++++++++++++++++---------------- 1 files changed, 161 insertions(+), 66 deletions(-) diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs index 8c1ef41..86ca1f3 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> @@ -95,7 +101,7 @@ } } - #region variable + #region variable /// <summary> /// 杩滅▼杩炴帴鎴愬姛鏃剁殑鏃堕棿 /// </summary> @@ -218,6 +224,7 @@ /// <para>绗竴涓弬鏁帮細濡傛灉涓� DDevice/IsGetEpointInfo:鏈夋柊璁惧鍔犲叆zigbee缃戠粶鍙嶉</para>璁惧璇锋眰APP鑾峰彇鍗囩骇鏁版嵁 /// <para>绗竴涓弬鏁帮細濡傛灉涓� Device/DeviceJoinZbNet:鑾峰彇鏂拌澶囨墍鏈夌鐐逛俊鎭槸鍚︽垚鍔熷弽棣�</para> /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceRequestAcUpdateData: 璁惧璇锋眰绌鸿皟鍙戝崌绾ф暟鎹�</para> + /// "宸茬粡閫氱煡");//宸茬粡閫氱煡"); /// </summary> [Newtonsoft.Json.JsonIgnore] public Action<string, object> ReportAction; @@ -603,7 +610,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 { } @@ -3177,7 +3185,7 @@ .WithTcpServer(brokerName, 1883) .WithKeepAlivePeriod(TimeSpan.FromSeconds(20)) .WithCleanSession() - .WithCommunicationTimeout(TimeSpan.FromSeconds(4)) + //.WithCommunicationTimeout(TimeSpan.FromSeconds(10)) .WithCredentials("", "") .Build(); await localMqttClient.ConnectAsync(options, CancellationToken.None); @@ -3228,6 +3236,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) { @@ -3270,11 +3283,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"]; @@ -3310,7 +3325,7 @@ /// 杩滅▼MqttClient /// </summary> public static IMqttClient RemoteMqttClient= new MqttFactory().CreateMqttClient(); - static bool remoteIsConnected; + static bool remoteIsConnected; private int IsLogin = 0; [Newtonsoft.Json.JsonIgnore] static Action actionTemp; @@ -3322,10 +3337,12 @@ /// <param name="brokerName">Broker name.</param> public static async System.Threading.Tasks.Task StartRemoteMqtt() { - if (remoteMqttIsConnecting - || !Shared.Common.Config.Instance.IsLogin - || Shared.Common.Config.Instance.HomeId == "" - || remoteIsConnected) + //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺 + if (AllowRemoteCtrl == false + || remoteMqttIsConnecting + || !Shared.Common.Config.Instance.IsLogin + || Shared.Common.Config.Instance.HomeId == "" + || remoteIsConnected) { return; } @@ -3358,7 +3375,7 @@ { DebugPrintLog($"杩滅▼杩炴帴鏂紑"); await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler"); - await StartRemoteMqtt(); + //await StartRemoteMqtt(); }); } if (RemoteMqttClient.ConnectedHandler == null) @@ -3366,6 +3383,18 @@ 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.ConnEmqClientId + "/Push/NotifySqueeze"); + await initGateWayBaseInfomation(); Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote); //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅 @@ -3411,24 +3440,44 @@ 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 + }; + 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 + }; + 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; + } var responseData = jobject["ResponseData"]; if (responseData != null) { @@ -3436,6 +3485,8 @@ 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]; @@ -3447,7 +3498,7 @@ .WithCredentials(connEmqUserName, connEmqPwd) .WithKeepAlivePeriod(TimeSpan.FromSeconds(20)) .WithCleanSession() - .WithCommunicationTimeout(TimeSpan.FromSeconds(6)) + //.WithCommunicationTimeout(TimeSpan.FromSeconds(10)) .Build(); await DisConnectRemoteMqttClient("StartRemoteMqtt"); await RemoteMqttClient.ConnectAsync(options, CancellationToken.None); @@ -3481,7 +3532,8 @@ { localIsConnected = false; DebugPrintLog($"Local涓诲姩鏂紑_{s}"); - await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await localMqttClient.DisconnectAsync(); } } catch (Exception ex) @@ -3501,10 +3553,11 @@ { remoteIsConnected = false; DebugPrintLog($"Remote涓诲姩鏂紑_{s}"); - await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await RemoteMqttClient.DisconnectAsync(); } } - catch(Exception e) { + catch(Exception e) { DebugPrintLog($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); } } @@ -3601,9 +3654,7 @@ //鏂囦欢娴佷笉鐢ㄥ姞瀵� 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)); + message = SecuritySet.AesEncryptBytes(message, password); } } if (localIsConnected) @@ -3614,10 +3665,12 @@ } 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 }); } } @@ -3644,8 +3697,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 @@ -3664,8 +3767,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; @@ -3680,7 +3782,7 @@ { return; } - if (topics[2]== "NotifyGateWayInfoChagne") { + if (topics[2]== "NotifyGateWayInfoChange") { initGateWayBaseInfomation(); return; } @@ -3727,39 +3829,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 } } @@ -3790,7 +3889,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) @@ -3822,9 +3924,6 @@ { jobject = Newtonsoft.Json.Linq.JObject.Parse(message); } - - //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) - Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, jobject); #region 杩滅▼,涓荤綉鍏充笂鎶ラ�氱煡 if (IsRemote) @@ -4268,22 +4367,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