From 9f326f4000847e6167d8166fa2f6a66f53cb3734 Mon Sep 17 00:00:00 2001 From: 黄学彪 <hxb@hdlchina.com.cn> Date: 星期四, 17 十二月 2020 09:07:13 +0800 Subject: [PATCH] 新云端Ver1.3 --- ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs | 1143 ++++++++++++++++++++++++++++---------------------------- 1 files changed, 568 insertions(+), 575 deletions(-) diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs index 64b9859..261ee6e 100755 --- a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs +++ b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs @@ -21,43 +21,39 @@ /// </summary> [System.Serializable] public class ZbGateway : ZbGatewayData - { + { #region 涓�鍫嗗彉閲� /// <summary> /// 涓荤綉鍏� /// </summary> - /// <value>The main gate way.</value> + [Newtonsoft.Json.JsonIgnore] public static ZbGateway MainGateWay { get { - return GateWayList.Find((obj) => { return obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId && obj.getGatewayBaseInfo.IsMainGateWay; }); - } - } - - /// <summary> - /// 涓荤綉鍏� - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public bool IsMainGateWay - { - get - { - return getGatewayBaseInfo != null && getGatewayBaseInfo.IsMainGateWay; + ZbGateway mainWay = null; + for (int i = 0; i < GateWayList.Count; i++) + { + if (GateWayList[i].HomeId == Config.Instance.HomeId) + { + //2020.07.16鍙樻洿:鍒閭d箞澶�,濡傛灉浣忓畢ID涓�鏍�,鍏堢‘瀹氬氨鏄畠浜�(涓嶇劧鏈夋椂鍊欑粡甯歌繑鍥瀗ull,鏈夊彲鑳芥槸鍒锋柊涓嶅埌) + mainWay = GateWayList[i]; + if (mainWay.IsMainGateWay == true) + { + //鐒跺悗濡傛灉瀹冪‘瀹炴槸涓荤綉鍏�,鐩存帴break + break; + } + } + } + return mainWay; } } /// <summary> /// 鏄惁浣跨敤杩滅▼杩炴帴妯″紡 /// </summary> - /// <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; + public static bool IsRemote; /// <summary> /// 缃戝叧淇濆瓨璺緞 @@ -68,7 +64,7 @@ { get { - var fileName = "Gateway_" + DeviceType.ZbGateway.ToString() + "_" + this.getGatewayBaseInfo?.gwID; + var fileName = "Gateway_" + DeviceType.ZbGateway.ToString() + "_" + this.GwId; return fileName; } } @@ -111,7 +107,13 @@ } return password; } - } + } + + /// <summary> + /// 缃戝叧杩滅▼杩炴帴鐨勪竴涓爣璇咺D,鑾峰彇鍒颁簡灏变笉鍐嶆敼鍙� + /// </summary> + [Newtonsoft.Json.JsonIgnore] + private static string RemoteClientId = new Random().Next(10, 99).ToString(); /// <summary> /// 缃戝叧鏄惁鍔犲瘑 @@ -299,7 +301,7 @@ return data; }); - } + } #endregion #region 璇诲彇鍗忚皟鍣∕AC鍦板潃. @@ -499,17 +501,9 @@ { //璐﹀彿ID string accountId = string.Empty; - if (homeId != string.Empty) + if (homeId != string.Empty) { - if (Shared.Phone.UserCenter.UserCenterResourse.UserInfo.AuthorityNo == 1) - { - //涓昏处鍙� - accountId = Config.Instance.Guid; - } - else - { - accountId = Config.Instance.Home.MainUserDistributedMark; - } + accountId = Config.Instance.Guid; } var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } }; var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } }; @@ -551,7 +545,6 @@ { await System.Threading.Tasks.Task.Run(async () => { - CommonDevice commonDev = null; Action<string, string> action1 = (topic, message) => { }; Actions += action1; var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 94 } }; @@ -1068,7 +1061,7 @@ /// </summary> public async System.Threading.Tasks.Task<Panel.PanelSwitchLevelInfo> ClientDataPassthroughBytesAsync(string deviceAddr, int devicePoint, long dataLength, byte[] passData) { - var myDevice = Shared.Common.LocalDevice.Current.GetDevice(deviceAddr, devicePoint); + var myDevice = Shared.Phone.HdlDeviceCommonLogic.Current.GetDevice(deviceAddr, devicePoint); Panel.PanelSwitchLevelInfo result = null; @@ -2334,49 +2327,54 @@ } } #endregion - - #region 閫氳杩炴帴 + + #region 鏈湴閫氳杩炴帴 + /// <summary> + /// 鏈湴杩炴帴鏄惁杩炴帴鎴愬姛 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public bool LocalIsConnected; /// <summary> /// 灞�鍩熺綉鐨凪QTT /// </summary> - IMqttClient localMqttClient = new MqttFactory().CreateMqttClient(); - bool localMqttIsConnecting; - [Newtonsoft.Json.JsonIgnore] - public bool localIsConnected; - /// <summary> - /// 鎵嬫満鏍囪瘑 + private IMqttClient localMqttClient = new MqttFactory().CreateMqttClient(); + /// <summary> + /// 鏈湴mqtt鏄惁姝e湪杩炴帴涓� /// </summary> - static Guid currentGuid = Guid.NewGuid(); + private bool localMqttIsConnecting; + /// <summary> + /// 鏈湴杩炴帴鐨勪竴涓鎴风ID(app鍚姩涔嬪悗灏变笉鍙樹簡) + /// </summary> + private static Guid LocalConnectGuid = 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 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; + public async Task StartLocalMqtt(string brokerName) + { + if (localMqttIsConnecting + || Shared.Common.Config.Instance.HomeId == "" + || LocalIsConnected) + { + return; } - await System.Threading.Tasks.Task.Factory.StartNew(async () => + await Task.Factory.StartNew(async () => { try { @@ -2401,7 +2399,7 @@ if (localMqttClient.DisconnectedHandler == null) { localMqttClient.UseDisconnectedHandler(async (e) => - { + { DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}"); await DisConnectLocalMqttClient("StartLocalMqtt.DisconnectedHandler"); //await StartLocalMqtt("ReConnect"); @@ -2409,50 +2407,60 @@ } if (localMqttClient.ConnectedHandler == null) { - localMqttClient.UseConnectedHandler(async (e) => - { - DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}"); - IsRemote = false; + localMqttClient.UseConnectedHandler(async (e) => + { + DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}"); + IsRemote = false; + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + Shared.Phone.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴鎴愬姛"); + } }); - } - - 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); - } - } + } + + var dateTime = DateTime.Now; + + new System.Threading.Thread(async () => + { + try + { + if (localMqttClient.Options == null) + { + var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT杩炴帴鍙傛暟濉厖 + .WithClientId(LocalConnectGuid.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) { + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + Shared.Phone.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父:\r\n" + ex.Message); + } DebugPrintLog($"灞�鍩熺綉閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); } finally @@ -2462,340 +2470,22 @@ }); } - class GateWayBaseInfomation - { - //public string GatewayUniqueId;//"Emq缃戝叧1", <!-- 缃戝叧Mac --> - public bool MqttOnlineStatus;//: true, <!-- 缃戝叧鍦ㄤ簯绔疎mq鏄惁鍦ㄧ嚎 --> - public string AesKey;// : "a5d8da8a-ddea-48", <!-- 涓庢缃戝叧鍦ㄤ簯绔疎mq閫氫俊鏃讹紝璐熻浇鍔犺В鐨�16浣岮es瀵嗛挜 --> - public string MacMark;//: "61eaa0ea-4812-4a7a-86d6-3098c61e64ed" <!-- 缃戝叧瀵瑰簲鐨勫敮涓�鐮� --> - } - /// <summary> - /// 褰撳墠鏈夊笎鍙蜂笅鎵�鏈夌殑缃戝叧鍒楄〃鍙婁俊鎭� - /// </summary> - static Dictionary<string, GateWayBaseInfomation> GateWayBaseInfomations = new Dictionary<string, GateWayBaseInfomation> { }; - /// <summary> - /// 鑾峰彇褰撳墠甯愬彿鎵�鏈夌殑缃戝叧淇℃伅 - /// </summary> - /// <returns></returns> - static async System.Threading.Tasks.Task initGateWayBaseInfomation() - { - if (AllowRemoteCtrl == false) - { - //娌℃湁杩滅▼杩炴帴鐨勬潈闄� - return; - } - string loginToken = Config.Instance.Token; - if (Config.Instance.Home.IsOthreShare == true) - { - //鑾峰彇鎴愬憳鐨勭壒娈奣oken - var pra = new - { - CommonPage.RequestVersion, - LoginAccessToken = Config.Instance.Token, - MainAccountId = Config.Instance.Home.MainUserDistributedMark, - SharedHid = Config.Instance.Home.Id - }; - - var listNotShow = new List<string>() { "NotSetAgain" }; - var resultData = await Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, listNotShow); - if (resultData == null) - { - return; - } - var revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Common.ResponseEntity.ResponsePack>(Encoding.UTF8.GetString(resultData)); - //鍒嗕韩閾炬帴 - var info = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Phone.UserCenter.MemberAdministratorResult>(revertObj.ResponseData.ToString()); - loginToken = info.RequestToken; - } - - try - { - //璁剧疆璁块棶鎺ュ彛鐨勫弬鏁� - var pra2 = new Shared.Phone.UserCenter.GetGatewayPra(); - pra2.IsOtherAccountCtrl = Config.Instance.Home.IsOthreShare; - pra2.ReqDto.PageSetting.Page = 1; - pra2.ReqDto.PageSetting.PageSize = 20; - pra2.ReqDto.LoginAccessToken = loginToken; - var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(pra2)); - - var result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, loginToken); - if (result != null) - { - var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result)); - - var statuCode = jobject["StateCode"].ToString(); - if (statuCode != "Success") - { - //搴忓垪鍖栧璞� - var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pra2); - //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"]; - if (responseData != null) - { - if (responseData["PageData"] != null) - { - var list = JArray.Parse(responseData["PageData"].ToString()); - foreach (var v in list) - { - GateWayBaseInfomations[v["GatewayUniqueId"].ToString()] = new GateWayBaseInfomation { AesKey = v["AesKey"].ToString(), MacMark = v["MacMark"].ToString(), MqttOnlineStatus = bool.Parse(v["MqttOnlineStatus"].ToString()) }; - //if (RemoteMqttClient.IsConnected) - { - await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/{v["MacMark"].ToString()}/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce); - } - } - } - } - } - } - catch (Exception ex) - { - Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(ex); - } - } - - /// <summary> - /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴 - /// </summary> - static bool remoteMqttIsConnecting; - - /// <summary> - /// 杩滅▼MqttClient - /// </summary> - public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient(); - static bool remoteIsConnected; - - /// <summary> - /// 鍚姩杩滅▼Mqtt - /// </summary> - /// <returns>The start.</returns> - /// <param name="brokerName">Broker name.</param> - 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) - { - //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� - remoteMqttIsConnecting = true; - - #region 鍒濆鍖栬繙绋婱qtt - //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 - if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) - { - RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => - { - //杩欓噷鏄壒娈婄殑涓婚 - 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); - }); - } - - if (RemoteMqttClient.DisconnectedHandler == null) - { - RemoteMqttClient.UseDisconnectedHandler(async (e) => - { - DebugPrintLog($"杩滅▼杩炴帴鏂紑"); - await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler"); - //await StartRemoteMqtt(); - }); - } - if (RemoteMqttClient.ConnectedHandler == null) - { - 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(); - - //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅 - var gateWayList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId); - if (gateWayList.Find(obj => obj.getGatewayBaseInfo.IsMainGateWay == true) == null) - { - if (gateWayList.Count == 1) - { - gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true; - } - else - { - for (int i = 0; i < gateWayList.Count; i++) - { - var gateWay = gateWayList[i]; - var info = await gateWay.GetZbGwInfoAsync(); - if (info == null || info.getGwData == null) - { - continue; - } - if (info.getGwData.IsDominant == 1) - { - for (int j = 0; j < gateWayList.Count; j++) - { - if (gateWayList[i].getGatewayBaseInfo.gwID == info.getGwData.GwId) - { - gateWayList[i].getGatewayBaseInfo.IsMainGateWay = true; - } - else - { - gateWayList[i].getGatewayBaseInfo.IsMainGateWay = false; - } - } - break; - } - } - } - } - }); - } - #endregion - } - - try - { - 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) - { - var connEmqDomainPort = responseData["ConnEmqDomainPort"]?.ToString(); - 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() - //.WithCommunicationTimeout(TimeSpan.FromSeconds(10)) - .Build(); - await DisConnectRemoteMqttClient("StartRemoteMqtt"); - await RemoteMqttClient.ConnectAsync(options, CancellationToken.None); - - remoteIsConnected = true; - } - } - } - catch { } - finally - { - //鏈�缁堣閲婃斁杩炴帴鐘舵�� - remoteMqttIsConnecting = false; - } - } - catch (Exception ex) - { - DebugPrintLog($"杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); - } - }); - } - /// <summary> /// 鏂紑鏈嶅姟鍣ㄨ繛鎺� /// </summary> - public async System.Threading.Tasks.Task DisConnectLocalMqttClient(string s) + public async Task DisConnectLocalMqttClient(string s) { try { - if (localIsConnected) - { - localIsConnected = false; - DebugPrintLog($"Local涓诲姩鏂紑_{s}"); - //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); - await localMqttClient.DisconnectAsync(); - } + if (LocalIsConnected) + { + LocalIsConnected = false; + //杩欎釜涓滆タ涔熻寮� + localMqttIsConnecting = false; + DebugPrintLog($"Local涓诲姩鏂紑_{s}"); + //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await localMqttClient.DisconnectAsync(); + } } catch (Exception ex) { @@ -2803,31 +2493,306 @@ } } - /// <summary> - /// 鏂紑杩滅▼Mqtt鐨勯摼鎺� + /// <summary> + /// 寮哄埗鏂紑鏈湴鐨勭綉鍏宠繛鎺� /// </summary> - public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s = "") - { + public async Task CloseLocalConnectionOnForce() + { + try + { + await localMqttClient.DisconnectAsync(); + } + catch { } + finally + { + LocalIsConnected = false; + //杩欎釜涓滆タ涔熻寮� + localMqttIsConnecting = false; + } + } + + #endregion + + #region 杩滅▼閫氳杩炴帴 + + /// <summary> + /// 褰撳墠鏈夊笎鍙蜂笅鎵�鏈夌殑浜戠缃戝叧鍒楄〃鍙婁俊鎭� + /// </summary> + public static Dictionary<string, Shared.Phone.GatewayResult> DicGatewayBaseInfo = new Dictionary<string, Shared.Phone.GatewayResult> { }; + /// <summary> + /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴 + /// </summary> + private static bool remoteMqttIsConnecting; + /// <summary> + /// 杩滅▼MqttClient + /// </summary> + public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient(); + /// <summary> + /// 杩滅▼杩炴帴鏄惁瀹屾垚 + /// </summary> + private static bool remoteIsConnected; + /// <summary> + /// 杩滅▼寮�濮嬭繛鎺ョ殑鏃堕棿鐐� + /// </summary> + private static DateTime RemoteConnectTime = DateTime.Now; + + /// <summary> + /// 鍚姩杩滅▼Mqtt + /// </summary> + public static async Task StartRemoteMqtt() + { + //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺 + if (Config.Instance.Home.IsRemoteControl == false + || Config.Instance.Home.Id == "" + || remoteIsConnected) + { + return; + } + //濡傛灉杩滅▼杩樺湪杩炴帴涓� + if (remoteMqttIsConnecting == true) + { + //濡傛灉杩欎釜鍙橀噺涓�鐩村浜庤繛鎺ヤ腑鐨勭姸鎬�,浣嗘槸宸茬粡杩囧幓浜�10绉掍簡,杩樻槸true鐨勮瘽,璇存槑杩欓噷鏄湁鐐归棶棰樼殑,闇�瑕侀噸鏂板垱寤� + if ((DateTime.Now - RemoteConnectTime).TotalMilliseconds < 10 * 1000) + { + return; + } + } + //璁板綍璧疯繖娆¤繙绋嬭繛鎺ョ殑鏃堕棿鐐� + RemoteConnectTime = DateTime.Now; + + //鍒濆鍖栬繙绋媘qtt浜嬩欢 + InitRemoteMqttEvent(); + try { - if (remoteIsConnected) + //鑾峰彇杩滅▼mqtt閾炬帴淇℃伅 + var pra = new { attachClientId = RemoteClientId, homeType = "ZIGBEE" }; + var result = Shared.Phone.HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/app/mqtt/getRemoteInfo", RestSharp.Method.POST, pra); + if (result != null && result.Code == Shared.Phone.HttpMessageEnum.A鎴愬姛) { - remoteIsConnected = false; - DebugPrintLog($"Remote涓诲姩鏂紑_{s}"); - //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); - await RemoteMqttClient.DisconnectAsync(); + var jobject = JObject.Parse(result.Data.ToString()); + + var connEmqClientId = jobject["clientId"]?.ToString(); + var connEmqUserName = jobject["userName"]?.ToString(); + var connEmqPwd = jobject["passWord"]?.ToString(); + //璁板綍璧峰綋鍓嶇殑瀹㈡埛绔疘D + Config.Instance.ConnEmqClientId = connEmqClientId; + + var connEmqDomainPorts = jobject["url"].ToString().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 DisConnectRemoteMqttClient("StartRemoteMqtt"); + await RemoteMqttClient.ConnectAsync(options, CancellationToken.None); + + remoteIsConnected = true; } } - catch (Exception e) - { - DebugPrintLog($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); + catch { } + finally + { + //鏈�缁堣閲婃斁杩炴帴鐘舵�� + remoteMqttIsConnecting = false; + } + } + + /// <summary> + /// 鍒濆鍖栬繙绋媘qtt浜嬩欢 + /// </summary> + private static void InitRemoteMqttEvent() + { + lock (RemoteMqttClient) + { + //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� + remoteMqttIsConnecting = true; + + //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 + if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) + { + RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => + { + //杩欓噷鏄壒娈婄殑涓婚 + 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); + }); + } + + if (RemoteMqttClient.DisconnectedHandler == null) + { + RemoteMqttClient.UseDisconnectedHandler(async (e) => + { + DebugPrintLog($"杩滅▼杩炴帴鏂紑"); + await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler"); + }); + } + + if (RemoteMqttClient.ConnectedHandler == null) + { + RemoteMqttClient.UseConnectedHandler(async (e) => + { + DebugPrintLog($"杩滅▼杩炴帴鎴愬姛"); + + if (Config.Instance.Home.IsOtherShare == 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"); + + //濡傛灉杩欎釜鍑芥暟鍗′箙浜嗙殑璇濓紝浼氭帴鏀跺埌浜戠鎺ㄩ�佺殑鎸や笅绾夸富棰橈紝涓嶇煡閬撲负浠�涔� + new System.Threading.Thread(async () => + { + await InitGateWayBaseInfomation(); + + //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅 + var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId); + if (gateWayList.Find(obj => obj.IsMainGateWay == true) == null) + { + if (gateWayList.Count == 1) + { + gateWayList[0].IsMainGateWay = true; + } + else + { + for (int i = 0; i < gateWayList.Count; i++) + { + var gateWay = gateWayList[i]; + var info = await gateWay.GetZbGwInfoAsync(); + if (info == null || info.getGwData == null) + { + continue; + } + if (info.getGwData.IsDominant == 1) + { + for (int j = 0; j < gateWayList.Count; j++) + { + if (gateWayList[i].GwId == info.getGwData.GwId) + { + gateWayList[i].IsMainGateWay = true; + } + else + { + gateWayList[i].IsMainGateWay = false; + } + } + break; + } + } + } + } + }) + { IsBackground = true }.Start(); + }); + } } + } + + /// <summary> + /// 鍒濆鍖栧綋鍓嶅笎鍙锋墍鏈夌殑浜戠缃戝叧淇℃伅 + /// </summary> + /// <returns></returns> + private static async Task InitGateWayBaseInfomation() + { + if (Config.Instance.Home.IsRemoteControl == false) + { + //娌℃湁杩滅▼杩炴帴鐨勬潈闄� + return; + } + //鑾峰彇浜戠缃戝叧淇℃伅 + var listGatewayInfo = Shared.Phone.HdlGatewayLogic.Current.GetGateWayListFromDataBase(Config.Instance.Home.Id); + if (listGatewayInfo == null) { return; } + + foreach (var info in listGatewayInfo.Values) + { + try + { + //鏈夊彲鑳戒簯绔槸杩欎箞澶勭悊:濡傛灉娌℃湁杩滅▼鏉冮檺,鍒欎笉缁橝esKey + if (string.IsNullOrEmpty(info.AesKey) == true) { continue; } + //淇濆瓨缂撳瓨 + DicGatewayBaseInfo[info.Mac] = info; + //鎴戜篃涓嶇煡閬撹繖涓槸骞插槢鐨� + await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/" + info.Id + "/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce); + } + catch (Exception ex) + { + Shared.Phone.HdlLogLogic.Current.WriteLog(ex); + } + } + } + + /// <summary> + /// 鏂紑杩滅▼Mqtt鐨勯摼鎺� + /// </summary> + public static async Task DisConnectRemoteMqttClient(string s = "") + { + try + { + if (remoteIsConnected) + { + remoteIsConnected = false; + //杩欎釜涓滆タ涔熻寮� + remoteMqttIsConnecting = false; + DebugPrintLog($"Remote涓诲姩鏂紑_{s}"); + //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await RemoteMqttClient.DisconnectAsync(); + } + } + catch (Exception e) + { + DebugPrintLog($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); + } + } + + /// <summary> + /// 寮哄埗鏂紑杩滅▼Mqtt鐨勯摼鎺� + /// </summary> + /// <returns></returns> + public static async Task CloseRemoteConnectionOnForce() + { + try + { + await RemoteMqttClient?.DisconnectAsync(); + } + catch { } + finally + { + remoteIsConnected = false; + //杩欎釜涓滆タ涔熻寮� + remoteMqttIsConnecting = false; + } } #endregion - + #region 鏁版嵁鍙戦�� - + /// <summary> /// 鍙戦�佹秷鎭埌鏈嶅姟鍣� /// </summary> @@ -2856,35 +2821,35 @@ /// </summary> async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false) { - 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 }); - } - } + try + { + if (this.GwId == string.Empty || !DicGatewayBaseInfo.ContainsKey(this.GwId)) + { + return; } - } - catch - { + var gateWayBaseInfomation = DicGatewayBaseInfo[this.GwId]; + message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey); + var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.Id}/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 + { } } @@ -2904,6 +2869,16 @@ return; } + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + string text = "杩滅▼鍙戦��:"; + if (IsRemote == false) { text = "鏈湴鍙戦��:"; } + text += topic + "\r\n"; + text += Encoding.UTF8.GetString(message) + "\r\n"; + Shared.Phone.HdlLogLogic.Current.WriteLog(2, text); + } + if (IsRemote) { await SendRemoteMsg(topic, message, retain); @@ -2911,8 +2886,8 @@ } else { - DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}"); - + DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}"); + if (IsEncry) { //鏂囦欢娴佷笉鐢ㄥ姞瀵� @@ -2920,25 +2895,30 @@ { 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) + } + if (LocalIsConnected) + { + try { - DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}"); + 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)}_鏄惁鍔犲瘑:{IsEncry}"); - await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + await StartLocalMqtt("ReConnect"); + if (LocalIsConnected) + { + DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}"); + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); } - } - } + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + Shared.Phone.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父鏂紑"); + } + } + } } } catch (Exception ex) @@ -2957,12 +2937,12 @@ public async System.Threading.Tasks.Task Send(string topic, string message, bool retain = false) { if (string.IsNullOrEmpty(message)) - { + { return; } await Send(topic, System.Text.Encoding.UTF8.GetBytes(message), retain); - } - + } + /// <summary> /// 寮哄埗鎸囧畾浣跨敤鏈湴灞�鍩熺綉鍙戦�佹秷鎭埌鏈嶅姟鍣� /// </summary> @@ -2977,35 +2957,35 @@ if (Shared.Common.Config.Instance.HomeId == "") { return; - } - - DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{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)}_鏄惁鍔犲瘑:{IsEncry}"); - await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); - } - } + } + + DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{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)}_鏄惁鍔犲瘑:{IsEncry}"); + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + } } } catch (Exception ex) @@ -3044,7 +3024,7 @@ } if (topics[2] == "NotifyGateWayInfoChange") { - initGateWayBaseInfomation(); + InitGateWayBaseInfomation(); return; } if (topics[2] == "Common") @@ -3057,10 +3037,10 @@ } else { - foreach (var key in GateWayBaseInfomations.Keys) + foreach (var key in DicGatewayBaseInfo.Keys) { - var value = GateWayBaseInfomations[key]; - if (value.MacMark == macMark) + var value = DicGatewayBaseInfo[key]; + if (value.Id == macMark) { topic = $"{key}/{topic}"; message = System.Text.Encoding.UTF8.GetString(ZigBee.Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, value.AesKey)); @@ -3110,9 +3090,9 @@ payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password)); } } - else - { - payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); + else + { + payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); } DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{payloadString}"); ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload); @@ -3150,12 +3130,20 @@ 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); + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + string text = "缃戝叧鍥炲:" + topic + "\r\n"; + text += message + "\r\n"; + Shared.Phone.HdlLogLogic.Current.WriteLog(2, text); + } + + //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) + Shared.Phone.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message); + + var gwa = GateWayList.Find(obj => obj.GwId == gatewayID); if (gwa == null) { return; @@ -3183,8 +3171,8 @@ else { jobject = Newtonsoft.Json.Linq.JObject.Parse(message); - } - + } + #region 杩滅▼,涓荤綉鍏充笂鎶ラ�氱煡 if (IsRemote) { @@ -3193,16 +3181,16 @@ var gwData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GetGwData>(jobject["Data"].ToString()); if (gwData != null) { - var gwList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId); + var gwList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId); for (int i = 0; i < gwList.Count; i++) { - if (gwList[i].getGatewayBaseInfo.gwID == gatewayID) - { - gwList[i].getGatewayBaseInfo.IsMainGateWay = true; + if (gwList[i].GwId == gatewayID) + { + gwList[i].IsMainGateWay = true; } - else - { - gwList[i].getGatewayBaseInfo.IsMainGateWay = false; + else + { + gwList[i].IsMainGateWay = false; } } } @@ -3218,15 +3206,15 @@ #endregion #region 璁惧鐘舵�佷笂鎶� - else if (topic == gatewayID + "/" + "DeviceStatusReport" + "/" + addr + "/" + epoint + "/" + cluID + "/" + attrId) + if (topic == gatewayID + "/" + "DeviceStatusReport" + "/" + addr + "/" + epoint + "/" + cluID + "/" + attrId) { var deviceID = jobject.Value<int>("Device_ID"); var deviceAddr = jobject.Value<string>("DeviceAddr"); var tempEpoint = jobject.Value<int>("Epoint"); var dataId = jobject.Value<int>("Data_ID"); - var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint }; - tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString()); + var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint }; + tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString()); UpdateDeviceInfo(tempDevice, "DeviceStatusReport"); } #endregion @@ -3237,7 +3225,7 @@ switch ((DeviceType)(deviceID)) { case DeviceType.DoorLock: - var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; + var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.GwId }; var OperatingEventNotificationDatad = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockOperatingEventNotificationCommand>(jobject["Data"].ToString()); if (OperatingEventNotificationDatad != null) { @@ -3260,7 +3248,7 @@ switch ((DeviceType)(deviceID)) { case DeviceType.DoorLock: - var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; + var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.GwId }; var ProgrammingEventNotificationData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockProgrammingEventNotificationCommand>(jobject["Data"].ToString()); if (ProgrammingEventNotificationData != null) { @@ -3274,12 +3262,12 @@ UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand"); break; } - } + } #endregion #region IAS瀹夐槻淇℃伅涓婃姤 - - //2020.05.11 鍒犻櫎 - + + //2020.05.11 鍒犻櫎 + #endregion #region 涓嬭浇杩涘害涓婃姤 else if (topic == gatewayID + "/" + "DownloadFile_Progress") @@ -3362,7 +3350,7 @@ #region 闃插尯琚Е鍙戞椂鎶ュ憡 else if (topic == gatewayID + "/" + "Security/ZoneTriggerReport") { - var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId }; ias.zoneTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.ZoneTriggerReportData>(jobject["Data"].ToString()); if (ias.zoneTriggerReportData == null) @@ -3380,7 +3368,7 @@ #region 閫昏緫琚皟鐢ㄥ弽棣� else if (topic == gatewayID + "/" + "Logic/Execute_Respon") { - //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId }; //logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString()); //if (logic.logicExecuteRespo == null) @@ -3398,7 +3386,7 @@ #region 鏃堕棿鐐规潯浠舵帹杩熸墽琛� else if (topic == gatewayID + "/" + "Logic/TimingWillArrive") { - //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId }; //logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString()); //if (logic.timingWillArriveData == null) @@ -3416,7 +3404,7 @@ #region 妯″紡瀹夐槻鍔ㄤ綔琚渶缁堟縺娲绘椂鍙戦�佹姤璀︿俊鎭� else if (topic == gatewayID + "/" + "Security/ModeTriggerReport") { - var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId }; ias.modeTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.ModeTriggerReportData>(jobject["Data"].ToString()); if (ias.modeTriggerReportData == null) { @@ -3433,7 +3421,7 @@ #region 閫氳繃澶栭儴鏂瑰紡甯冮槻鎾ら槻鎴愬姛鏃舵姤鍛婃伅 else if (topic == gatewayID + "/" + "Security/EnOrWithdrawSucceedReport") { - var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId }; ias.enOrWithdrawSucceedReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.EnOrWithdrawSucceedReportData>(jobject["Data"].ToString()); if (ias.enOrWithdrawSucceedReportData == null) { @@ -3450,7 +3438,7 @@ #region 鑳佽揩瀵嗙爜鎾ら槻鏃剁煭淇℃帹閫� else if (topic == gatewayID + "/" + "Security/PushTargetInfo") { - var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId }; ias.coercedPWDWithdrawReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.CoercedPWDWithdrawReportData>(jobject["Data"].ToString()); if (ias.coercedPWDWithdrawReportData == null) { @@ -3470,12 +3458,12 @@ { //涓婃姤绫诲瀷閫氱煡 if (gwa.ReportAction != null) - { - var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString()); - if (clientDataPassthrough != null) - { - DebugPrintLog("DeviceRequestAcUpdateData"); - gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough); + { + var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString()); + if (clientDataPassthrough != null) + { + DebugPrintLog("DeviceRequestAcUpdateData"); + gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough); } } } @@ -3497,6 +3485,11 @@ /// </summary> public void ReSave() { + if (Shared.Common.Config.Instance.Home.IsShowTemplate == true) + { + //灞曠ず妯℃澘鏃�,涓嶅厑璁镐繚瀛樻枃浠�(闃叉灞炴�т笂鎶ョ敤鐨�) + return; + } Global.WriteFileByBytesByHomeId(FilePath, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(this))); } #endregion @@ -3513,7 +3506,7 @@ #if DEBUG if (flage == true) { - if (msg.Contains("DeviceStatusReport") == false) + //if (msg.Contains("DeviceInfoRespon") == true) { System.Console.WriteLine(msg + " " + System.DateTime.Now.ToLongTimeString() + " " + System.DateTime.Now.Millisecond); } -- Gitblit v1.8.0