From 9a4b76398009cf76c508d61f7e48fb6f5cb7ac2d Mon Sep 17 00:00:00 2001 From: xm <1271024303@qq.com> Date: 星期二, 21 七月 2020 09:46:53 +0800 Subject: [PATCH] 请合并最新多功能面板代码 --- ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs | 3537 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 3,537 insertions(+), 0 deletions(-) diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs new file mode 100755 index 0000000..9ff57e4 --- /dev/null +++ b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs @@ -0,0 +1,3537 @@ +锘縰sing System; +using System.Collections.Generic; +using ZigBee.Common; +using Shared; +using System.Linq; +using System.Text; +using System.Threading; +using System.Net.Sockets; +using System.Net; +using Newtonsoft.Json.Linq; +using MQTTnet; +using Shared.Common; +using Shared.Phone.UserView; +using MQTTnet.Client; +using System.Threading.Tasks; + +namespace ZigBee.Device +{ + /// <summary>茠 + /// ZigBee缃戝叧瀵硅薄 + /// </summary> + [System.Serializable] + public class ZbGateway : ZbGatewayData + { + #region 涓�鍫嗗彉閲� + /// <summary> + /// 涓荤綉鍏� + /// </summary> + /// <value>The main gate way.</value> + public static ZbGateway MainGateWay + { + get + { + return GateWayList.Find((obj) => { return obj.HomeId == Shared.Common.Config.Instance.HomeId && obj.IsMainGateWay; }); + } + } + + /// <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; + + /// <summary> + /// 缃戝叧淇濆瓨璺緞 + /// </summary> + /// <value>The file path.</value> + [Newtonsoft.Json.JsonIgnore] + public string FilePath + { + get + { + var fileName = "Gateway_" + DeviceType.ZbGateway.ToString() + "_" + this.GwId; + return fileName; + } + } + + /// <summary> + /// 绛夊緟浠庣綉鍏虫帴鏀舵暟鎹殑鏃堕棿 + /// </summary> + /// <value>The wait receive data time.</value> + [Newtonsoft.Json.JsonIgnore] + public int WaitReceiveDataTime + { + get + { + if (Device.ZbGateway.RemoteMqttClient != null && Device.ZbGateway.RemoteMqttClient.IsConnected) + { + return 10000; + } + else + { + return 3000; + } + } + } + + /// <summary> + /// 灞�鍩熺綉鍔犲瘑瀵嗙爜 + /// </summary> + private string password; + /// <summary> + /// 灞�鍩熺綉鍔犲瘑瀵嗛挜 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public string Password + { + get + { + if (password == null) + { + password = Guid.NewGuid().ToString().Substring(0, 16); + } + return password; + } + } + + /// <summary> + /// 缃戝叧鏄惁鍔犲瘑 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public bool IsEncry; + /// <summary> + /// 缃戝叧褰撳墠鍏挜 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public string PubKey; + /// <summary> + /// 鎵�鏈夌殑缃戝叧鍒楄〃 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public static List<ZbGateway> GateWayList = new List<ZbGateway>(); + + /// <summary> + /// 缃戝叧鎺ㄩ�佹暟鎹� + /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceInComingRespon:璁惧鏂颁笂鎶�</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceStatusReport:璁惧涓婃姤</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� IASInfoReport:IAS瀹夐槻淇℃伅涓婃姤</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceStatusReport:璁惧涓婃姤</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� EnOrWithdrawSucceedReport:閫氳繃澶栭儴鏂瑰紡甯冮槻鎾ら槻鎴愬姛鏃舵姤鍛�</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� DownloadFileProgress:涓嬭浇杩涘害</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� CordinatorUpgradePercent:鍗忚皟鍣ㄥ崌绾х櫨鍒嗘瘮</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceUpgradePercent:鑺傜偣璁惧鍗囩骇鐧惧垎姣�</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� VirtualDriveUpgrade:铏氭嫙璁惧鍗囩骇杩涘害</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� ZoneTriggerReport:闃插尯琚Е鍙戞椂鎶ュ憡</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� LogicExecuteReport:閫昏緫琚皟鐢ㄥ弽棣�</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� TimingWillArrive:鏃堕棿鐐规潯浠舵帹杩熸墽琛�</para> + /// <para>绗竴涓弬鏁帮細 濡傛灉涓� ModeTriggerReport:妯″紡瀹夐槻鍔ㄤ綔琚渶缁堟縺娲绘椂鍙戦�佹姤璀︿俊鎭�</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� EnOrWithdrawSucceedReport:閫氳繃澶栭儴鏂瑰紡甯冮槻鎾ら槻鎴愬姛鏃舵姤鍛婃伅</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� PushTargetInfoReport:鑳佽揩瀵嗙爜鎾ら槻鏃剁煭淇℃帹閫�</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� DDevice/IsGetEpointInfo:鏈夋柊璁惧鍔犲叆zigbee缃戠粶鍙嶉</para>璁惧璇锋眰APP鑾峰彇鍗囩骇鏁版嵁 + /// <para>绗竴涓弬鏁帮細濡傛灉涓� Device/DeviceJoinZbNet:鑾峰彇鏂拌澶囨墍鏈夌鐐逛俊鎭槸鍚︽垚鍔熷弽棣�</para> + /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceRequestAcUpdateData: 璁惧璇锋眰绌鸿皟鍙戝崌绾ф暟鎹�</para> + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public Action<string, object> ReportAction; + + /// <summary> + /// 缃戝叧鏂囦欢娴佸唴瀹归�氱煡 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public Action<string, byte[]> FileContentAction; + + /// <summary> + /// 缃戝叧鍥炲鏁版嵁鍐呭閫氱煡 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public Action<string, string> GwResDataAction; + + /// <summary> + /// 涓庣綉鍏抽�氳鏃跺彂閫佸拰鎺ユ敹鏁版嵁閫氱煡 + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public Action<string, string> Actions; + + #endregion + + #region 缃戝叧API + #region 缃戝叧淇℃伅 + /// <summary> + ///鑾峰彇缃戝叧鐗堟湰淇℃伅 + /// <para> gateway锛氬綋鍓嶇綉鍏�</para> + /// </summary> + public async System.Threading.Tasks.Task<GetGwVersionAllData> GetZbGwVersionInfoAsync() + { + return await System.Threading.Tasks.Task.Run(async () => + { + GetGwVersionAllData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new GetGwVersionAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GetGwVersionAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "GetZbGwVersionRespon") + { + var getGwVersion = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwVersionData>(jobject["Data"].ToString()); + + if (getGwVersion == null) + { + d = new GetGwVersionAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GetGwVersionAllData { getGwVersion = getGwVersion }; + //Save(); + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{topic}"); + } + } + }; + Actions += action; + DebugPrintLog("GetGwVersionData_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 92 } }; + Send("GetZbGwVersion", jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new GetGwVersionAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("GetGwVersionData_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 鑾峰彇缃戝叧淇℃伅 + /// <summary> + /// 鑾峰彇缃戝叧淇℃伅 + /// <para> gateway锛氬綋鍓嶇綉鍏�</para> + /// </summary> + public async System.Threading.Tasks.Task<GetGwAllData> GetZbGwInfoAsync() + { + return await System.Threading.Tasks.Task.Run(async () => + { + GetGwAllData data = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + if (topic == gatewayID + "/" + "GetZbGwInfo_Respon") + { + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + var getGwInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwData>(jobject["Data"].ToString()); + + if (getGwInfo == null) + { + data = new GetGwAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + data = new GetGwAllData { getGwData = getGwInfo }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{topic}"); + } + } + }; + Actions += action; + + DebugPrintLog("GetGwData_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 95 } }; + Send("GetZbGwInfo", jObject.ToString()); + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (data != null) + { + break; + } + } + + Actions -= action; + DebugPrintLog("GetGwData_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return data; + }); + } + #endregion + + #region 璇诲彇鍗忚皟鍣∕AC鍦板潃. + ///<summary > + /// 璇诲彇鍗忚皟鍣∕AC鍦板潃/绔偣榛樿鏄�08 + /// </summary> + public async System.Threading.Tasks.Task<GetMacResponData> ReadMacAsync() + { + return await System.Threading.Tasks.Task.Run(async () => + { + GetMacResponData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new GetMacResponData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GetMacResponData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbGw/GetMac_Respon") + { + var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<MacAddrData>(jobject["Data"].ToString()); + + if (tempData == null) + { + d = new GetMacResponData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new GetMacResponData { macAddrData = tempData }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + + Actions += action; + var jObject = new JObject { { "Cluster_ID", 64512 }, { "Command", 13 } }; + Send(("ZbGw/GetMac"), jObject.ToString()); + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new GetMacResponData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + return d; + }); + } + #endregion + + #region 淇敼缃戝叧鍚嶇О + /// <summary> + /// 淇敼缃戝叧鍚嶇О + ///<para>gwName锛氱綉鍏冲悕绉�</para> + /// </summary> + public async System.Threading.Tasks.Task<GwReNameAllData> GwReNameAsync(string gwName) + { + return await System.Threading.Tasks.Task.Run(async () => + { + GwReNameAllData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new GwReNameAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GwReNameAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "GwReName_Respon") + { + var gwRename = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwReNameData>(jobject["Data"].ToString()); + + if (gwRename == null) + { + d = new GwReNameAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new GwReNameAllData { gwReNameData = gwRename }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("GwReName_Actions 鍚姩" + System.DateTime.Now.ToString()); + try + { + var bytes = new byte[32]; + var reamarkGwBytes = System.Text.Encoding.UTF8.GetBytes(gwName); + System.Array.Copy(reamarkGwBytes, 0, bytes, 0, 32 < reamarkGwBytes.Length ? 32 : reamarkGwBytes.Length); + gwName = System.Text.Encoding.UTF8.GetString(bytes); + + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 91 } }; + var data = new JObject { { "GwName", gwName } }; + jObject.Add("Data", data); + Send("GwReName", jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new GwReNameAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("GwReName_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 璁惧畾缃戝叧浣忓畢id + /// <summary> + /// 璁惧畾缃戝叧浣忓畢id + /// <para>homeId:浣忓畢id</para> + /// </summary> + public async System.Threading.Tasks.Task<GwSetHomeIdAllData> GwSetHomeIdAsync(string homeId) + { + return await System.Threading.Tasks.Task.Run(async () => + { + GwSetHomeIdAllData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new GwSetHomeIdAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GwSetHomeIdAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "GwSetHomeId_Respon") + { + var gwSetHomeId = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwSetHomeIdData>(jobject["Data"].ToString()); + if (gwSetHomeId == null) + { + d = new GwSetHomeIdAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new GwSetHomeIdAllData { gwSetHomeIdData = gwSetHomeId }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("GwReName_Actions 鍚姩" + System.DateTime.Now.ToString()); + try + { + //璐﹀彿ID + string accountId = string.Empty; + if (homeId != string.Empty) + { + if (Shared.Phone.UserCenter.UserCenterResourse.UserInfo.AuthorityNo == 1) + { + //涓昏处鍙� + accountId = Config.Instance.Guid; + } + else + { + accountId = Config.Instance.Home.MainUserDistributedMark; + } + } + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } }; + var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } }; + jObject.Add("Data", data); + //浣忓畢ID鐨勮缃�,鍥哄畾浣跨敤灞�鍩熺綉,涓嶅瓨鍦ㄨ繙绋嬬殑璇存硶 + SendLocation("GwSetHomeId", System.Text.Encoding.UTF8.GetBytes(jObject.ToString())); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new GwSetHomeIdAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + + Actions -= action; + DebugPrintLog("GwReName_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 鍏佽璁惧鍏ョ綉 + ///<summary > + /// 鎼滅储鏂板叆缃戠殑璁惧锛堝厑璁歌澶囧叆缃戯級 + /// <para>Time:0-255,0:鍏抽棴鎼滅储,255:涓�鐩村紑鍚�</para> + /// </summary> + public async void AddNewDeviceToGateway(int time = 3) + { + await System.Threading.Tasks.Task.Run(async () => + { + Action<string, string> action1 = (topic, message) => { }; + Actions += action1; + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 94 } }; + var data = new JObject { { "Time", time } }; + jObject.Add("Data", data); + Send(("SearchNewDevice"), jObject.ToString()); + + Actions -= action1; + }); + } + #endregion + + #region 鍗忚皟鍣ㄦ仮澶嶅嚭鍘傝缃� + ///<summary > + ///zigbee鍗忚皟鍣ㄦ仮澶嶅嚭鍘傝缃� + /// <para>DelAllInfo:0/1</para> + ///<para> 0:浠呭皢鍗忚皟鍣ㄦ仮澶嶅嚭鍘傝缃紝涓嶅垹闄ょ綉鍏充繚瀛樼殑璁惧鍒楄〃锛岀粍鍒楄〃锛屽満鏅垪琛ㄧ瓑淇℃伅銆�</para> + ///<para>1锛氬皢鍗忚皟鍣ㄦ仮澶嶅嚭鍘傝缃紝骞跺垹闄ょ綉鍏充繚瀛樼殑璁惧鍒楄〃锛岀粍鍒楄〃锛屽満鏅垪琛ㄧ瓑淇℃伅銆�</para> + /// </summary> + public void GwOperationReset(int delAllInfo) + { + Action<string, string> action = (topic, message) => { }; + Actions += action; + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 160 } }; + var data = new JObject { { "DelAllInfo", delAllInfo } }; + jObject.Add("Data", data); + Send(("ZbGwOperation/Reset"), jObject.ToString()); + } + catch { } + + Actions -= action; + } + #endregion + + #region 缃戝叧鎭㈠鍑哄巶璁剧疆 + ///<summary > + ///缃戝叧鎭㈠鍑哄巶璁剧疆 + /// <para>璇ユ寚浠ょ敤浜庣綉鍏砽inux绯荤粺鎭㈠鍑哄巶璁剧疆銆傛仮澶嶅嚭鍘傝缃悗锛岀郴缁熷皢鑷姩閲嶅惎</para> + /// <para>0锛氬懡浠ゅ凡鎺ユ敹锛岀郴缁熷嵆灏嗘仮澶嶅嚭鍘傚苟閲嶅惎銆�</para> + /// </summary> + public async System.Threading.Tasks.Task<GwLinuxResetResponData> GwLinuxResetAsync() + { + return await System.Threading.Tasks.Task.Run(async () => + { + GwLinuxResetResponData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new GwLinuxResetResponData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GwLinuxResetResponData { errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "GwLinuxReset_Respon") + { + var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"].ToString()); + + if (result == null) + { + d = new GwLinuxResetResponData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new GwLinuxResetResponData { Result = result }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("GwLinuxReset Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 84 } }; + Send("GwLinuxReset", jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new GwLinuxResetResponData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("GwLinuxReset Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 閲嶅惎缃戝叧绯荤粺 + ///<summary > + ///閲嶅惎缃戝叧绯荤粺 + /// <para>鍙戦�佽鎸囦护灏嗕娇缃戝叧涓诲姩鏂紑鎵�鏈塵qtt杩炴帴骞舵墽琛岄噸鍚�傞噸鍚椂闂村ぇ绾﹂渶瑕�60绉�</para> + /// <para>杩斿洖鍊兼槸0:鍛戒护宸叉帴鏀讹紝绯荤粺鍗冲皢閲嶅惎銆�</para> + /// </summary> + public async System.Threading.Tasks.Task<GwRebootResponAllData> GwRebootAsync() + { + return await System.Threading.Tasks.Task.Run(async () => + { + GwRebootResponAllData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new GwRebootResponAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GwRebootResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "GwReboot_Respon") + { + var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"].ToString()); + + if (result == null) + { + d = new GwRebootResponAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new GwRebootResponAllData { Result = result }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("GwReboot Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 83 } }; + Send("GwReboot", jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new GwRebootResponAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("GwReboot Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 缃戝叧鍜屽崗璋冨櫒鍗囩骇 + ///<summary > + ///淇濆瓨zigbee鍗忚皟鍣ㄧ粍缃戜俊鎭� + /// </summary> + public async System.Threading.Tasks.Task<SaveNVFileResponseAllData> SaveNVFile(string imageName, string imagePath) + { + return await System.Threading.Tasks.Task.Run(async () => + { + SaveNVFileResponseAllData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new SaveNVFileResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new SaveNVFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbGwOperation/SaveNVFile_Respon") + { + var zbGwOperationSaveNVFileData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.SaveNVFileResponseData>(jobject["Data"].ToString()); + + if (zbGwOperationSaveNVFileData == null) + { + d = new SaveNVFileResponseAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new SaveNVFileResponseAllData { saveNVFileResponseData = zbGwOperationSaveNVFileData }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("ZbGwOperation/SaveNVFile Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 500 } }; + var data = new JObject { { "ImageName", imageName }, { "ImagePath", imagePath } }; + jObject.Add("Data", data); + Send(("ZbGwOperation/SaveNVFile"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new SaveNVFileResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("ZbGwOperation/SaveNVFile Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 鍗忚皟鍣ㄦ仮澶嶇粍缃戜俊鎭� + ///<summary > + ///鍗忚皟鍣ㄦ仮澶嶇粍缃戜俊鎭� + /// </summary> + public async System.Threading.Tasks.Task<RestoreNVAllDtta> RestoreNV(string imageName, string imagePath) + { + return await System.Threading.Tasks.Task.Run(async () => + { + RestoreNVAllDtta d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new RestoreNVAllDtta { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new RestoreNVAllDtta { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + + if (topic == gatewayID + "/" + "ZbGwOperation/RestoreNV_Respon") + { + var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.RestoreNVDtta>(jobject["Data"].ToString()); + + if (tempData == null) + { + d = new RestoreNVAllDtta { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new RestoreNVAllDtta { restoreNVDtta = tempData }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + + } + } + }; + Actions += action; + DebugPrintLog("ZbGwOperation/RestoreNV Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 501 } }; + var data = new JObject { { "ImageName", imageName }, { "ImagePath", imagePath } }; + jObject.Add("Data", data); + Send(("ZbGwOperation/RestoreNV"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new RestoreNVAllDtta { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("ZbGwOperation/RestoreNV Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 鑾峰彇鍗忚皟鍣ㄥ綋鍓嶄俊閬�. + ///<summary > + /// 鑾峰彇鍗忚皟鍣ㄥ綋鍓嶄俊閬� + /// </summary> + public async System.Threading.Tasks.Task<GwGetChannelResponData> GetChannelAsync() + { + return await System.Threading.Tasks.Task.Run(async () => + { + GwGetChannelResponData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + if (temp == null) + { + d = new GwGetChannelResponData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new GwGetChannelResponData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbGw/GetChannel_Respon") + { + var channel = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Channel"].ToString()); + d = new GwGetChannelResponData { channel = channel }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + }; + + Actions += action; + DebugPrintLog("ZbGw/GetChannel Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 64512 }, { "Command", 8 } }; + Send(("ZbGw/GetChannel"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new GwGetChannelResponData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("ZbGw/GetChannel Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return d; + }); + } + #endregion + + #region 鏇存敼鍗忚皟鍣ㄥ綋鍓嶄俊閬� + ///<summary > + /// 鏇存敼鍗忚皟鍣ㄥ綋鍓嶄俊閬� + /// <para>Channel:瑕佹洿鏀圭殑淇¢亾: 11 -26</para> + /// </summary> + public async System.Threading.Tasks.Task<ChangeChannelResponAllData> ChangeChannelAsync(int channel) + { + return await System.Threading.Tasks.Task.Run(async () => + { + ChangeChannelResponAllData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new ChangeChannelResponAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new ChangeChannelResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbGw/ChangeChannel_Respon") + { + var tempInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ChangeChannelResponData>(jobject["Data"].ToString()); + + if (tempInfo == null) + { + d = new ChangeChannelResponAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new ChangeChannelResponAllData { changeChannelResponData = tempInfo }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + + } + } + }; + + Actions += action; + try + { + var jObject = new JObject { { "Cluster_ID", 64512 }, { "Command", 9 } }; + var data = new JObject { { "Channel", channel } }; + jObject.Add("Data", data); + Send(("ZbGw/ChangeChannel"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new ChangeChannelResponAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + return d; + }); + } + #endregion + + #region 鏁版嵁閫忎紶1锛堟暟鎹槸鍗佸叚杩涘埗褰㈠紡鐨勫瓧绗︿覆锛� + ///<summary > + ///瀹㈡埛绔悜鑺傜偣璁惧閫忎紶鏁版嵁锛岋紙鏁版嵁鏄崄鍏繘鍒跺舰寮忕殑瀛楃涓诧級 + /// <para>deviceAddr:璁惧鐨刴ac鍦板潃</para> + /// <para>devicePoint:璁惧绔彛鍙�</para> + /// <para>PassData:閫忎紶鐨勬暟鎹紝鏈�澶�256涓瓧绗︼紝涔熷氨鏄�忎紶128涓瓧鑺�</para> + /// </summary> + public async void ClientDataPassthrough(string deviceAddr, int devicePoint, string passData) + { + await System.Threading.Tasks.Task.Run(async () => + { + Action<string, string> action = (topic, message) => { }; + Actions += action; + try + { + var jObject = new JObject { { "DeviceAddr", deviceAddr }, { "Epoint", devicePoint }, { "Cluster_ID", 64513 }, { "Command", 0 } }; + Send(("ClientDataPassthrough"), jObject.ToString()); + } + catch { } + Actions -= action; + }); + } + + #region 鏁版嵁閫忎紶2锛堟暟鎹槸浜岃繘鍒舵祦锛� + ///<summary > + /// 瀹㈡埛绔彂閫佹枃浠舵祦鍒扮綉鍏筹紙鏁版嵁鏄簩杩涘埗娴侊級 + ///<para> passData: 閫忎紶鏁版嵁</para> + ///<para>Result 0: 鏁版嵁鍐欏叆鎴愬姛,璇锋眰鍙戦�佷笅涓�涓暟鎹寘</para> + ///<para>Result1锛氭暟鎹啓鍏ュけ璐�</para> + ///<para>Result2锛氭暟鎹В鏋愰敊璇�</para> + ///<para>Result3锛氬彂閫佹暟鎹ぇ灏忚秴鍑洪檺鍒�</para> + /// </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); + + Panel.PanelSwitchLevelInfo result = null; + + if (myDevice.Gateway == null) + { + result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "褰撳墠娌℃湁缃戝叧" }; + return result; + } + return await System.Threading.Tasks.Task.Run(async () => + { + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + + else + { + result = new Panel.PanelSwitchLevelInfo { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbDataPassthrough") + { + var clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString()); + + if (clientDataPassthroughResponseData == null) + { + result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + if (clientDataPassthroughResponseData?.PassData != null) + { + var data = clientDataPassthroughResponseData.PassData; + if (data.Length == 14) + { + var command = data[4].ToString() + data[5].ToString() + data[2].ToString() + data[3].ToString(); + if (command == "0407") + { + var level1 = Convert.ToInt32(data[10].ToString() + data[11].ToString(), 16); + var level2 = Convert.ToInt32(data[12].ToString() + data[13].ToString(), 16); + result = new Panel.PanelSwitchLevelInfo { panelDirectionsLevel = level1, panelBacklightLevel = level2 }; + System.Console.WriteLine($"UI鏀跺埌閫氱煡鍚庣殑涓婚_command:0406_{ topic}"); + } + } + } + } + } + }; + + myDevice.Gateway.Actions += action; + System.Console.WriteLine("ClientDataPassthrough_Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var sendDataBytes = new byte[12 + dataLength]; + sendDataBytes[0] = 0xfe; + //璁惧绔偣锛�1涓猙ytes + sendDataBytes[1] = Convert.ToByte(devicePoint); + //璁惧mac鍦板潃锛屽皬绔粨鏋�,8涓猙ytes + //var addrAllBytes = new byte[8]; + int j = 0; + for (int i = 14; i >= 0; i = i - 2) + { + var curByte = deviceAddr.Substring(i, 2); //00 0d 6f ff fe 04 51 52 + + sendDataBytes[2 + j] = Convert.ToByte(string.Format("0x{0}", curByte), 16); + j++; + } + //鏁版嵁闀垮害锛�1涓猙ytes + sendDataBytes[10] = Convert.ToByte(dataLength % 256); // DataLen 0x01 鍒� 0x800 锛堝嵆姣忔鏈�澶у彂閫�2048瀛楄妭锛�2 + sendDataBytes[11] = Convert.ToByte(dataLength / 256); + //閫忎紶鏁版嵁 + System.Array.Copy(passData, 0, sendDataBytes, 12, dataLength); + await Send("ClientDataPassthrough", sendDataBytes); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (result != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + result = new Panel.PanelSwitchLevelInfo { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + myDevice.Gateway.Actions -= action; + System.Console.WriteLine("ClientDataPassthrough_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return result; + }); + } + #endregion + + #endregion + + #region 鍚敤鎴栧叧闂�忎紶鏁版嵁涓婁紶鎺ュ彛 + /// <summary> + /// 鍚敤鎴栧叧闂�忎紶鏁版嵁涓婁紶鎺ュ彛 + /// </summary> + /// <returns>The scene new identifier async.</returns> + /// <param name="gateway">Gateway.</param> + /// <param name="IsOn">0锛氬叧闂�忎紶鏁版嵁涓婁紶 ;1锛氬紑鍚�忎紶鏁版嵁涓婁紶</param> + public async System.Threading.Tasks.Task<PassthroughAllData> GetSceneNewIdAsync(int IsOn) + { + return await System.Threading.Tasks.Task.Run(async () => + { + PassthroughAllData d = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new PassthroughAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + d = new PassthroughAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbDataPassthrough") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(jobject["Data"].ToString()); + + d = new PassthroughAllData { passData = temp }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + }; + Actions += action; + DebugPrintLog("ZbDataPassthrough_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 64513 }, { "Command", 1 } }; + Send("GetZbGwVersion", jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new PassthroughAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("GetGwVersionData_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 缃戝叧鍗囩骇 + /// <summary> + /// 缃戝叧鍗囩骇 + /// </summary> + /// <returns>The upgrade async.</returns> + /// <param name="imageName">Image name:(鍗囩骇鍥轰欢鍚嶇О锛屽悕绉颁腑瑕佸甫鏈夆�淟INUXMODULE鈥濇爣璇嗭紝鍚﹀垯灏嗕笉浼氬崌绾с�傛渶澶�128瀛楄妭</param> + public async System.Threading.Tasks.Task<LinuxUpgradeAllData> LinuxUpgradeAsync(string imageName) + { + return await System.Threading.Tasks.Task.Run(async () => + { + LinuxUpgradeAllData d = null; + + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new LinuxUpgradeAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + + else + { + d = new LinuxUpgradeAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbGwOperation/LinuxUpgrade_Respon") + { + var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString()); + d = new LinuxUpgradeAllData { Result = result }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + }; + Actions += action; + DebugPrintLog("ZbGwOperation/LinuxUpgrade_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 503 } }; + var data = new JObject { + { "IsForce", 0}, + { "SaveChange", 1}, + { "ImageName", imageName}, + { "ImagePath", "/tmp"} + }; + jObject.Add("Data", data); + Send(("ZbGwOperation/LinuxUpgrade"), jObject.ToString()); + } + catch { } + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000) + { + d = new LinuxUpgradeAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("ZbGwOperation/LinuxUpgrade_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 鍗忚皟鍣ㄥ崌绾� + /// <summary> + /// 鍗忚皟鍣ㄥ崌绾� + /// </summary> + /// <returns>The NVA sync.</returns> + /// <param name="imageName">Image name:(鍗囩骇闀滃儚鍚嶇О锛屽悕绉颁腑瑕佸甫鏈夆�淶BMODULE鈥濇爣璇嗭紝鍚﹀垯涓嶅厑璁稿崌绾с�傛渶澶�128瀛楄妭銆�)</param> + public async System.Threading.Tasks.Task<ZbGwOperationUpgradeAllData> UpgradeNVAsync(string imageName) + { + return await System.Threading.Tasks.Task.Run(async () => + { + ZbGwOperationUpgradeAllData d = null; ; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new ZbGwOperationUpgradeAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + + else + { + d = new ZbGwOperationUpgradeAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon") + { + zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ZbGwOperationUpgradeData>(jobject["Data"].ToString()); + + if (zbGwOperationUpgradeData == null) + { + d = new ZbGwOperationUpgradeAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new ZbGwOperationUpgradeAllData { bGwOperationUpgradeData = zbGwOperationUpgradeData }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("ZbGwOperation/Upgrade_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 502 } }; + var data = new JObject { { "ImageName", imageName }, { "ImagePath", "/tmp" } }; + jObject.Add("Data", data); + Send(("ZbGwOperation/Upgrade"), jObject.ToString()); + } + catch + { } + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000) + { + d = new ZbGwOperationUpgradeAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + + } + Actions -= action; + DebugPrintLog("ZbGwOperation/Upgrade_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 涓嬭浇浜戠鍥轰欢. + /// <summary> + /// 涓嬭浇浜戠缃戝叧鎴栧崗璋冨櫒鍥轰欢. + /// </summary> + /// <returns>The file async.</returns> + /// <param name="distributedMark">Distributed mark:鍥轰欢鍞竴鏍囪瘑</param> + /// <param name="imageName">Image name:鍥轰欢鐗堟湰</param> + public async System.Threading.Tasks.Task<CommonDevice.DownloadFileResponAllData> DownloadFileAsync(string distributedMark, string imageName) + { + return await System.Threading.Tasks.Task.Run(async () => + { + CommonDevice.DownloadFileResponAllData d = null; ; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + + else + { + d = new CommonDevice.DownloadFileResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "DownloadFile_Respon") + { + var downloadFileResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DownloadFileResponData>(jobject["Data"].ToString()); + + if (downloadFileResponData == null) + { + d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new CommonDevice.DownloadFileResponAllData { downloadFileResponData = downloadFileResponData }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("DownloadFile_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 6000 } }; + var data = new JObject { + { "DistributeMark", distributedMark}, + { "DownloadPath", "/tmp" }, + { "FileName", imageName } + }; + jObject.Add("Data", data); + Send(("DownloadFile"), jObject.ToString()); + } + catch { } + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000) + { + d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + + } + Actions -= action; + DebugPrintLog("DownloadFile_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + #endregion + + #region 鏌ョ湅缃戝叧璁板綍鐨勮櫄鎷熼┍鍔�. + /// <summary> + /// 鏌ョ湅缃戝叧璁板綍鐨勮櫄鎷熼┍鍔� + /// </summary> + public async System.Threading.Tasks.Task<CheckVDDriveCodeResponseAllData> CheckVDDriveCodeAsync() + { + return await System.Threading.Tasks.Task.Run(async () => + { + CheckVDDriveCodeResponseAllData d = null; ; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new CheckVDDriveCodeResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + + else + { + d = new CheckVDDriveCodeResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "VirtualDrive/CatDriveCode_Respon") + { + var vDriveDriveCodeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VDriveDriveCodeResponData>(jobject["Data"].ToString()); + + if (vDriveDriveCodeResponData == null) + { + d = new CheckVDDriveCodeResponseAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new CheckVDDriveCodeResponseAllData { vDriveDriveCodeResponData = vDriveDriveCodeResponData }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + } + }; + Actions += action; + DebugPrintLog("VirtualDriveDriveCode_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 505 } }; + Send(("VirtualDrive/CatDriveCode"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + d = new CheckVDDriveCodeResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("VirtualDriveDriveCode_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + + #endregion + + #region 鍗囩骇铏氭嫙椹卞姩璁惧. + /// <summary> + /// 鍗囩骇铏氭嫙椹卞姩璁惧 + /// <para>oTAImageName:鍗囩骇闀滃儚鍚嶇О</para> + /// <para>driveCode:椹卞姩浠e彿</para> + /// </summary> + public async System.Threading.Tasks.Task<VirtualDriveUpgradeResponseAllData> VirtualDriveUpgradeAsync(string imageName, int driveCode) + { + return await System.Threading.Tasks.Task.Run(async () => + { + VirtualDriveUpgradeResponseAllData d = null; ; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + + else + { + d = new VirtualDriveUpgradeResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon") + { + virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString()); + + if (virtualDriveUpgradeResponData == null) + { + d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = "缃戝叧杩斿洖鐨勬暟鎹负绌�" }; + } + else + { + d = new VirtualDriveUpgradeResponseAllData { virtualDriveUpgradeResponData = virtualDriveUpgradeResponData }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{topic}"); + } + } + }; + Actions += action; + DebugPrintLog("VirtualDrive/Upgrade_Actions 鍚姩" + "_" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 504 } }; + var data = new JObject { { "ImageName", imageName }, { "ImagePath", "/tmp" }, { "DriveCode", driveCode } }; + jObject.Add("Data", data); + Send(("VirtualDrive/Upgrade"), jObject.ToString()); + } + catch { } + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < 30 * 1000) + { + await System.Threading.Tasks.Task.Delay(10); + if (d != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000) + { + d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + } + Actions -= action; + DebugPrintLog("VirtualDrive/Upgrade_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + + return d; + }); + } + + #endregion + + #region 瀹㈡埛绔笂浼犳枃浠跺埌缃戝叧. + /// <summary> + /// 瀹㈡埛绔笂浼犳枃浠跺埌缃戝叧 + /// </summary> + /// <returns>The admin password async.</returns> + /// <param name="fileName">涓婁紶鏂囦欢鍚庯紝淇濆瓨鐨勬枃浠跺悕绉�</param> + /// <param name="filePath">鏂囦欢淇濆瓨鍦ㄧ郴缁熺殑鐩綍璺緞锛屽鏋滅洰褰曚笉瀛樺湪绯荤粺灏嗚嚜鍔ㄥ垱寤鸿鐩綍銆傚锛�/tmp/. </param> + public async System.Threading.Tasks.Task<CreateFileResponseAllData> CreateFileAsync(string fileName, string filePath = "/etc/hdlDat") + { + return await System.Threading.Tasks.Task.Run(async () => + { + CreateFileResponseAllData dataRes = null; + + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + dataRes = new CreateFileResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + dataRes = new CreateFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "FileTransfer/CreateFile_Respon") + { + var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString()); + dataRes = new CreateFileResponseAllData { Result = result }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + }; + Actions += action; + DebugPrintLog("FileTransfer/CreateFile_Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3000 } }; + var data = new JObject { { "FileName", fileName }, { "FilePath", filePath } }; + jObject.Add("Data", data); + Send(("FileTransfer/CreateFile"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (dataRes != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + dataRes = new CreateFileResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + }; + + Actions -= action; + DebugPrintLog("FileTransfer/CreateFile_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return dataRes; + }); + } + #endregion + + #region 瀹㈡埛绔彂閫佹枃浠舵祦鍒扮綉鍏� + ///<summary > + /// 瀹㈡埛绔彂閫佹枃浠舵祦鍒扮綉鍏� + ///<para>Result 0: 鏁版嵁鍐欏叆鎴愬姛,璇锋眰鍙戦�佷笅涓�涓暟鎹寘</para> + ///<para>Result1锛氭暟鎹啓鍏ュけ璐�</para> + ///<para>Result2锛氭暟鎹В鏋愰敊璇�</para> + ///<para>Result3锛氬彂閫佹暟鎹ぇ灏忚秴鍑洪檺鍒�</para> + /// </summary> + public async System.Threading.Tasks.Task<SendFileResponseAllData> SendFileAsync(byte[] data) + { + if (data == null) + { + return new SendFileResponseAllData { errorMessageBase = "鏁版嵁鍐呭鏄┖" }; + } + return await System.Threading.Tasks.Task.Run(async () => + { + var isRespond = true; + SendFileResponseAllData dataRes = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/FileTransfer/SendFile_Respon") + { + var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString()); + dataRes = new SendFileResponseAllData { Result = result }; + if (result == 0) + { + isRespond = true; + } + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + }; + Actions += action; + DebugPrintLog("FileTransfer/SendFile_Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var fileBytes = data; + var size = 2048; + var dateTime = DateTime.Now; + for (int i = 0, tempSize = 0; i < fileBytes.Length; i += tempSize) + { + while (!isRespond) + { + if (WaitReceiveDataTime < (DateTime.Now - dateTime).TotalMilliseconds) + { + return new SendFileResponseAllData { errorMessageBase = "鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; ; + } + await System.Threading.Tasks.Task.Delay(10); + } + isRespond = false; + + byte finish = 0; + if (i + size < fileBytes.Length) + { + tempSize = size; + } + else if (i + size == fileBytes.Length) + { + tempSize = size; + finish = 1; + } + else + { + tempSize = fileBytes.Length % size; + finish = 1; + } + var bytes = new byte[8 + tempSize]; + bytes[0] = 0xfe; + bytes[1] = 0; + bytes[2] = 0; + bytes[3] = 0; + bytes[4] = 0; + bytes[5] = finish;//0x00 鎴� 0x01 + bytes[6] = Convert.ToByte(tempSize % 256); // DataLen 0x01 鍒� 0x800 锛堝嵆姣忔鏈�澶у彂閫�2048瀛楄妭锛�2 + bytes[7] = Convert.ToByte(tempSize / 256); + System.Array.Copy(fileBytes, i, bytes, 8, tempSize); + dateTime = DateTime.Now; + await Send("FileTransfer/SendFile", bytes); + DebugPrintLog($"涓婁紶鍒扮綉鍏冲綋鍓嶆暟鎹暟閲廮{i}_鏄笉鏄渶鍚庝竴涓猒{finish}_{System.DateTime.Now.ToString()}"); + } + } + catch { } + finally + { + Actions -= action; + } + DebugPrintLog("Security/ChangeAdminPassword_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return dataRes; + }); + } + #endregion + + #region 鏌ョ湅缃戝叧鐩綍鏂囦欢淇℃伅. + /// <summary> + /// 鏌ョ湅缃戝叧鐩綍鏂囦欢淇℃伅 + /// </summary> + /// <returns>The admin password async.</returns> + /// <param name="filePath">鏂囦欢淇濆瓨鍦ㄧ郴缁熺殑鐩綍璺緞锛屽鏋滅洰褰曚笉瀛樺湪绯荤粺灏嗚嚜鍔ㄥ垱寤鸿鐩綍銆傚锛�/tmp/. </param> + public async System.Threading.Tasks.Task<FileTransferLsDiResponseAllData> FileTransferLsDirAsync(string filePath = "/etc/hdlDat") + { + return await System.Threading.Tasks.Task.Run(async () => + { + FileTransferLsDiResponseAllData dataRes = null; + + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + dataRes = new FileTransferLsDiResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + dataRes = new FileTransferLsDiResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "FileTransfer/lsDir_Respon") + { + var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject<FileTransferLsDiResponseData>(jobject["Data"].ToString()); + if (resultlsDir != null) + { + dataRes = new FileTransferLsDiResponseAllData { fileTransferLsDiResponseData = resultlsDir }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + else + { + dataRes = new FileTransferLsDiResponseAllData { errorMessageBase = "鏀跺埌鐨勭綉鍏宠繑鍥炴暟鎹槸绌�" }; + } + } + }; + Actions += action; + DebugPrintLog("FileTransfer/lsDir_Actions 鍚姩" + System.DateTime.Now.ToString()); + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3002 } }; + var data = new JObject { { "FilePath", filePath } }; + jObject.Add("Data", data); + Send(("FileTransfer/lsDir"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (dataRes != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + dataRes = new FileTransferLsDiResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + }; + Actions -= action; + DebugPrintLog("FileTransfer/lsDir_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return dataRes; + }); + } + #endregion + + #region 鏌ョ湅鍗曚釜鏂囦欢淇℃伅. + /// <summary> + /// 鏌ョ湅鍗曚釜鏂囦欢淇℃伅 + /// </summary> + /// <returns>The admin password async.</returns> + /// <param name="filePath">鏂囦欢淇濆瓨鍦ㄧ郴缁熺殑鐩綍璺緞锛屽鏋滅洰褰曚笉瀛樺湪绯荤粺灏嗚嚜鍔ㄥ垱寤鸿鐩綍銆傚锛�/tmp/. </param> + public async System.Threading.Tasks.Task<FileTransferGetFileInfoResponseAllData> GetCurrentFileInfoAsync(string fileName, string filePath = "/etc/hdlDat/") + { + return await System.Threading.Tasks.Task.Run(async () => + { + FileTransferGetFileInfoResponseAllData dataRes = null; + + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + dataRes = new FileTransferGetFileInfoResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + dataRes = new FileTransferGetFileInfoResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "FileTransfer/GetFileInfo_Respon") + { + var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject<FileTransferGetFileInfoResponseData>(jobject["Data"].ToString()); + if (resultlsDir != null) + { + dataRes = new FileTransferGetFileInfoResponseAllData { fileTransferGetFileInfoResponseData = resultlsDir }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + else + { + dataRes = new FileTransferGetFileInfoResponseAllData { errorMessageBase = "鏀跺埌鐨勭綉鍏宠繑鍥炴暟鎹槸绌�" }; + } + } + }; + Actions += action; + DebugPrintLog("FileTransfer/GetFileInfo_Actions 鍚姩" + System.DateTime.Now.ToString()); + try + { + var tempFilePath = filePath + fileName; + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3007 } }; + var data = new JObject { { "File", tempFilePath } }; + jObject.Add("Data", data); + Send(("FileTransfer/GetFileInfo"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (dataRes != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + dataRes = new FileTransferGetFileInfoResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + }; + Actions -= action; + DebugPrintLog("FileTransfer/GetFileInfo_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return dataRes; + }); + } + #endregion + + #region 瀹㈡埛绔瀹氳涓嬭浇鐨勬枃浠跺悕绉板拰璺緞 + /// <summary> + /// 瀹㈡埛绔瀹氳涓嬭浇鐨勬枃浠跺悕绉板拰璺緞 + /// <para>fileName:涓嬭浇鐨勬枃浠跺悕绉�.</para> + /// <para>blockStartAddress:鍙拷鐣ワ紝榛樿涓�0銆備笅杞藉紑濮嬪湴鍧�锛岀敤浜庢柇鐐圭画浼犮�傚锛氭枃浠舵�诲ぇ灏忎负1000Byte锛屽鎴风涓嬭浇浜�200Byte鍚庤繛鎺ユ剰澶栨柇寮�銆傚綋瀹㈡埛绔噸鏂拌繛鎺ュ悗鎯崇户缁笅杞藉悗缁枃浠舵祦鑰屼笉鎯充粠鏂囦欢澶撮噸鏂板紑濮嬩笅杞斤紝鍙皢璇ュ弬鏁拌缃负200锛岀綉鍏冲皢浠庣2001Byte寮�濮嬪彂閫佹枃浠舵祦銆�</para> + /// <para>filePath">鏂囦欢鎵�鍦ㄧ郴缁熺殑鐩綍璺緞銆傚锛�/tmp.</para> + /// </summary> + public async System.Threading.Tasks.Task<SetDownloadFileResponseAllData> SetDownloadFileAsync(string fileName, int blockStartAddress = 0, string filePath = "/etc/hdlDat") + { + return await System.Threading.Tasks.Task.Run(async () => + { + SetDownloadFileResponseAllData dataRes = null; + + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + dataRes = new SetDownloadFileResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + dataRes = new SetDownloadFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "FileTransfer/SetDownloadFile_Respon") + { + var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<SetDownloadFileResponseData>(jobject["Data"].ToString()); + if (tempData != null) + { + dataRes = new SetDownloadFileResponseAllData { }; + var tempDa = new SetDownloadFileResponseData(); + if (tempData.Result == 0) + { + this.byteSource.Clear(); + } + tempDa.Result = tempData.Result; + dataRes.setDownloadFileResponseData = tempDa; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + else + { + dataRes = new SetDownloadFileResponseAllData { errorMessageBase = "鏀跺埌鐨勭綉鍏宠繑鍥炴暟鎹槸绌�" }; + } + } + }; + Actions += action; + DebugPrintLog("FileTransfer/SetDownloadFile_Actions 鍚姩" + System.DateTime.Now.ToString()); + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3003 } }; + var data = new JObject { + { "FileName", fileName }, + { "FilePath", filePath }, + { "BlockStartAddress", blockStartAddress } + }; + jObject.Add("Data", data); + Send(("FileTransfer/SetDownloadFile"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (dataRes != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + dataRes = new SetDownloadFileResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + }; + Actions -= action; + DebugPrintLog("FileTransfer/SetDownloadFile_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return dataRes; + }); + } + #endregion + + #region 缃戝叧鍙戦�佹枃浠舵祦鍒板鎴风 + private List<byte> byteSource = new List<byte>(); + ///<summary > + /// 涓嬭浇鏂囦欢涓殑鏁版嵁 + /// </summary> + public void DownloadFileConfirmAsync(byte[] fileBytes) + { + int result = 0; + + if (fileBytes[5] != 1) + { + if (fileBytes.Length == 2056) + { + result = 0; + var tempBytes = new byte[2048]; + System.Array.Copy(fileBytes, 8, tempBytes, 0, 2048); + byteSource.AddRange(tempBytes); + } + else + { + var tempBytes = new byte[fileBytes.Length - 8]; + System.Array.Copy(fileBytes, 8, tempBytes, 0, tempBytes.Length); + byteSource.AddRange(tempBytes); + return; + } + } + else + { + var tempBytes = new byte[fileBytes.Length - 8]; + System.Array.Copy(fileBytes, 8, tempBytes, 0, tempBytes.Length); + byteSource.AddRange(tempBytes); + return; + } + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3004 } }; + var data = new JObject { { "Result", result } }; + jObject.Add("Data", data); + Send("FileTransfer/DownloadFile_Respon", jObject.ToString()); + } + catch { } + } + #endregion + + #region 鍒犻櫎鏂囦欢鎴栫洰褰� + /// <summary> + /// 鍒犻櫎鏂囦欢鎴栫洰褰� + /// </summary> + /// <returns>The admin password async.</returns> + /// <param name="path">鍒犻櫎鐩綍鎴栨枃浠剁殑璺緞銆傚锛�/tmp/锛屽垯鍒犻櫎tmp鐩綍銆�/tmp/aa.txt锛屽垯鍒犻櫎tmp鐩綍涓嬬殑aa.txt鏂囦欢銆� </param> + public async System.Threading.Tasks.Task<DelFileOrDirResponseAllData> DelFileOrDirAsync(string path = "/etc/hdlDat") + { + return await System.Threading.Tasks.Task.Run(async () => + { + DelFileOrDirResponseAllData dataRes = null; + + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + dataRes = new DelFileOrDirResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + dataRes = new DelFileOrDirResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "FileTransfer/DelFileOrDir_Respon") + { + var resultDelFileOrDir = Newtonsoft.Json.JsonConvert.DeserializeObject<DelFileOrDirResponseData>(jobject["Data"].ToString()); + if (resultDelFileOrDir != null) + { + dataRes = new DelFileOrDirResponseAllData { delFileOrDirResponseData = resultDelFileOrDir }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + else + { + dataRes = new DelFileOrDirResponseAllData { errorMessageBase = "鏀跺埌鐨勭綉鍏宠繑鍥炴暟鎹槸绌�" }; + } + } + }; + Actions += action; + DebugPrintLog("FileTransfer/DelFileOrDir_Actions 鍚姩" + System.DateTime.Now.ToString()); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3005 } }; + var data = new JObject { { "Path", path } }; + jObject.Add("Data", data); + Send(("FileTransfer/DelFileOrDir"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (dataRes != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + dataRes = new DelFileOrDirResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + }; + Actions -= action; + DebugPrintLog("FileTransfer/DelFileOrDir_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return dataRes; + }); + } + #endregion + + #region 鍒涘缓涓�涓洰褰�. + /// <summary> + /// 鍒涘缓涓�涓洰褰� + /// </summary> + /// <returns>The admin password async.</returns> + /// <param name="path">鍒犻櫎鐩綍鎴栨枃浠剁殑璺緞銆傚锛�/tmp/锛屽垯鍒犻櫎tmp鐩綍銆�/tmp/aa.txt锛屽垯鍒犻櫎tmp鐩綍涓嬬殑aa.txt鏂囦欢銆� </param> + public async System.Threading.Tasks.Task<CreateDirResponseAllData> CreateDirAsync(string path = "/etc/hdlDat") + { + return await System.Threading.Tasks.Task.Run(async () => + { + CreateDirResponseAllData dataRes = null; + + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + + if (topic == gatewayID + "/" + "Error_Respon") + { + var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString()); + + if (temp == null) + { + dataRes = new CreateDirResponseAllData { errorMessageBase = "缃戝叧閿欒鍥炲锛屼笖鏁版嵁鏄┖" }; + } + else + { + dataRes = new CreateDirResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) }; + } + } + + if (topic == gatewayID + "/" + "FileTransfer/CreateDir_Respon") + { + var resultCreateDir = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateDirResponseData>(jobject["Data"].ToString()); + if (resultCreateDir != null) + { + dataRes = new CreateDirResponseAllData { createDirResponseData = resultCreateDir }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + else + { + dataRes = new CreateDirResponseAllData { errorMessageBase = "鏀跺埌鐨勭綉鍏宠繑鍥炴暟鎹槸绌�" }; + } + } + }; + Actions += action; + DebugPrintLog("FileTransfer/CreateDir_Actions 鍚姩" + System.DateTime.Now.ToString()); + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 3006 } }; + var data = new JObject { { "Path", path } }; + jObject.Add("Data", data); + Send(("FileTransfer/CreateDir"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (dataRes != null) + { + break; + } + } + if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) + { + dataRes = new CreateDirResponseAllData { errorMessageBase = " 鍥炲瓒呮椂锛岃閲嶆柊鎿嶄綔" }; + }; + Actions -= action; + DebugPrintLog("FileTransfer/CreateDir_Actions 閫�鍑�" + System.DateTime.Now.ToString()); + return dataRes; + }); + } + #endregion + + #region 瀹㈡埛绔彂閫佸瘑閽ュ埌缃戝叧 + ///<summary > + /// 瀹㈡埛绔彂閫丏ES瀵嗛挜鍒扮綉鍏� + /// <para>DES瀵嗛挜缁廟SA鍏挜鍔犲瘑杞垚base64鍚庢墍寰楃殑瀛楃涓蹭俊鎭�</para> + /// </summary> + public async System.Threading.Tasks.Task<SendKeyResponData> SendAesKeyAsync(string aesKey) + { + return await System.Threading.Tasks.Task.Run(async () => + { + SendKeyResponData sendKeyResponData = null; + Action<string, string> action = (topic, message) => + { + var gatewayID = topic.Split('/')[0]; + + if (topic == gatewayID + "/" + "SendAESKey_Respon") + { + var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString()); + sendKeyResponData = new SendKeyResponData { Result = result }; + DebugPrintLog($"UI鏀跺埌閫氱煡鍚庣殑涓婚_{ topic}"); + } + }; + + Actions += action; + DebugPrintLog($"SendAESKey_Actions 鍚姩_{System.DateTime.Now.ToString()}"); + + try + { + var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 100 } }; + var data = new JObject { { "AesKey", aesKey } }; + jObject.Add("Data", data); + Send(("SendAESKey"), jObject.ToString()); + } + catch { } + + var dateTime = DateTime.Now; + while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) + { + await System.Threading.Tasks.Task.Delay(10); + if (sendKeyResponData != null) + { + break; + } + } + + Actions -= action; + DebugPrintLog($"SendAESKey_Actions 閫�鍑篲{System.DateTime.Now.ToString()}"); + return sendKeyResponData; + }); + } + + + #endregion + #endregion + + #region 璁惧鐘舵�佹洿鏂� + /// <summary> + /// 璁惧鐘舵�佺洃鍚垪琛� + /// <para>杩涘叆褰撳墠鐣岄潰鏃惰娣诲姞</para> + /// <para>閫�鍑哄綋鍓嶇晫闈㈡椂瑕佸叧闂�</para> + /// </summary> + public static readonly List<IStatus> StatusList = new List<IStatus>(); + + /// <summary> + /// 璁惧淇℃伅鍙樺寲 + /// <para>type锛氬鏋滀负 DeviceInComingRespon:璁惧鏂颁笂鎶�</para> + /// <para>type锛氬鏋滀负 IASInfoReport:RemoveDeviceRespon</para> + /// <para>type锛氬鏋滀负 DeviceStatusReport:璁惧涓婃姤</para> + /// <para>type锛氬鏋滀负 IASInfoReport:IAS瀹夐槻淇℃伅涓婃姤</para> + /// <para>type锛氬鏋滀负 OnlineStatusChange: 璁惧鍦ㄧ嚎鐘舵�佹洿鏂�</para> + /// </summary> + /// <param name="commonDevice">Common device.</param> + public static void UpdateDeviceInfo(CommonDevice commonDevice, string type) + { + if (commonDevice == null) + { + return; + } + for (int i = 0; i < StatusList.Count; i++) + { + StatusList[i].DeviceInfoChange(commonDevice, type); + } + } + #endregion + + #region 閫氳杩炴帴 + /// <summary> + /// 灞�鍩熺綉鐨凪QTT + /// </summary> + IMqttClient localMqttClient = new MqttFactory().CreateMqttClient(); + bool localMqttIsConnecting; + [Newtonsoft.Json.JsonIgnore] + 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) + { + //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� + localMqttIsConnecting = true; + + //(3)褰揫杩炴帴Mqtt鎴愬姛鍚嶿鎴栬�匸Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒版暟鎹寘鍝嶅簲鏃跺湪mqttClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 + if (localMqttClient.ApplicationMessageReceivedHandler == null) + { + localMqttClient.UseApplicationMessageReceivedHandler((e) => + { + if (!localMqttClient.IsConnected) + { + return; + } + mqttClient_MqttMsgPublishReceived(e); + }); + } + + if (localMqttClient.DisconnectedHandler == null) + { + localMqttClient.UseDisconnectedHandler(async (e) => + { + DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}"); + await DisConnectLocalMqttClient("StartLocalMqtt.DisconnectedHandler"); + //await StartLocalMqtt("ReConnect"); + }); + } + if (localMqttClient.ConnectedHandler == null) + { + localMqttClient.UseConnectedHandler(async (e) => + { + DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}"); + IsRemote = false; + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + Shared.Phone.UserCenter.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); + } + } + } + catch (Exception ex) + { + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父:\r\n" + ex.Message); + } + DebugPrintLog($"灞�鍩熺綉閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); + } + finally + { + localMqttIsConnecting = false; + } + }); + } + + /// <summary> + /// 褰撳墠鏈夊笎鍙蜂笅鎵�鏈夌殑缃戝叧鍒楄〃鍙婁俊鎭� + /// </summary> + public static Dictionary<string, Shared.Phone.UserCenter.GatewayResult> GateWayBaseInfomations = new Dictionary<string, Shared.Phone.UserCenter.GatewayResult> { }; + /// <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 resultData = Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, new List<string> { "NotCheck" }); + 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 = 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 Shared.Phone.UserCenter.GatewayResult { 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.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; + } + } + } + } + }); + } + #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 = 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 = 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) + { + try + { + if (localIsConnected) + { + localIsConnected = false; + DebugPrintLog($"Local涓诲姩鏂紑_{s}"); + //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await localMqttClient.DisconnectAsync(); + } + } + catch (Exception ex) + { + DebugPrintLog($"Local鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); + } + } + + /// <summary> + /// 鏂紑杩滅▼Mqtt鐨勯摼鎺� + /// </summary> + public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s = "") + { + 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 + + #region 鏁版嵁鍙戦�� + + /// <summary> + /// 鍙戦�佹秷鎭埌鏈嶅姟鍣� + /// </summary> + /// <returns>The send.</returns> + /// <param name="topic">Topic.</param> + /// <param name="cluster_ID">Cluster identifier.</param> + /// <param name="commnand">Commnand.</param> + /// <param name="message">Message.</param> + public void Send(string topic, Cluster_ID cluster_ID, Command commnand, Newtonsoft.Json.Linq.JObject message = null) + { + var jObject = new Newtonsoft.Json.Linq.JObject() { + { + "Cluster_ID", (int)cluster_ID }, + { + "Command", (int)commnand } + }; + if (message != null) + { + jObject.Add("Data", message); + } + Send(topic, System.Text.Encoding.UTF8.GetBytes(jObject.ToString())); + } + + /// <summary> + /// 杩滅▼鍙戦�佹暟鎹牸寮� + /// </summary> + async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false) + { + try + { + if (this.GwId == string.Empty || !GateWayBaseInfomations.ContainsKey(this.GwId)) + { + return; + } + var gateWayBaseInfomation = GateWayBaseInfomations[this.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 + { + } + } + + /// <summary> + /// 鍙戦�佹秷鎭埌鏈嶅姟鍣� + /// </summary> + /// <returns></returns> + /// <param name="topic"></param> + /// <param name="message"></param> + /// <param name="retain"></param> + public async System.Threading.Tasks.Task Send(string topic, byte[] message, bool retain = false) + { + try + { + if (Shared.Common.Config.Instance.HomeId == "") + { + return; + } + + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + string text = "杩滅▼鍙戦��:"; + if (IsRemote == false) { text = "鏈湴鍙戦��:"; } + text += topic + "\r\n"; + text += Encoding.UTF8.GetString(message) + "\r\n"; + Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text); + } + + if (IsRemote) + { + await SendRemoteMsg(topic, message, retain); + DebugPrintLog($"杩滅▼鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + } + else + { + 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 }); + } + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父鏂紑"); + } + } + } + } + } + catch (Exception ex) + { + DebugPrintLog($"Send:{ex.Message}"); + } + } + + /// <summary> + /// 鍙戦�佹秷鎭埌鏈嶅姟鍣� + /// </summary> + /// <returns></returns> + /// <param name="topic"></param> + /// <param name="message"></param> + /// <param name="retain"></param> + 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> + /// <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)}_鏄惁鍔犲瘑:{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) + { + DebugPrintLog($"Send:{ex.Message}"); + } + } + + #endregion + + #region 鏁版嵁鎺ユ敹澶勭悊 + + /// <summary> + /// 鎺ユ敹杩滅▼鏁版嵁澶勭悊 + /// </summary> + /// <param name="sender">Sender.</param> + /// <param name="e">E.</param> + static void mqttRemoteClient_MqttMsgPublishReceived(MqttApplicationMessageReceivedEventArgs e) + { + try + { + var topic = e.ApplicationMessage.Topic.TrimStart('/'); + var payload = e.ApplicationMessage.Payload; + + var message = string.Empty; + //浣犲綋鍓嶇殑IP鍙婄鍙e湪浜戠涓嶅瓨鍦�,璇烽噸鏂扮櫥褰曡繛鎺ヤ笅! + + var topics = topic.Split("/"); + if (topics.Length < 3) + { + return; + } + if (topics[0] != "ZigbeeGateWayToClient") + { + return; + } + if (topics[2] == "NotifyGateWayInfoChange") + { + initGateWayBaseInfomation(); + return; + } + if (topics[2] == "Common") + { + var macMark = topics[1]; + topic = topic.Substring(topics[0].Length + topics[1].Length + topics[2].Length + 3); + if (payload[0] == (byte)'{' && payload[payload.Length - 1] == (byte)'}') + { + message = System.Text.Encoding.UTF8.GetString(payload); + } + else + { + foreach (var key in GateWayBaseInfomations.Keys) + { + var value = GateWayBaseInfomations[key]; + if (value.MacMark == macMark) + { + topic = $"{key}/{topic}"; + message = System.Text.Encoding.UTF8.GetString(ZigBee.Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, value.AesKey)); + break; + } + } + } + } + + DebugPrintLog($"杩滅▼杩斿洖鐨勪富棰�:{ topic}_杩滅▼杩斿洖鐨勬暟鎹甠{message}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + + ReceiveMessage(topic, message, payload); + } + catch (Exception ex) + { + DebugPrintLog($"鎺ユ敹浜戠鏁版嵁寮傚父:{ex.Message} "); + } + } + + /// <summary> + /// 鎺ユ敹灞�鍩熺綉涓殑鏁版嵁 + /// 褰撹闃呮秷鎭垚鍔熷悗锛岃浜嬩欢浼氳璋冪敤 + /// </summary> + /// <param name="sender">Sender.</param> + /// <param name="e">E.</param> + void mqttClient_MqttMsgPublishReceived(MqttApplicationMessageReceivedEventArgs e) + { + try + { + var topic = e.ApplicationMessage.Topic; + string payloadString = ""; + + if (IsEncry) + { + //涓婚 + //涓嬭浇鐨勫瓧鑺傛祦涓嶉渶瑕佽В瀵� + if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer") + { + if (topic.Split('/')[2] != "DownloadFile") + { + payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password)); + } + } + else if (topic == topic.Split('/')[0] + "/" + "SendAESKey_Respon") { }//鍥炲涓婚鏄鏂囷紝鏁版嵁鏄槑鏂� + else + { + payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password)); + } + } + else + { + payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); + } + DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{payloadString}"); + ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload); + } + catch (Exception ex) + { + DebugPrintLog($"鎺ユ敹缃戝叧鏁版嵁寮傚父:{ex.Message}"); + } + } + + /// <summary> + /// 鏁版嵁鎺ユ敹澶勭悊 + /// </summary> + /// <param name="topic">Topic.</param> + /// <param name="message">Message.</param> + /// <param name="e">E.</param> + static void ReceiveMessage(string topic, string message, byte[] payload) + { + try + { + if (string.IsNullOrEmpty(message)) + { + message = "{}"; + } + var gatewayID = topic.Split('/')[0];//缃戝叧杩斿洖鐨勭綉鍏矷D + var reportStatus = ""; + reportStatus = topic.Split('/')[1];//涓婚涓鸿澶囦笂鎶ョ殑涓婚 + string addr = "";//涓婃姤鐨勮澶嘺ddr + string epoint = "";//涓婃姤鐨勮澶噀point + string cluID = "";//涓婃姤鐨勮澶嘽luID + string attrId = "";//涓婃姤鐨勮澶嘺ttrId + if (reportStatus == "DeviceStatusReport") + { + addr = topic.Split('/')[2]; + epoint = topic.Split('/')[3]; + cluID = topic.Split('/')[4]; + attrId = topic.Split('/')[5]; + } + + //Log鍐欏叆(璋冭瘯鐢�) + if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1) + { + string text = "缃戝叧鍥炲:" + topic + "\r\n"; + text += message + "\r\n"; + Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text); + } + + //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) + Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message); + + var gwa = GateWayList.Find(obj => obj.GwId == gatewayID); + if (gwa == null) + { + return; + } + + if (gwa.Actions != null) + { + gwa?.Actions(topic, message); + } + + gwa.GwResDataAction?.Invoke(topic, message); + + var jobject = new Newtonsoft.Json.Linq.JObject(); + if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer") + { + if (topic.Split('/')[2] == "DownloadFile") + { + gwa.DownloadFileConfirmAsync(payload); + message = System.Text.Encoding.UTF8.GetString(payload); + gwa.FileContentAction?.Invoke(topic, payload); + DebugPrintLog($"缃戝叧杩斿洖鏁版嵁娴乢{message}"); + return; + } + } + else + { + jobject = Newtonsoft.Json.Linq.JObject.Parse(message); + } + + #region 杩滅▼,涓荤綉鍏充笂鎶ラ�氱煡 + if (IsRemote) + { + if (topic == gatewayID + "/" + "BeMainGw_Report") + { + var gwData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GetGwData>(jobject["Data"].ToString()); + if (gwData != null) + { + var gwList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId); + for (int i = 0; i < gwList.Count; i++) + { + if (gwList[i].GwId == gatewayID) + { + gwList[i].IsMainGateWay = true; + } + else + { + gwList[i].IsMainGateWay = false; + } + } + } + } + } + + #endregion + + #region 璁惧鍦ㄧ嚎鐘舵�佹洿鏂板弽棣� + + //2020.05.11 鍒犻櫎 + + #endregion + + #region 璁惧鐘舵�佷笂鎶� + 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()); + UpdateDeviceInfo(tempDevice, "DeviceStatusReport"); + } + #endregion + #region 闂ㄩ攣鎿嶄綔浜嬩欢閫氱煡 + else if (topic == gatewayID + "/" + "DoorLock/DoorLockOperatingEventNotificationCommand") + { + var deviceID = jobject.Value<int>("Device_ID"); + 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.GwId }; + var OperatingEventNotificationDatad = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockOperatingEventNotificationCommand>(jobject["Data"].ToString()); + if (OperatingEventNotificationDatad != null) + { + doorLock.doorLockOperatingEventNotificationCommand = OperatingEventNotificationDatad; + } + if (gwa.ReportAction != null) + { + DebugPrintLog("DoorLockProgrammingEventNotificationCommand宸茬粡閫氱煡"); + gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock); + } + UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand"); + break; + } + } + #endregion + #region 闂ㄩ攣缂栫▼浜嬩欢閫氱煡 + else if (topic == gatewayID + "/" + "DoorLock/DoorLockProgrammingEventNotificationCommand") + { + var deviceID = jobject.Value<int>("Device_ID"); + 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.GwId }; + var ProgrammingEventNotificationData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockProgrammingEventNotificationCommand>(jobject["Data"].ToString()); + if (ProgrammingEventNotificationData != null) + { + doorLock.doorLockProgrammingEventNotificationCommand = ProgrammingEventNotificationData; + } + if (gwa.ReportAction != null) + { + DebugPrintLog("DoorLockProgrammingEventNotificationCommand宸茬粡閫氱煡"); + gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock); + } + UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand"); + break; + } + } + #endregion + #region IAS瀹夐槻淇℃伅涓婃姤 + + //2020.05.11 鍒犻櫎 + + #endregion + #region 涓嬭浇杩涘害涓婃姤 + else if (topic == gatewayID + "/" + "DownloadFile_Progress") + { + gwa.downloadFileProgressResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DownloadFileProgressResponData>(jobject["Data"].ToString()); + if (gwa.downloadFileProgressResponData == null) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("DownloadFileProgress"); + gwa.ReportAction("DownloadFileProgress", gwa); + } + } + else if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon") + { + gwa.zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGwOperationUpgradeData>(jobject["Data"].ToString()); + if (gwa.zbGwOperationUpgradeData == null) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("鍗忚皟鍣ㄥ崌绾х櫨鍒嗘瘮"); + gwa.ReportAction("CordinatorUpgradePercent", gwa); + } + } + else if (topic == gatewayID + "/" + "OTA/Schedule_Respon") + { + gwa.oTAScheduleResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.OTAScheduleResponData>(jobject["Data"].ToString()); + + if (gwa.oTAScheduleResponData == null) + { + return; + } + + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("鑺傜偣璁惧鍗囩骇鐧惧垎姣�"); + gwa.ReportAction("DeviceUpgradePercent", gwa); + } + } + else if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon") + { + gwa.virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString()); + + if (gwa.virtualDriveUpgradeResponData == null) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("铏氭嫙椹卞姩鍗囩骇鐧惧垎姣�"); + gwa.ReportAction("VirtualDriveUpgrade", gwa); + } + } + #endregion + #region 閲嶅惎缃戝叧绯荤粺 + else if (topic == gatewayID + "/" + "GwReboot_Respon") + { + var gwRebootResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<GwRebootResponData>(jobject["Data"].ToString()); + + if (gwRebootResponData == null) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("GwReboot_Respon宸茬粡閫氱煡"); + gwa.ReportAction("GwReboot_Respon", gwRebootResponData); + } + } + #endregion + #region 闃插尯琚Е鍙戞椂鎶ュ憡 + else if (topic == gatewayID + "/" + "Security/ZoneTriggerReport") + { + 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) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("ZoneTriggerReport宸茬粡閫氱煡"); + gwa.ReportAction("ZoneTriggerReport", ias.zoneTriggerReportData); + } + } + #endregion + #region 閫昏緫琚皟鐢ㄥ弽棣� + else if (topic == gatewayID + "/" + "Logic/Execute_Respon") + { + //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) + //{ + // 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.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); + //} + } + #endregion + #region 妯″紡瀹夐槻鍔ㄤ綔琚渶缁堟縺娲绘椂鍙戦�佹姤璀︿俊鎭� + else if (topic == gatewayID + "/" + "Security/ModeTriggerReport") + { + 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) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("ModeTriggerReport宸茬粡閫氱煡"); + gwa.ReportAction("ModeTriggerReport", ias.modeTriggerReportData); + } + } + #endregion + #region 閫氳繃澶栭儴鏂瑰紡甯冮槻鎾ら槻鎴愬姛鏃舵姤鍛婃伅 + else if (topic == gatewayID + "/" + "Security/EnOrWithdrawSucceedReport") + { + 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) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("EnOrWithdrawSucceedReport"); + gwa.ReportAction("EnOrWithdrawSucceedReport", ias.enOrWithdrawSucceedReportData); + } + } + #endregion + #region 鑳佽揩瀵嗙爜鎾ら槻鏃剁煭淇℃帹閫� + else if (topic == gatewayID + "/" + "Security/PushTargetInfo") + { + 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) + { + return; + } + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + DebugPrintLog("PushTargetInfoReport"); + gwa.ReportAction("PushTargetInfoReport", ias.coercedPWDWithdrawReportData); + } + } + #endregion + + #region 璁惧璇锋眰APP鑾峰彇鍗囩骇鏁版嵁 + else if (topic == gatewayID + "/" + "ZbDataPassthrough") + { + //涓婃姤绫诲瀷閫氱煡 + if (gwa.ReportAction != null) + { + var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString()); + if (clientDataPassthrough != null) + { + DebugPrintLog("DeviceRequestAcUpdateData"); + gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough); + } + } + } + #endregion + } + catch (Exception ex) + { + DebugPrintLog($"澶勭悊鍥炲鐨勬暟鎹姏鍑哄紓甯革細{ex.Message}"); + } + + } + + #endregion + + #region 淇濆瓨缂撳瓨 + + /// <summary> + /// 閲嶆柊淇濆瓨璁惧 + /// </summary> + public void ReSave() + { + Global.WriteFileByBytesByHomeId(FilePath, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(this))); + } + #endregion + + #region 璋冭瘯鎵撳嵃 + + /// <summary> + /// 璋冭瘯鏃舵墦寮�鎵撳嵃淇℃伅锛宼rue:鎵撳嵃锛宖alse:涓嶆墦鍗� + /// </summary> + /// <param name="msg">Message.</param> + /// <param name="flage">If set to <c>true</c> flage.</param> + public static void DebugPrintLog(string msg, bool flage = true) + { +#if DEBUG + if (flage == true) + { + //if (msg.Contains("DeviceStatusReport") == false) + { + System.Console.WriteLine(msg + " " + System.DateTime.Now.ToLongTimeString() + " " + System.DateTime.Now.Millisecond); + } + } +#endif + } + + #endregion + } +} -- Gitblit v1.8.0