From 3272ca5b51e19f7f8a827b0f68400570a547fe60 Mon Sep 17 00:00:00 2001 From: 陈嘉乐 <cjl@hdlchina.com.cn> Date: 星期二, 28 四月 2020 15:02:44 +0800 Subject: [PATCH] 2020-04-28-1 --- ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs | 1867 ++++++++++++++++++++++----------------------------------- 1 files changed, 717 insertions(+), 1,150 deletions(-) diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs index 4ca338b..a105443 100755 --- a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs +++ b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs @@ -8,10 +8,11 @@ using System.Net.Sockets; using System.Net; using Newtonsoft.Json.Linq; -using MQTTnet.Core.Client; using MQTTnet; using Shared.Common; using Shared.Phone.UserView; +using MQTTnet.Client; +using System.Threading.Tasks; namespace ZigBee.Device { @@ -25,6 +26,8 @@ { this.Type = DeviceType.ZbGateway; } + + #region 缃戝叧鐗规畩淇℃伅澶勭悊 /// <summary> @@ -52,16 +55,16 @@ } /// <summary> - /// 杩滅▼缃戝叧 + /// 鏄惁浣跨敤杩滅▼杩炴帴妯″紡 /// </summary> /// <value><c>true</c> if is remote; otherwise, <c>false</c>.</value> - public static bool IsRemote - { - get - { - return ZigBee.Device.ZbGateway.RemoteMqttClient != null && ZigBee.Device.ZbGateway.RemoteMqttClient.IsConnected; - } - } + public static bool IsRemote; + + /// <summary> + /// 鏄惁鎷ユ湁杩滅▼杩炴帴鐨勬潈闄� + /// </summary> + [Newtonsoft.Json.JsonIgnore] + public static bool AllowRemoteCtrl = true; /// <summary> /// 缃戝叧淇濆瓨璺緞 @@ -140,12 +143,6 @@ public List<CommonDevice> DeviceList = new List<CommonDevice>(); /// <summary> - /// 鎵�鏈夌綉鍏充腑鐨勮澶囧垪琛� - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public List<CommonDevice> AllGatewayDeviceList = new List<CommonDevice>(); - - /// <summary> /// 缃戝叧涓満鏅垪琛� /// 涓�涓満鏅腑鍖呭惈鎵�鏈変俊鎭紝鍖呮嫭鍦烘櫙璁惧淇℃伅 /// </summary> @@ -157,34 +154,6 @@ /// </summary> [Newtonsoft.Json.JsonIgnore] public List<Scene.GetSceneDeviceListInfo> SceneDeviceList = new List<Scene.GetSceneDeviceListInfo>(); - - /// <summary> - /// 缃戝叧涓�昏緫鍒楄〃 - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public static List<Logic.GetLogicInfoResponseData> LogicList = new List<Logic.GetLogicInfoResponseData>(); - - /// <summary> - /// 缃戝叧涓環dl绉佹湁鎸夐敭缁戝畾鍒楄〃 - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public List<HDLbutton> HdlButtonList = new List<HDLbutton>(); - - //缃戝叧涓柊鐨勮澶囧垪琛� - [Newtonsoft.Json.JsonIgnore] - public List<CommonDevice> ListNewDeviceInfoData = new List<CommonDevice>(); - - /// <summary> - /// 绉佹湁鎸夐敭淇℃伅鍒楄〃 - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public System.Collections.Generic.Dictionary<string, HDLbutton> hdlButtonInfoList = new Dictionary<string, HDLbutton>(); - - /// <summary> - /// 浼犳劅鍣ㄤ俊鎭垪琛� - /// </summary> - [Newtonsoft.Json.JsonIgnore] - public System.Collections.Generic.Dictionary<string, Scene.TaskListInfo> sceneTaskInfoList = new Dictionary<string, Scene.TaskListInfo>(); #region action variable /// <summary> @@ -221,7 +190,6 @@ /// <para>绗竴涓弬鏁帮細濡傛灉涓� DDevice/IsGetEpointInfo:鏈夋柊璁惧鍔犲叆zigbee缃戠粶鍙嶉</para>璁惧璇锋眰APP鑾峰彇鍗囩骇鏁版嵁 /// <para>绗竴涓弬鏁帮細濡傛灉涓� Device/DeviceJoinZbNet:鑾峰彇鏂拌澶囨墍鏈夌鐐逛俊鎭槸鍚︽垚鍔熷弽棣�</para> /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceRequestAcUpdateData: 璁惧璇锋眰绌鸿皟鍙戝崌绾ф暟鎹�</para> - /// "宸茬粡閫氱煡");//宸茬粡閫氱煡"); /// </summary> [Newtonsoft.Json.JsonIgnore] public Action<string, object> ReportAction; @@ -590,10 +558,25 @@ 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 } }; + var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } }; jObject.Add("Data", data); - Send("GwSetHomeId", jObject.ToString()); + //浣忓畢ID鐨勮缃�,鍥哄畾浣跨敤灞�鍩熺綉,涓嶅瓨鍦ㄨ繙绋嬬殑璇存硶 + SendLocation("GwSetHomeId", System.Text.Encoding.UTF8.GetBytes(jObject.ToString())); } catch { } @@ -3037,22 +3020,6 @@ public static readonly System.Collections.Generic.List<IStatus> StatusList = new System.Collections.Generic.List<IStatus>(); /// <summary> - /// 璁惧鐘舵�佹洿鏂� - /// </summary> - /// <param name="commonDevice">Common device.</param> - public static void UpdateDeviceStatus(CommonDevice commonDevice) - { - if (commonDevice == null) - { - return; - } - for (int i = 0; i < StatusList.Count; i++) - { - StatusList[i].Changed(commonDevice); - } - } - - /// <summary> /// 璁惧淇℃伅鍙樺寲 /// <para>type锛氬鏋滀负 DeviceInComingRespon:璁惧鏂颁笂鎶�</para> /// <para>type锛氬鏋滀负 IASInfoReport:RemoveDeviceRespon</para> @@ -3078,257 +3045,448 @@ /// <summary> /// 灞�鍩熺綉鐨凪QTT /// </summary> - IMqttClient mqttClient; + IMqttClient localMqttClient = new MqttFactory().CreateMqttClient(); + bool localMqttIsConnecting; + public bool localIsConnected; /// <summary> /// 鎵嬫満鏍囪瘑 /// </summary> static Guid currentGuid = Guid.NewGuid(); - /// <summary> - /// 灞�鍩熺綉鐨凪QTT鏄惁姝e湪杩炴帴 - /// </summary> - object mqttIsConnecting = false.ToString(); + + 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 (mqttIsConnecting) + lock (localMqttClient) { - if (mqttIsConnecting.ToString() == true.ToString() || brokerName == null) - { - return; - } - mqttIsConnecting = true.ToString(); + //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� + localMqttIsConnecting = true; - if (mqttClient == null) + //(3)褰揫杩炴帴Mqtt鎴愬姛鍚嶿鎴栬�匸Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒版暟鎹寘鍝嶅簲鏃跺湪mqttClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 + if (localMqttClient.ApplicationMessageReceivedHandler == null) { - //(2)鍒涘缓Mqtt瀹㈡埛绔� - mqttClient = new MqttClientFactory().CreateMqttClient(); - //(3)褰揫杩炴帴Mqtt鎴愬姛鍚嶿鎴栬�匸Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒版暟鎹寘鍝嶅簲鏃跺湪mqttClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 - mqttClient.ApplicationMessageReceived += (sender, e) => - { - if (mqttClient == null || !mqttClient.IsConnected) + localMqttClient.UseApplicationMessageReceivedHandler((e) => { - return; - } - mqttClient_MqttMsgPublishReceived(sender, e); - }; - mqttClient.Disconnected += (sender, e) => - { - IsEncry = false; -#if DEBUG - DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_{System.DateTime.Now.ToString()}"); -#endif - }; - mqttClient.Connected += async (sender, e) => + if (!localMqttClient.IsConnected) + { + return; + } + mqttClient_MqttMsgPublishReceived(e); + }); + } + + if (localMqttClient.DisconnectedHandler == null) + { + localMqttClient.UseDisconnectedHandler(async (e) => { -#if DEBUG - DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}_{System.DateTime.Now.ToString()}"); -#endif - - if (PubKey != null) - { - var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password); - var resultVerityfy = await SendAesKeyAsync(rsaString); - if (resultVerityfy == null) - { - resultVerityfy = await SendAesKeyAsync(rsaString); - } - if (resultVerityfy != null && resultVerityfy.Result == 0) - { - IsEncry = true; - } - } + 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; Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI); - System.Console.WriteLine($"褰撳墠鏄綉鍏砏i-Fi鍦ㄩ�氳_{System.DateTime.Now.ToString()}"); + }); + } - }; - } - - if (RemoteMqttClient != null && RemoteMqttClient.IsConnected == true) - { - RemoteMqttClient?.DisconnectAsync(); - System.Console.WriteLine($"鏀跺埌灞�鍩熺綉缃戝叧锛岃繙绋嬭繛鎺ヤ富鍔ㄦ柇寮�_{System.DateTime.Now.ToString()}"); - RemoteMqttClient = null; - } - - if (mqttClient.IsConnected) - { - return; - } - } - //(1)杩炴帴鍒癕qtt瀹㈡埛绔繛鎺ュ弬鏁� - var connectCloudMqttClientOptions = new MqttClientTcpOptions - { - Server = brokerName, //ip鍦板潃 - ClientId = currentGuid.ToString(), - CleanSession = true,// 璁剧疆鏄惁娓呯┖session,杩欓噷濡傛灉璁剧疆涓篺alse琛ㄧず鏈嶅姟鍣ㄤ細淇濈暀瀹㈡埛绔殑杩炴帴璁板綍锛岃繖閲岃缃负true琛ㄧず姣忔杩炴帴鍒版湇鍔″櫒閮戒互鏂扮殑韬唤杩炴帴 - KeepAlivePeriod = new TimeSpan(0, 5, 0),//璁剧疆蹇冭烦鏃堕棿锛堟渶澶у�硷紝2^16-1 = 65535绉� = 18灏忔椂銆傛渶灏忓�煎彲浠ヤ负0锛岃〃绀哄鎴风涓嶆柇寮�銆備竴鑸涓哄嚑鍒嗛挓锛屾瘮濡傚井淇″績璺冲懆鏈熶负300绉掋�傦級 - DefaultCommunicationTimeout = new TimeSpan(0, 0, 100),//璁剧疆瓒呮椂鏃堕棿 - }; - await mqttClient.ConnectAsync(connectCloudMqttClientOptions); + 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) { -#if DEBUG DebugPrintLog($"灞�鍩熺綉閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); -#endif } finally { - mqttIsConnecting = false.ToString(); + localMqttIsConnecting = false; } }); + } + + class GateWayBaseInfomation + { + //public string GatewayUniqueId;//"Emq缃戝叧1", <!-- 缃戝叧Mac --> + public bool MqttOnlineStatus;//: true, <!-- 缃戝叧鍦ㄤ簯绔疎mq鏄惁鍦ㄧ嚎 --> + public string AesKey;// : "a5d8da8a-ddea-48", <!-- 涓庢缃戝叧鍦ㄤ簯绔疎mq閫氫俊鏃讹紝璐熻浇鍔犺В鐨�16浣岮es瀵嗛挜 --> + public string MacMark;//: "61eaa0ea-4812-4a7a-86d6-3098c61e64ed" <!-- 缃戝叧瀵瑰簲鐨勫敮涓�鐮� --> + } + /// <summary> + /// 褰撳墠鏈夊笎鍙蜂笅鎵�鏈夌殑缃戝叧鍒楄〃鍙婁俊鎭� + /// </summary> + static Dictionary<string, GateWayBaseInfomation> GateWayBaseInfomations = new Dictionary<string, GateWayBaseInfomation> { }; + /// <summary> + /// 鑾峰彇褰撳墠甯愬彿鎵�鏈夌殑缃戝叧淇℃伅 + /// </summary> + /// <returns></returns> + static async System.Threading.Tasks.Task initGateWayBaseInfomation() + { + if (AllowRemoteCtrl == false) + { + //娌℃湁杩滅▼杩炴帴鐨勬潈闄� + return; + } + string loginToken = Config.Instance.Token; + if (Config.Instance.Home.IsOthreShare == true) + { + //鑾峰彇鎴愬憳鐨勭壒娈奣oken + var pra = new + { + CommonPage.RequestVersion, + LoginAccessToken = Config.Instance.Token, + MainAccountId = Config.Instance.Home.MainUserDistributedMark, + SharedHid = Config.Instance.Home.Id + }; + + var listNotShow = new List<string>() { "NotSetAgain" }; + var resultData = await Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, listNotShow); + if (resultData == null) + { + return; + } + var revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Common.ResponseEntity.ResponsePack>(Encoding.UTF8.GetString(resultData)); + //鍒嗕韩閾炬帴 + var info = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Phone.UserCenter.MemberAdministratorResult>(revertObj.ResponseData.ToString()); + loginToken = info.RequestToken; + } + + try + { + //璁剧疆璁块棶鎺ュ彛鐨勫弬鏁� + var pra2 = new Shared.Phone.UserCenter.GetGatewayPra(); + pra2.IsOtherAccountCtrl = Config.Instance.Home.IsOthreShare; + pra2.ReqDto.PageSetting.Page = 1; + pra2.ReqDto.PageSetting.PageSize = 20; + pra2.ReqDto.LoginAccessToken = loginToken; + var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(pra2)); + + var result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, loginToken); + if (result != null) + { + var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result)); + + var statuCode = jobject["StateCode"].ToString(); + if (statuCode != "Success") + { + //搴忓垪鍖栧璞� + var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pra2); + //Log鍑哄姏 + string errorMsg = "鎺ュ彛璁块棶澶辫触鈽咃細App/GetSingleHomeGatewayPagger " + statuCode + "\r\n"; + errorMsg += "鍙傛暟锛歕r\n" + requestJson; + Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, errorMsg); + return; + } + + var responseData = jobject["ResponseData"]; + if (responseData != null) + { + if (responseData["PageData"] != null) + { + var list = JArray.Parse(responseData["PageData"].ToString()); + foreach (var v in list) + { + GateWayBaseInfomations[v["GatewayUniqueId"].ToString()] = new GateWayBaseInfomation { AesKey = v["AesKey"].ToString(), MacMark = v["MacMark"].ToString(), MqttOnlineStatus = bool.Parse(v["MqttOnlineStatus"].ToString()) }; + //if (RemoteMqttClient.IsConnected) + { + await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/{v["MacMark"].ToString()}/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce); + } + } + } + } + } + } + catch (Exception ex) + { + Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(ex); + } } /// <summary> /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴 /// </summary> - static bool remoteMqttIsConnecting; static bool IsLoginAgain; + static bool remoteMqttIsConnecting; + static bool IsLoginAgain; /// <summary> /// 杩滅▼MqttClient /// </summary> - public static IMqttClient RemoteMqttClient; + public static IMqttClient RemoteMqttClient= new MqttFactory().CreateMqttClient(); + static bool remoteIsConnected; private int IsLogin = 0; [Newtonsoft.Json.JsonIgnore] static Action actionTemp; + /// <summary> /// 鍚姩杩滅▼Mqtt /// </summary> /// <returns>The start.</returns> /// <param name="brokerName">Broker name.</param> - public static async System.Threading.Tasks.Task StartCloudMqtt() - { + public static async System.Threading.Tasks.Task StartRemoteMqtt() + { + //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺 + if (AllowRemoteCtrl == false + || remoteMqttIsConnecting + || !Shared.Common.Config.Instance.IsLogin + || Shared.Common.Config.Instance.HomeId == "" + || remoteIsConnected) + { + return; + } await System.Threading.Tasks.Task.Factory.StartNew(async () => { try { - if (remoteMqttIsConnecting || Shared.Common.Config.Instance.HomeId == "") + lock (RemoteMqttClient) { - return; - } - remoteMqttIsConnecting = true; + //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺� + remoteMqttIsConnecting = true; - var url = Shared.Common.Config.Instance.ZigbeeMqttBrokerLoadSubDomain;//.Replace("6688","6689"); - if (string.IsNullOrEmpty(url) || !url.StartsWith("tcp://") || url.Split(':').Length != 3) - { - remoteMqttIsConnecting = false; - return; - } - if (RemoteMqttClient == null) - { - //(2)鍒涘缓Mqtt瀹㈡埛绔� - RemoteMqttClient = new MqttClientFactory().CreateMqttClient(); + #region 鍒濆鍖栬繙绋婱qtt //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊 - RemoteMqttClient.ApplicationMessageReceived += (sender, e) => + if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) { - if (RemoteMqttClient == null || !RemoteMqttClient.IsConnected) - { - return; - } - mqttRemoteClient_MqttMsgPublishReceived(sender, e); - }; - RemoteMqttClient.Disconnected += (sender, e) => - { -#if DEBUG - DebugPrintLog($"杩滅▼杩炴帴鏂紑_{System.DateTime.Now.ToString()}"); -#endif - }; - RemoteMqttClient.Connected += async (sender, e) => - { -#if DEBUG - DebugPrintLog($"杩滅▼杩炴帴鎴愬姛_{System.DateTime.Now.ToString()}"); -#endif - Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote); - //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅 - var gateWayList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId); - if (gateWayList.Find(obj => obj.getGatewayBaseInfo.IsMainGateWay == true) == null) + RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => { - if (gateWayList.Count == 1) + //杩欓噷鏄壒娈婄殑涓婚 + 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")//瀛愯处鍙疯鍒犻櫎 { - gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true; + mqttRemoteClient_MqttMsgPublishReceived(e); + return; } - else + if (!RemoteMqttClient.IsConnected || !IsRemote) { - for (int i = 0; i < gateWayList.Count; i++) + 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(); + Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote); + //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅 + var gateWayList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId); + if (gateWayList.Find(obj => obj.getGatewayBaseInfo.IsMainGateWay == true) == null) + { + if (gateWayList.Count == 1) { - var gateWay = gateWayList[i]; - var info = await gateWay.GetZbGwInfoAsync(); - if (info == null || info.getGwData == null) + gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true; + } + else + { + for (int i = 0; i < gateWayList.Count; i++) { - continue; - } - if (info.getGwData.IsDominant == 1) - { - gateWay.getGatewayBaseInfo.IsMainGateWay = true; - for (int j = i + 1; j < gateWayList.Count; j++) + var gateWay = gateWayList[i]; + var info = await gateWay.GetZbGwInfoAsync(); + if (info == null || info.getGwData == null) { - gateWayList[j].getGatewayBaseInfo.IsMainGateWay = false; + continue; } - break; + if (info.getGwData.IsDominant == 1) + { + for (int j = 0; j < gateWayList.Count; j++) + { + if (gateWayList[i].getGatewayBaseInfo.gwID == info.getGwData.GwId) + { + gateWayList[i].getGatewayBaseInfo.IsMainGateWay = true; + } + else + { + gateWayList[i].getGatewayBaseInfo.IsMainGateWay = false; + } + } + break; + } } } } - } - }; - } - - if (RemoteMqttClient.IsConnected) - { - //褰撶綉鍏崇殑杩炴帴鏂瑰紡鏀瑰彉鏃�,妫�娴嬬綉鍏�,鐒跺悗鏄剧ず鐗规晥(鍙噸澶嶈皟鐢�) - return; - } - for (int i = 0; i < GateWayList.Count; i++) - { - var gateWay = GateWayList[i]; - try - { - gateWay.IsVirtual = true; - await gateWay.DisConnect("鏈湴鎼滅礌涓嶅埌缃戝叧锛屽噯澶囪皟鐢ㄨ繙绋嬶紝鍏抽棴褰撳墠灞�鍩熺綉涓墍鏈夌綉鍏�"); + }); } - catch { } - } - //鏂紑鍚庨噸鏂伴摼鎺ラ渶瑕侀噸鏂扮櫥褰曡幏鍙栬繛鎺ョ殑瀵嗙爜 - var tempResult = await Shared.Phone.UserView.HomePage.Instance.LoginByPWDAsync(Shared.Common.Config.Instance.Account, Shared.Common.Config.Instance.Password); - if (tempResult != 1) - { -#if DEBUG - DebugPrintLog($"閲嶆柊杩炴帴杩滅▼閫氳澶辫触锛屽洜涓鸿幏鍙栨柊鐨凨EY澶辫触"); -#endif - return; + #endregion } - //杩樻湁绉嶆儏鍐垫槸鍚屼竴涓狪D 鏈夊涓澶囩敤杩欎釜id杩炴帴锛堜細瀵艰嚧涓柇锛� - string clientId = Shared.Common.Config.Instance.ConnectZigbeeMqttClientId; - string username = Shared.Common.Config.Instance.ConnectZigbeeMqttBrokerName; - string passwordRemote = Shared.Common.Config.Instance.ConnectZigbeeMqttBrokerPwd; - //(1)杩炴帴鍒颁簯绔殑Mqtt瀹㈡埛绔繛鎺ュ弬鏁� - var connectCloudMqttClientOptions = new MqttClientTcpOptions - { - Server = url.Split(':')[1].Substring("//".Length), //114.215.173.87 鍏堝啓ip鍚э紝杩欎釜鍦板潃鍙兘鍚庨潰浼氭崲鎴愬煙鍚� - Port = int.Parse(url.Split(':')[2]), - ClientId = clientId, - UserName = username,//杩炴帴鐨勭敤鎴峰悕 - Password = passwordRemote,//杩炴帴鐨勫瘑鐮侊紙App鐧诲綍鍚庤幏鍙栧埌鐨勮繛鎺ヤ簯绔疢qtt瀵嗙爜鍙兘杩炴帴涓�娆℃垚鍔熶箣鍚庝笉鑳藉啀浣跨敤鐩稿悓鐨勫瘑鐮佽繘琛岃繛鎺qtt鍚﹀垯浼氭彁绀虹敤鎴峰悕瀵嗙爜澶辫触锛岃繛鎺ヤ笉涓婁簯绔�;锛� - CleanSession = true,// 璁剧疆鏄惁娓呯┖session,杩欓噷濡傛灉璁剧疆涓篺alse琛ㄧず鏈嶅姟鍣ㄤ細淇濈暀瀹㈡埛绔殑杩炴帴璁板綍锛岃繖閲岃缃负true琛ㄧず姣忔杩炴帴鍒版湇鍔″櫒閮戒互鏂扮殑韬唤杩炴帴 - KeepAlivePeriod = new TimeSpan(0, 5, 0),//璁剧疆蹇冭烦鏃堕棿锛堟渶澶у�硷紝2^16-1 = 65535绉� = 18灏忔椂銆傛渶灏忓�煎彲浠ヤ负0锛岃〃绀哄鎴风涓嶆柇寮�銆備竴鑸涓哄嚑鍒嗛挓锛屾瘮濡傚井淇″績璺冲懆鏈熶负300绉掋�傦級 - DefaultCommunicationTimeout = new TimeSpan(0, 0, 100),//璁剧疆瓒呮椂鏃堕棿 - }; - //杩滅▼閫氳杩炴帴锛岃繛鎺ヤ簯绔湇鍔″櫒 - await RemoteMqttClient.ConnectAsync(connectCloudMqttClientOptions); + try + { + byte[] result = null; + if (Config.Instance.Home.IsOthreShare == false) + { + //涓讳汉 + var jsonData = new Dictionary<string, object> + { + ["RequestVersion"] = CommonPage.RequestVersion, + ["RequestSource"] = 0, + ["LoginAccessToken"] = Config.Instance.Token, + ["RequestProtocolType"] = 0, + ["PlatformStr"] = "h",//杩欎袱涓�煎鏋滀笉璁剧疆,鍒欎簯绔笉鍙戝竷涓婚 + ["PublishPayloadJsonStr"] = "1" + }; + var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData)); + result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token); + } + else + { + //鍒嗕韩鐨� + var jsonData = new Dictionary<string, object> + { + ["RequestVersion"] = CommonPage.RequestVersion, + ["RequestSource"] = 0, + ["LoginAccessToken"] = Config.Instance.Token, + ["RequestProtocolType"] = 0, + ["MainUserDistributedMark"] = Config.Instance.Home.MainUserDistributedMark, + ["HomeId"] = Config.Instance.Home.Id, + ["PlatformStr"] = "h",//杩欎袱涓�煎鏋滀笉璁剧疆,鍒欎簯绔笉鍙戝竷涓婚 + ["PublishPayloadJsonStr"] = "1" + }; + var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData)); + result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/ShareMemberConnMqttInfo", bytes, Config.Instance.Token); + } + if (result != null) + { + var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result)); + if (jobject["StateCode"].ToString() == "NotAllowRemoteCtrl") + { + //娌℃湁杩滅▼杩炴帴鐨勬潈闄� + AllowRemoteCtrl = false; + return; + } + //铏界劧涓嶇煡閬撳鎸や笅绾块偅涓�鍧楁湁娌℃湁鐢�,涓嶈繃鍏堣繖涔堝紕 + await System.Threading.Tasks.Task.Delay(1500); + var responseData = jobject["ResponseData"]; + if (responseData != null) + { + var connEmqDomainPort = responseData["ConnEmqDomainPort"]?.ToString(); + var connEmqClientId = responseData["ConnEmqClientId"]?.ToString(); + var connEmqUserName = responseData["ConnEmqUserName"]?.ToString(); + var connEmqPwd = responseData["ConnEmqPwd"]?.ToString(); + //璁板綍璧峰綋鍓嶇殑瀹㈡埛绔疘D + Config.Instance.ConnEmqClientId = connEmqClientId; + + var connEmqDomainPorts = connEmqDomainPort.Replace("//", "").Split(':'); + var domain = connEmqDomainPorts[1]; + var port = connEmqDomainPorts[2]; + + var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder() + .WithClientId(connEmqClientId) + .WithTcpServer(domain, int.Parse(port)) + .WithCredentials(connEmqUserName, connEmqPwd) + .WithKeepAlivePeriod(TimeSpan.FromSeconds(20)) + .WithCleanSession() + //.WithCommunicationTimeout(TimeSpan.FromSeconds(10)) + .Build(); + await DisConnectRemoteMqttClient("StartRemoteMqtt"); + await RemoteMqttClient.ConnectAsync(options, CancellationToken.None); + + remoteIsConnected = true; + } + } + } + catch { } + finally + { + //鏈�缁堣閲婃斁杩炴帴鐘舵�� + remoteMqttIsConnecting = false; + } } catch (Exception ex) { -#if DEBUG DebugPrintLog($"杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); -#endif - } - finally - { - remoteMqttIsConnecting = false; } }); } @@ -3336,25 +3494,44 @@ /// <summary> /// 鏂紑鏈嶅姟鍣ㄨ繛鎺� /// </summary> - public async System.Threading.Tasks.Task DisConnect(string s) + public async System.Threading.Tasks.Task DisConnectLocalMqttClient(string s) { try { -#if DEBUG - DebugPrintLog($"涓诲姩鏂紑_{System.DateTime.Now.ToString()}_{s}"); -#endif - if (mqttClient != null && mqttClient.IsConnected == true) + if (localIsConnected) { - await mqttClient.DisconnectAsync(); - } + localIsConnected = false; + DebugPrintLog($"Local涓诲姩鏂紑_{s}"); + //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await localMqttClient.DisconnectAsync(); + } } catch (Exception ex) { -#if DEBUG - DebugPrintLog($"鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}"); -#endif + 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 /// <summary> @@ -3383,37 +3560,38 @@ /// <summary> /// 杩滅▼鍙戦�佹暟鎹牸寮� /// </summary> - async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, MQTTnet.Core.Protocol.MqttQualityOfServiceLevel qosLevel = MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, bool retain = false) + async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false) { - #region MD5鍔犲瘑 token - var result = System.Text.Encoding.UTF8.GetBytes(Shared.Common.Config.Instance.Password); - var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); - var output = md5.ComputeHash(result); - var md5Password = BitConverter.ToString(output).Replace("-", "").ToUpper(); - #endregion - - //(1)鐢熸垚[鐢ㄦ埛鍚�:瀵嗙爜] - var userNameAndPwdStr = string.Concat(Shared.Common.Config.Instance.Account, RemoteOperatorConsts.CAP_NUMBER, md5Password); - - //(2)灏�(1)杞垚Base64瀛楃涓�,鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜)] - var userNameAndPwdStrBaseSexFour = Convert.ToBase64String(ZigBee.Common.CommonInfo.EncodingUTF8.GetBytes(userNameAndPwdStr)); - - //(3)灏�(2)缁х画鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp] - var userNameAndPwdStrBaseSexFourAndTimestamp = string.Concat(userNameAndPwdStrBaseSexFour, RemoteOperatorConsts.CAP_NUMBER, CurrentTimeStamp.ToString()); - - ///[Zigbee.Buspro]App/id(甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/杞彂缁欑綉鍏崇殑涓婚/XX/XX - //(4)鐢熸垚涓婃姤涓婚锛屼富棰樻ā寮忛渶瑕佷负 /ZigbeeApp/id(涓诲瓙璋冭瘯甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/topicName "000204022022" GateWayId 000204022022 - var reportTopic = string.Format("/{0}/{1}/{2}/{3}/{4}", RemoteOperatorConsts.ZIGBEE_APP_STARTS_WITH, Shared.Common.Config.Instance.Account, userNameAndPwdStrBaseSexFourAndTimestamp, this.getGatewayBaseInfo?.gwID, topicName); - - //(5)浣跨敤浣犵櫥褰曟垚鍔熸椂8浣峩ey锛岃繘琛孌ES鍔犲瘑浣犻渶瑕佷笂鎶ョ殑鏁版嵁 - string topicEncStr = reportTopic; - //鏂囦欢娴佷笉鐢ㄥ姞瀵� - topicEncStr = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(topicEncStr), Shared.Common.Config.Instance.MqttKey); - topicEncStr = topicEncStr.Replace("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]").Replace("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]"); - message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, Shared.Common.Config.Instance.MqttKey)); - - //(6)鏋勫缓Mqtt闇�瑕佸彂甯冪殑鏁版嵁鍖�,鍙戝竷缁欎簯绔殑MqttBroker - await RemoteMqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topicEncStr, message, qosLevel, retain)); + try + { + if (this.getGatewayBaseInfo?.gwID == null || !GateWayBaseInfomations.ContainsKey(this.getGatewayBaseInfo?.gwID)) + { + return; + } + var gateWayBaseInfomation = GateWayBaseInfomations[this.getGatewayBaseInfo?.gwID]; + message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey); + var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.MacMark}/Common/{topicName}"; + //(6)鏋勫缓Mqtt闇�瑕佸彂甯冪殑鏁版嵁鍖�,鍙戝竷缁欎簯绔殑MqttBroker + if (remoteIsConnected) + { + try + { + await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }); + } + catch (Exception e) + { + await DisConnectRemoteMqttClient(e.Message); + await StartRemoteMqtt(); + if (remoteIsConnected) + { + await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }); + } + } + } + } + catch + { + } } /// <summary> @@ -3422,9 +3600,8 @@ /// <returns></returns> /// <param name="topic"></param> /// <param name="message"></param> - /// <param name="qosLevel"></param> /// <param name="retain"></param> - public async System.Threading.Tasks.Task Send(string topic, byte[] message, MQTTnet.Core.Protocol.MqttQualityOfServiceLevel qosLevel = MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, bool retain = false) + public async System.Threading.Tasks.Task Send(string topic, byte[] message, bool retain = false) { try { @@ -3435,46 +3612,44 @@ if (IsRemote) { - - await SendRemoteMsg(topic, message, qosLevel, retain); -#if DEBUG - DebugPrintLog($"杩滅▼ 鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") -#endif + await SendRemoteMsg(topic, message, retain); + DebugPrintLog($"杩滅▼鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") } else { -#if DEBUG - DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{System.DateTime.Now.ToString()}"); -#endif - if (mqttClient == null || !mqttClient.IsConnected) - { - await StartLocalMqtt(getGatewayBaseInfo.IpAddress); - } - + DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + if (IsEncry) { //鏂囦欢娴佷笉鐢ㄥ姞瀵� if (topic != "FileTransfer/SendFile") { - topic = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(topic), Password); - message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, password)); - DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰橈紙绉樻枃锛�:{topic}_褰撳墠绉橀挜{Password}_鍙戦�佸埌缃戝叧鐨勬暟鎹紙绉樻枃锛�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{System.DateTime.Now.ToString()}"); - + message = SecuritySet.AesEncryptBytes(message, password); } - - await mqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topic, message, qosLevel, retain)); - } - else - { - await mqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topic, message, qosLevel, retain)); - } + } + if (localIsConnected) + { + try + { + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + catch(Exception e) + { + DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}"); + await DisConnectLocalMqttClient(e.Message); + await StartLocalMqtt("ReConnect"); + if (localIsConnected) + { + DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + } + } } } catch (Exception ex) { -#if DEBUG DebugPrintLog($"Send:{ex.Message}"); -#endif } } @@ -3484,17 +3659,66 @@ /// <returns></returns> /// <param name="topic"></param> /// <param name="message"></param> - /// <param name="qosLevel"></param> /// <param name="retain"></param> - public async System.Threading.Tasks.Task Send(string topic, string message, MQTTnet.Core.Protocol.MqttQualityOfServiceLevel qosLevel = MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, bool retain = false) + 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), qosLevel, retain); + await Send(topic, System.Text.Encoding.UTF8.GetBytes(message), retain); + } + + /// <summary> + /// 寮哄埗鎸囧畾浣跨敤鏈湴灞�鍩熺綉鍙戦�佹秷鎭埌鏈嶅姟鍣� + /// </summary> + /// <returns></returns> + /// <param name="topic"></param> + /// <param name="message"></param> + /// <param name="retain"></param> + public async Task SendLocation(string topic, byte[] message, bool retain = false) + { + try + { + if (Shared.Common.Config.Instance.HomeId == "") + { + return; + } + + DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + + if (IsEncry) + { + //鏂囦欢娴佷笉鐢ㄥ姞瀵� + if (topic != "FileTransfer/SendFile") + { + message = SecuritySet.AesEncryptBytes(message, password); + } + } + if (localIsConnected) + { + try + { + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + catch (Exception e) + { + DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}"); + await DisConnectLocalMqttClient(e.Message); + await StartLocalMqtt("ReConnect"); + if (localIsConnected) + { + DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}"); + await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain }); + } + } + } + } + catch (Exception ex) + { + DebugPrintLog($"Send:{ex.Message}"); + } } - [Serializable] public class CloudTimeResponse @@ -3509,100 +3733,59 @@ /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> - static void mqttRemoteClient_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e) + static void mqttRemoteClient_MqttMsgPublishReceived(MqttApplicationMessageReceivedEventArgs e) { try { var topic = e.ApplicationMessage.Topic.TrimStart('/'); + var payload = e.ApplicationMessage.Payload; + var message = string.Empty; //浣犲綋鍓嶇殑IP鍙婄鍙e湪浜戠涓嶅瓨鍦�,璇烽噸鏂扮櫥褰曡繛鎺ヤ笅! - if (topic == "YouIpAndPortNoRecord") + + var topics = topic.Split("/"); + if (topics.Length < 3) { - message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); - } - else if (topic == "BeingSqueezedOffline") - { - //浜戠涓殑褰撳墠杩炴帴琚尋涓嬬嚎锛岄渶瑕侀�氱煡app - //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) - message = "BeingSqueezedOffline"; - Shared.Phone.UserCenter.HdlGatewayReceiveLogic.GatewayOverallMsgReceive("", topic, null); - DebugPrintLog($"琚尋涓嬬嚎閫氱煡:{ topic}_杩滅▼杩斿洖鐨勬暟鎹甠{message}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") return; } - //閲嶆柊鐧诲綍:甯愬彿鎴栬�呭叡浜繛鎺ヤ腑鐨刐瀛愬笎鍙峰垎甯冨紡Id$Share$鍒嗗竷寮忎綇瀹匢d=XXX灏氭湭鐧诲綍,璇烽噸鏂扮櫥褰曞悗鍐嶈繛鎺ュ悗鍐嶈繘琛屽彂甯冩搷浣�,濡傛灉鎮ㄥ綋鍓嶆槸鍒汉鍏变韩缁欎綘鐨勮繛鎺�,鍒欒閲嶆柊璇锋眰鑾峰彇杩炴帴淇℃伅涓�涓�,鍐嶅垵濮嬪寲杩炴帴鍐嶆鍙戝竷杩滅▼鎺у埗鍗冲彲!! - else if (topic == "AppNoLogin") + if (topics[0] != "ZigbeeGateWayToClient") { - message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); + return; } - else - { - topic = topic.Replace("[[$-MQTT_TILT_SYMBOL_REPLACE-$]]", "/"); - topic = topic.Replace("[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]", "+"); - topic = ZigBee.Common.SecuritySet.AesDecrypt(System.Text.Encoding.UTF8.GetBytes(topic), Shared.Common.Config.Instance.MqttKey).TrimStart('/'); ; - - if (!message.EndsWith("}")) - { - message = ZigBee.Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Shared.Common.Config.Instance.MqttKey); - } + if (topics[2]== "NotifyGateWayInfoChange") { + initGateWayBaseInfomation(); + return; } -#if DEBUG - DebugPrintLog($"杩滅▼杩斿洖鐨勪富棰�:{ topic}_杩滅▼杩斿洖鐨勬暟鎹甠{message}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") -#endif - var cloudMqttResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Common.CloudMqttResponsePack>(message); - if (cloudMqttResult != null) + if (topics[2] == "Common") { - if (topic == "AppConnectMqttBrokerSuccess") + 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)'}') { - RemoteTimeStamp = ulong.Parse(cloudMqttResult.CloudTimestamp); - LoginRemoteDateTime = System.DateTime.Now; -#if DEBUG - DebugPrintLog($"杩滅▼杩斿洖涓婚:{topic}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff" // {System.DateTime.Now.ToString()}"); -#endif - return; + message = System.Text.Encoding.UTF8.GetString(payload); } else { - switch (cloudMqttResult.StateCode) + foreach (var key in GateWayBaseInfomations.Keys) { - case "GatewayIdNoIsYou": - message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info; -#if DEBUG - DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}"); -#endif - return; - case "AppTimeOut": - RemoteTimeStamp = ulong.Parse(cloudMqttResult.CloudTimestamp); - LoginRemoteDateTime = System.DateTime.Now; - message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info; -#if DEBUG - DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}"); -#endif - return; - case "AppReportSuccess": - RemoteTimeStamp = ulong.Parse(cloudMqttResult.CloudTimestamp); - LoginRemoteDateTime = System.DateTime.Now; - message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info; -#if DEBUG - DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}"); -#endif - return; - case "ForwardGatewayNoOnLine": - message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info; -#if DEBUG - DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}"); -#endif - return; + 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; + } } } } - ReceiveMessage(topic, message, e); + DebugPrintLog($"杩滅▼杩斿洖鐨勪富棰�:{ topic}_杩滅▼杩斿洖鐨勬暟鎹甠{message}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + + ReceiveMessage(topic, message, payload); } catch (Exception ex) { -#if DEBUG - DebugPrintLog($"鎺ユ敹浜戠鏁版嵁寮傚父:{ex.Message}"); -#endif + DebugPrintLog($"鎺ユ敹浜戠鏁版嵁寮傚父:{ex.Message} "); } } @@ -3612,45 +3795,40 @@ /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> - void mqttClient_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e) + void mqttClient_MqttMsgPublishReceived(MqttApplicationMessageReceivedEventArgs e) { try { var topic = e.ApplicationMessage.Topic; - var message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); + string payloadString = ""; if (IsEncry) { //涓婚 - topic = Common.SecuritySet.AesDecrypt(System.Text.Encoding.UTF8.GetBytes(topic), Password); //涓嬭浇鐨勫瓧鑺傛祦涓嶉渶瑕佽В瀵� if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer") { if (topic.Split('/')[2] != "DownloadFile") { - message = Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Password); + payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password)); } } else if (topic == topic.Split('/')[0] + "/" + "SendAESKey_Respon") { }//鍥炲涓婚鏄鏂囷紝鏁版嵁鏄槑鏂� else { - message = Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Password); + payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password)); } } - else - { - topic = e.ApplicationMessage.Topic; + else + { + payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); } -#if DEBUG - DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{message}_{System.DateTime.Now.ToString()}"); -#endif - ReceiveMessage(topic, message, e); + DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{payloadString}"); + ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload); } catch (Exception ex) { -#if DEBUG DebugPrintLog($"鎺ユ敹缃戝叧鏁版嵁寮傚父:{ex.Message}"); -#endif } } @@ -3660,7 +3838,7 @@ /// <param name="topic">Topic.</param> /// <param name="message">Message.</param> /// <param name="e">E.</param> - static void ReceiveMessage(string topic, string message, MqttApplicationMessageReceivedEventArgs e) + static void ReceiveMessage(string topic, string message, byte []payload) { try { @@ -3681,9 +3859,12 @@ epoint = topic.Split('/')[3]; cluID = topic.Split('/')[4]; attrId = topic.Split('/')[5]; - } + } + + //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) + Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message); - var gwa = ZigBee.Device.ZbGateway.GateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == gatewayID); + var gwa = GateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == gatewayID); if (gwa == null) { return; @@ -3694,32 +3875,18 @@ gwa?.Actions(topic, message); } - if (gwa.GwResDataAction != null) - { - gwa.GwResDataAction(topic, message); - if (topic == $"{gatewayID}/DoorLock/DoorLockOperatingEventNotificationCommand") - { - Console.WriteLine($"111_DoorLockOperatingEventNotificationCommand:{message}"); - } - if (topic == $"{gatewayID}/DoorLock/DoorLockProgrammingEventNotificationCommand") - { - Console.WriteLine($"111_DoorLockProgrammingEventNotificationCommand:{message}"); - } - } + gwa.GwResDataAction?.Invoke(topic, message); gwa.CurrentGateWayId = gatewayID; - Newtonsoft.Json.Linq.JObject jobject = new Newtonsoft.Json.Linq.JObject(); + 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(e.ApplicationMessage.Payload); - message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); - if (gwa.FileContentAction != null) - { - gwa.FileContentAction(topic, e.ApplicationMessage.Payload); - } - DebugPrintLog($"缃戝叧杩斿洖鏁版嵁娴乢{message}_{System.DateTime.Now.ToString()}"); + gwa.DownloadFileConfirmAsync(payload); + message = System.Text.Encoding.UTF8.GetString(payload); + gwa.FileContentAction?.Invoke(topic, payload); + DebugPrintLog($"缃戝叧杩斿洖鏁版嵁娴乢{message}"); return; } } @@ -3728,41 +3895,6 @@ jobject = Newtonsoft.Json.Linq.JObject.Parse(message); } - //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) - Shared.Phone.UserCenter.HdlGatewayReceiveLogic.GatewayOverallMsgReceive(gatewayID, topic, jobject); - - #region 浜戠閫氱煡 - var cloudMqttResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Common.CloudMqttResponsePack>(message); - if (cloudMqttResult != null) - { - switch (cloudMqttResult.StateCode) - { - case "AppNoLogin": - if (gwa.CloudErrorAction != null) - { - DebugPrintLog("AppNoLogin宸茬粡閫氱煡"); - gwa.CloudErrorAction("AppNoLogin", "鐧诲綍杩囨湡锛岃閲嶆柊鐧诲綍"); - } - //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�) - Shared.Phone.UserCenter.HdlGatewayReceiveLogic.GatewayOverallMsgReceive(gatewayID, "AppNoLogin", jobject); - break; - case "AppTimeOut": - if (gwa.CloudErrorAction != null) - { - DebugPrintLog("AppTimeOut宸茬粡閫氱煡"); - gwa.CloudErrorAction("AppTimeOut", "浠庝簯绔幏鍙栨暟鎹秴鏃讹紝璇烽噸鏂拌幏鍙�"); - } - break; - case "ForwardGatewayNoOnLine": - if (gwa.CloudErrorAction != null) - { - DebugPrintLog("ForwardGatewayNoOnLine宸茬粡閫氱煡"); - gwa.CloudErrorAction("ForwardGatewayNoOnLine", "褰撳墠鎿嶄綔鐨勭綉鍏充笉鍦ㄧ嚎"); - } - break; - } - } - #endregion #region 杩滅▼,涓荤綉鍏充笂鎶ラ�氱煡 if (IsRemote) { @@ -3772,17 +3904,15 @@ if (gwData != null) { var gwList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId); - for (int i = 0; i < gwList.Count; i++) { - var gwTemp = gwList[i]; - if (gwData.IsDominant == 1) - { - gwTemp.getGatewayBaseInfo.IsMainGateWay = true; - for (int j = i + 1; j < gwList.Count; j++) - { - gwList[j].getGatewayBaseInfo.IsMainGateWay = false; - } + if (gwList[i].getGatewayBaseInfo.gwID == gatewayID) + { + gwList[i].getGatewayBaseInfo.IsMainGateWay = true; + } + else + { + gwList[i].getGatewayBaseInfo.IsMainGateWay = false; } } } @@ -3829,380 +3959,40 @@ if (topic == gatewayID + "/" + "DeviceInComingRespon") { //鏂拌澶囦笂鎶ワ紝閲嶆柊鍙戣幏鍙栨墍鏈夌殑璁惧 - var deviceID = jobject.Value<int>("Device_ID"); - switch ((DeviceType)(deviceID)) - { - case DeviceType.DimmableLight: - var dimmableLight = new DimmableLight() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - dimmableLight.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<DimmableLight.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", dimmableLight.getNewDeviceInfo); - } - UpdateDeviceInfo(dimmableLight, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.OnOffOutput: - var toggleLight = new ToggleLight() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - toggleLight.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ToggleLight.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", toggleLight.getNewDeviceInfo); - } - UpdateDeviceInfo(toggleLight, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.AirSwitch: - var airSwitch = new AirSwitch() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - airSwitch.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<AirSwitch.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", airSwitch.getNewDeviceInfo); - } - UpdateDeviceInfo(airSwitch, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.OnOffSwitch: - var panel = new Panel() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - panel.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Panel.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", panel.getNewDeviceInfo); - } - UpdateDeviceInfo(panel, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.WindowCoveringDevice: - var curtain = new Rollershade() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - curtain.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Rollershade.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", curtain.getNewDeviceInfo); - } - UpdateDeviceInfo(curtain, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.IASZone: - var ias = new IASZone() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - ias.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<IASZone.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", ias.getNewDeviceInfo); - } - UpdateDeviceInfo(ias, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.Repeater: - var repeater = new Repeater() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - repeater.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Repeater.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", repeater.getNewDeviceInfo); - } - UpdateDeviceInfo(repeater, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.Thermostat: - var ac = new AC() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - ac.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<AC.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", ac.getNewDeviceInfo); - } - UpdateDeviceInfo(ac, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.Transverter: - var transverter = new Transverter() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - transverter.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Transverter.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", transverter.getNewDeviceInfo); - } - UpdateDeviceInfo(transverter, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - case DeviceType.DoorLock: - var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - doorLock.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<DoorLock.NewDeviceInfoData>(jobject["Data"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); - gwa.ReportAction("DeviceInComingRespon", doorLock.getNewDeviceInfo); - } - UpdateDeviceInfo(doorLock, "DeviceInComingRespon"); - UpdateDeviceStatus(gwa); - break; - } + var tempDevice = new CommonDevice() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; + tempDevice.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.NewDeviceInfoData>(jobject["Data"].ToString()); + if (gwa.ReportAction != null) + { + DebugPrintLog("DeviceInComingRespon宸茬粡閫氱煡"); + gwa.ReportAction("DeviceInComingRespon", tempDevice.getNewDeviceInfo); + } + UpdateDeviceInfo(tempDevice, "DeviceInComingRespon"); } #endregion #region 璁惧鍦ㄧ嚎鐘舵�佹洿鏂板弽棣� else if (topic == gatewayID + "/" + "OnlineStatusChange_Respon") { - var deviceID = jobject.Value<int>("Device_ID"); - switch ((DeviceType)(deviceID)) - { - case DeviceType.DimmableLight: - var dimmableLight = new DimmableLight() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - dimmableLight.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", dimmableLight); - } - var lightDimmer = gwa.DeviceList.Find(obj => obj.DeviceID == dimmableLight.DeviceID && obj.DeviceAddr == dimmableLight.DeviceAddr); - if (lightDimmer == null) - { - gwa.DeviceList.Add(dimmableLight); - UpdateDeviceStatus(dimmableLight); - UpdateDeviceInfo(dimmableLight, "OnlineStatusChange"); - } - else - { - if (dimmableLight.DeviceInfo != null) - { - dimmableLight.DeviceInfo.IsOnline = dimmableLight.IsOnline; - } - UpdateDeviceInfo(dimmableLight, "OnlineStatusChange"); - UpdateDeviceStatus(dimmableLight); - } - - break; - case DeviceType.OnOffOutput: - var toggleLight = new ToggleLight() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - toggleLight.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", toggleLight); - } - var toggleInfo = gwa.DeviceList.Find(obj => obj.DeviceID == toggleLight.DeviceID && obj.DeviceAddr == toggleLight.DeviceAddr); - if (toggleInfo == null) - { - gwa.DeviceList.Add(toggleLight); - UpdateDeviceInfo(toggleLight, "OnlineStatusChange"); - UpdateDeviceStatus(toggleLight); - } - else - { - if (toggleLight.DeviceInfo != null) - { - toggleLight.DeviceInfo.IsOnline = toggleLight.IsOnline; - } - UpdateDeviceInfo(toggleLight, "OnlineStatusChange"); - UpdateDeviceStatus(toggleLight); - } - break; - case DeviceType.AirSwitch: - var airSwitch = new AirSwitch() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - airSwitch.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", airSwitch); - } - var airSwitchInfo = gwa.DeviceList.Find(obj => obj.DeviceID == airSwitch.DeviceID && obj.DeviceAddr == airSwitch.DeviceAddr); - if (airSwitchInfo == null) - { - gwa.DeviceList.Add(airSwitch); - UpdateDeviceInfo(airSwitch, "OnlineStatusChange"); - UpdateDeviceStatus(gwa); - } - else - { - if (airSwitchInfo.DeviceInfo != null) - { - airSwitchInfo.DeviceInfo.IsOnline = airSwitchInfo.IsOnline; - } - UpdateDeviceInfo(airSwitchInfo, "OnlineStatusChange"); - UpdateDeviceStatus(airSwitchInfo); - } - break; - case DeviceType.OnOffSwitch: - var panel = new Panel() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - panel.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", panel); - } - var panelInfo = gwa.DeviceList.Find(obj => obj.DeviceID == panel.DeviceID && obj.DeviceAddr == panel.DeviceAddr); - if (panelInfo == null) - { - gwa.DeviceList.Add(panel); - UpdateDeviceInfo(panel, "OnlineStatusChange"); - UpdateDeviceStatus(panel); - } - else - { - if (panelInfo.DeviceInfo != null) - { - panelInfo.DeviceInfo.IsOnline = panelInfo.IsOnline; - } - UpdateDeviceInfo(panelInfo, "OnlineStatusChange"); - UpdateDeviceStatus(panelInfo); - } - break; - case DeviceType.WindowCoveringDevice: - var curtain = new Rollershade() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - curtain.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", curtain); - } - var curtainInfo = gwa.DeviceList.Find(obj => obj.DeviceID == curtain.DeviceID && obj.DeviceAddr == curtain.DeviceAddr); - if (curtainInfo == null) - { - gwa.DeviceList.Add(curtain); - UpdateDeviceInfo(curtain, "OnlineStatusChange"); - UpdateDeviceStatus(gwa); - } - else - { - if (curtain.DeviceInfo != null) - { - curtain.DeviceInfo.IsOnline = curtain.IsOnline; - } - UpdateDeviceStatus(curtain); - UpdateDeviceInfo(curtain, "OnlineStatusChange"); - } - break; - case DeviceType.IASZone: - var ias = new IASZone() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - ias.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", ias); - } - var iasInfo = gwa.DeviceList.Find(obj => obj.DeviceID == ias.DeviceID && obj.DeviceAddr == ias.DeviceAddr); - if (iasInfo == null) - { - gwa.DeviceList.Add(iasInfo); - UpdateDeviceInfo(iasInfo, "OnlineStatusChange"); - UpdateDeviceStatus(gwa); - } - else - { - if (iasInfo.DeviceInfo != null) - { - iasInfo.DeviceInfo.IsOnline = iasInfo.IsOnline; - } - UpdateDeviceInfo(iasInfo, "OnlineStatusChange"); - UpdateDeviceStatus(iasInfo); - } - break; - case DeviceType.Repeater: - var repeater = new Repeater() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - repeater.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", repeater); - } - var repeaterInfo = gwa.DeviceList.Find(obj => obj.DeviceID == repeater.DeviceID && obj.DeviceAddr == repeater.DeviceAddr); - if (repeaterInfo == null) - { - gwa.DeviceList.Add(repeaterInfo); - UpdateDeviceInfo(repeaterInfo, "OnlineStatusChange"); - UpdateDeviceStatus(gwa); - } - else - { - if (repeaterInfo.DeviceInfo != null) - { - repeaterInfo.DeviceInfo.IsOnline = repeaterInfo.IsOnline; - } - UpdateDeviceInfo(repeaterInfo, "OnlineStatusChange"); - UpdateDeviceStatus(repeaterInfo); - } - break; - case DeviceType.Thermostat: - var ac = new AC() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - ac.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", ac); - } - var acInfo = gwa.DeviceList.Find(obj => obj.DeviceID == ac.DeviceID && obj.DeviceAddr == ac.DeviceAddr); - if (acInfo == null) - { - gwa.DeviceList.Add(acInfo); - UpdateDeviceInfo(acInfo, "OnlineStatusChange"); - UpdateDeviceStatus(gwa); - } - else - { - if (acInfo.DeviceInfo != null) - { - acInfo.DeviceInfo.IsOnline = acInfo.IsOnline; - } - UpdateDeviceInfo(acInfo, "OnlineStatusChange"); - UpdateDeviceStatus(acInfo); - } - break; - case DeviceType.Transverter: - var transverter = new Transverter() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - transverter.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", transverter); - } - var transverterInfo = gwa.DeviceList.Find(obj => obj.DeviceID == transverter.DeviceID && obj.DeviceAddr == transverter.DeviceAddr); - if (transverterInfo == null) - { - gwa.DeviceList.Add(transverterInfo); - UpdateDeviceInfo(transverterInfo, "OnlineStatusChange"); - UpdateDeviceStatus(gwa); - } - else - { - if (transverterInfo.DeviceInfo != null) - { - transverterInfo.DeviceInfo.IsOnline = transverterInfo.IsOnline; - } - UpdateDeviceInfo(transverterInfo, "OnlineStatusChange"); - UpdateDeviceStatus(transverterInfo); - } - break; - case DeviceType.DoorLock: - var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - doorLock.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); - if (gwa.ReportAction != null) - { - DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); - gwa.ReportAction("OnlineStatusChange", doorLock); - } - var doorLockInfo = gwa.DeviceList.Find(obj => obj.DeviceID == doorLock.DeviceID && obj.DeviceAddr == doorLock.DeviceAddr); - if (doorLockInfo == null) - { - gwa.DeviceList.Add(doorLockInfo); - UpdateDeviceInfo(doorLockInfo, "OnlineStatusChange"); - UpdateDeviceStatus(gwa); - } - else - { - if (doorLockInfo.DeviceInfo != null) - { - doorLockInfo.DeviceInfo.IsOnline = doorLockInfo.IsOnline; - } - UpdateDeviceInfo(doorLockInfo, "OnlineStatusChange"); - UpdateDeviceStatus(doorLockInfo); - } - break; + var tempDevice = new CommonDevice() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; + tempDevice.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString()); + + if (gwa.ReportAction != null) + { + DebugPrintLog("OnlineStatusChange宸茬粡閫氱煡"); + gwa.ReportAction("OnlineStatusChange", tempDevice); + } + var infoTempDevice = gwa.DeviceList.Find(obj => obj.DeviceID == tempDevice.DeviceID && obj.DeviceAddr == tempDevice.DeviceAddr); + if (infoTempDevice == null) + { + gwa.DeviceList.Add(tempDevice); + UpdateDeviceInfo(tempDevice, "OnlineStatusChange"); + } + else + { + if (infoTempDevice.DeviceInfo != null) + { + infoTempDevice.DeviceInfo.IsOnline = infoTempDevice.IsOnline; + } + UpdateDeviceInfo(infoTempDevice, "OnlineStatusChange"); } } #endregion @@ -4220,219 +4010,23 @@ { foreach (var delD in gatewayTemp.removeDeviceResponseData.DeviceList) { - var deviceID = delD.Device_ID; - switch ((DeviceType)(deviceID)) - { - case DeviceType.OnOffOutput: - var toggleLight = new ToggleLight() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - toggleLight.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<ToggleLight.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (toggleLight.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(toggleLight); - UpdateDeviceInfo(toggleLight, "RemoveDeviceRespon"); - if (toggleLight.removeDeviceResponseData.Result == 0) - { - var infoToggleLight = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == toggleLight.DeviceID && obj.DeviceAddr == toggleLight.DeviceAddr && obj.DeviceEpoint == toggleLight.DeviceEpoint); - if (infoToggleLight != null) - { - gwa.DeviceList.Remove(infoToggleLight); - } - } - } - break; - case DeviceType.AirSwitch: - var airSwitch = new AirSwitch() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - airSwitch.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<AirSwitch.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (airSwitch.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(airSwitch); - UpdateDeviceInfo(airSwitch, "RemoveDeviceRespon"); - if (airSwitch.removeDeviceResponseData.Result == 0) - { - var infoAirSwitch = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == airSwitch.DeviceID && obj.DeviceAddr == airSwitch.DeviceAddr && obj.DeviceEpoint == airSwitch.DeviceEpoint); - if (infoAirSwitch != null) - { - gwa.DeviceList.Remove(infoAirSwitch); - } - } - } - break; - case DeviceType.OnOffSwitch: - var panelObj = new Panel() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - panelObj.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<Panel.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (panelObj.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(panelObj); - UpdateDeviceInfo(panelObj, "RemoveDeviceRespon"); - if (panelObj.removeDeviceResponseData.Result == 0) - { - var infoPanel = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == panelObj.DeviceID && obj.DeviceAddr == panelObj.DeviceAddr && obj.DeviceEpoint == panelObj.DeviceEpoint); - if (infoPanel != null) - { - gwa.DeviceList.Remove(infoPanel); - } - } - } - break; - case DeviceType.WindowCoveringDevice: - var rollershade = new Rollershade() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - rollershade.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<Panel.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (rollershade.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(rollershade); - UpdateDeviceInfo(rollershade, "RemoveDeviceRespon"); - if (rollershade.removeDeviceResponseData.Result == 0) - { - var infoRoller = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == rollershade.DeviceID && obj.DeviceAddr == rollershade.DeviceAddr && obj.DeviceEpoint == rollershade.DeviceEpoint); - if (infoRoller != null) - { - gwa.DeviceList.Remove(infoRoller); - } - } - } - break; - case DeviceType.IASZone: - var ias = new IASZone() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - ias.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<IASZone.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (ias.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(ias); - UpdateDeviceInfo(ias, "RemoveDeviceRespon"); - if (ias.removeDeviceResponseData.Result == 0) - { - var info = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == ias.DeviceID && obj.DeviceAddr == ias.DeviceAddr && obj.DeviceEpoint == ias.DeviceEpoint); - if (info != null) - { - gwa.DeviceList.Remove(info); - } - } - } - break; - case DeviceType.DimmableLight: - var dimmableLight = new DimmableLight() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - dimmableLight.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<DimmableLight.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (dimmableLight.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(dimmableLight); - UpdateDeviceInfo(dimmableLight, "RemoveDeviceRespon"); - if (dimmableLight.removeDeviceResponseData.Result == 0) - { - var info = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == dimmableLight.DeviceID && obj.DeviceAddr == dimmableLight.DeviceAddr && obj.DeviceEpoint == dimmableLight.DeviceEpoint); - if (info != null) - { - gwa.DeviceList.Remove(info); - } - } - } - break; - case DeviceType.Repeater: - var repeater = new Repeater() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - repeater.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<DimmableLight.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (repeater.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(repeater); - UpdateDeviceInfo(repeater, "RemoveDeviceRespon"); - if (repeater.removeDeviceResponseData.Result == 0) - { - var info = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == repeater.DeviceID && obj.DeviceAddr == repeater.DeviceAddr && obj.DeviceEpoint == repeater.DeviceEpoint); - if (info != null) - { - gwa.DeviceList.Remove(info); - } - } - } - break; - case DeviceType.Thermostat: - var ac = new AC() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - ac.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<AC.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (ac.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(ac); - UpdateDeviceInfo(ac, "RemoveDeviceRespon"); - if (ac.removeDeviceResponseData.Result == 0) - { - var info = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == ac.DeviceID && obj.DeviceAddr == ac.DeviceAddr && obj.DeviceEpoint == ac.DeviceEpoint); - if (info != null) - { - gwa.DeviceList.Remove(info); - } - } - } - break; - case DeviceType.Transverter: - var transverter = new Transverter() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - transverter.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<Transverter.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (transverter.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(transverter); - UpdateDeviceInfo(transverter, "RemoveDeviceRespon"); - if (transverter.removeDeviceResponseData.Result == 0) - { - var info = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == transverter.DeviceID && obj.DeviceAddr == transverter.DeviceAddr && obj.DeviceEpoint == transverter.DeviceEpoint); - if (info != null) - { - gwa.DeviceList.Remove(info); - } - } - } - break; - case DeviceType.DoorLock: - var doorLock = new DoorLock() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; - doorLock.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<DoorLock.RemoveDeviceResponseData>(jobject["Data"].ToString()); - if (doorLock.removeDeviceResponseData == null) - { - return; - } - else - { - UpdateDeviceStatus(doorLock); - UpdateDeviceInfo(doorLock, "RemoveDeviceRespon"); - if (doorLock.removeDeviceResponseData.Result == 0) - { - var info = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == doorLock.DeviceID && obj.DeviceAddr == doorLock.DeviceAddr && obj.DeviceEpoint == doorLock.DeviceEpoint); - if (info != null) - { - gwa.DeviceList.Remove(info); - } - } - } - break; + var tempDevice = new CommonDevice() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; + tempDevice.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.RemoveDeviceResponseData>(jobject["Data"].ToString()); + if (tempDevice.removeDeviceResponseData == null) + { + return; + } + else + { + UpdateDeviceInfo(tempDevice, "RemoveDeviceRespon"); + if (tempDevice.removeDeviceResponseData.Result == 0) + { + var infoTempDevice = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == tempDevice.DeviceID && obj.DeviceAddr == tempDevice.DeviceAddr && obj.DeviceEpoint == tempDevice.DeviceEpoint); + if (infoTempDevice != null) + { + gwa.DeviceList.Remove(infoTempDevice); + } + } } } } @@ -4449,74 +4043,53 @@ var tempEpoint = jobject.Value<int>("Epoint"); var dataId = jobject.Value<int>("Data_ID"); + var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; + 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.DimmableLight: - var light = new DimmableLight { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - light.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<DimmableLight.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(light); - UpdateDeviceInfo(light, "DeviceStatusReport"); - break; - case DeviceType.OnOffSwitch: - var lightSwitch = new Panel { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - lightSwitch.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<Panel.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(lightSwitch); - UpdateDeviceInfo(lightSwitch, "DeviceStatusReport"); - break; - case DeviceType.OnOffOutput: - var lighttoggle = new ToggleLight { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - lighttoggle.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<ToggleLight.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(lighttoggle); - UpdateDeviceInfo(lighttoggle, "DeviceStatusReport"); - break; - case DeviceType.AirSwitch: - var airSwitch = new AirSwitch { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - airSwitch.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<AirSwitch.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(airSwitch); - UpdateDeviceInfo(airSwitch, "DeviceStatusReport"); - break; - case DeviceType.WindowCoveringDevice: - var curtain = new Rollershade { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - curtain.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<Rollershade.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(curtain); - UpdateDeviceInfo(curtain, "DeviceStatusReport"); - break; - case DeviceType.OtaDevice: - case DeviceType.OtaPanelDevice: - var ota = new OTADevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - ota.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<OTADevice.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(ota); - UpdateDeviceInfo(ota, "DeviceStatusReport"); - break; - case DeviceType.IASZone: - var ias = new IASZone { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - ias.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<IASZone.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(ias); - UpdateDeviceInfo(ias, "DeviceStatusReport"); - break; - case DeviceType.Repeater: - var repeater = new Repeater { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - repeater.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<Repeater.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(repeater); - UpdateDeviceInfo(repeater, "DeviceStatusReport"); - break; - case DeviceType.Thermostat: - var ac = new AC { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - ac.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<AC.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(ac); - UpdateDeviceInfo(ac, "DeviceStatusReport"); - break; - case DeviceType.Transverter: - var transverter = new Transverter { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - transverter.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<Transverter.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(transverter); - UpdateDeviceInfo(transverter, "DeviceStatusReport"); - break; case DeviceType.DoorLock: - var doorLock = new DoorLock { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; - doorLock.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<DoorLock.DeviceStatusReportData>(jobject["Data"].ToString()); - UpdateDeviceStatus(doorLock); - UpdateDeviceInfo(doorLock, "DeviceStatusReport"); + var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.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"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.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; } } @@ -4537,8 +4110,6 @@ //ias.Save(); gwa.ReportAction("IASInfoReport", ias.iASInfo); } - - UpdateDeviceStatus(ias); UpdateDeviceInfo(ias, "IASInfoReport"); break; } @@ -4653,37 +4224,37 @@ #region 閫昏緫琚皟鐢ㄥ弽棣� else if (topic == gatewayID + "/" + "Logic/Execute_Respon") { - var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; - logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString()); + //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + //logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString()); - if (logic.logicExecuteRespo == null) - { - return; - } - //涓婃姤绫诲瀷閫氱煡 - if (gwa.ReportAction != null) - { - DebugPrintLog("LogicExecuteReport宸茬粡閫氱煡"); - gwa.ReportAction("LogicExecuteReport", logic.logicExecuteRespo); - } + //if (logic.logicExecuteRespo == null) + //{ + // return; + //} + ////涓婃姤绫诲瀷閫氱煡 + //if (gwa.ReportAction != null) + //{ + // DebugPrintLog("LogicExecuteReport宸茬粡閫氱煡"); + // gwa.ReportAction("LogicExecuteReport", logic.logicExecuteRespo); + //} } #endregion #region 鏃堕棿鐐规潯浠舵帹杩熸墽琛� else if (topic == gatewayID + "/" + "Logic/TimingWillArrive") { - var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; - logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString()); + //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; + //logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString()); - if (logic.timingWillArriveData == null) - { - return; - } - //涓婃姤绫诲瀷閫氱煡 - if (gwa.ReportAction != null) - { - DebugPrintLog("TimingWillArrive宸茬粡閫氱煡"); - gwa.ReportAction("TimingWillArrive", logic.timingWillArriveData); - } + //if (logic.timingWillArriveData == null) + //{ + // return; + //} + ////涓婃姤绫诲瀷閫氱煡 + //if (gwa.ReportAction != null) + //{ + // DebugPrintLog("TimingWillArrive宸茬粡閫氱煡"); + // gwa.ReportAction("TimingWillArrive", logic.timingWillArriveData); + //} } #endregion #region 妯″紡瀹夐槻鍔ㄤ綔琚渶缁堟縺娲绘椂鍙戦�佹姤璀︿俊鎭� @@ -4757,22 +4328,18 @@ #region 璁惧璇锋眰APP鑾峰彇鍗囩骇鏁版嵁 else if (topic == gatewayID + "/" + "ZbDataPassthrough") { - var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") }; - gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString()); - if (gatewayTemp.clientDataPassthroughResponseData == null) - { - return; - } - //涓婃姤绫诲瀷閫氱煡 if (gwa.ReportAction != null) - { - DebugPrintLog("DeviceRequestAcUpdateData"); - gwa.ReportAction("DeviceRequestAcUpdateData", gatewayTemp.clientDataPassthroughResponseData); + { + var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString()); + if (clientDataPassthrough != null) + { + DebugPrintLog("DeviceRequestAcUpdateData"); + gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough); + } } } #endregion - DebugPrintLog("缃戝叧杩斿洖鏁版嵁閫氱煡"); } catch (Exception ex) { -- Gitblit v1.8.0