using 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.Core.Client; using MQTTnet; using Shared.Common; using Shared.Phone.UserView; namespace ZigBee.Device { /// ƒ /// ZigBee网关对象 /// [System.Serializable] public class ZbGateway : ZbGatewayData { public ZbGateway() { this.Type = DeviceType.ZbGateway; } #region 网关特殊信息处理 /// /// 主网关 /// /// The main gate way. public static ZbGateway MainGateWay { get { return GateWayList.Find((obj) => { return obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId && obj.getGatewayBaseInfo.IsMainGateWay; }); } } /// /// 主网关 /// [Newtonsoft.Json.JsonIgnore] public bool IsMainGateWay { get { return getGatewayBaseInfo != null && getGatewayBaseInfo.IsMainGateWay; } } /// /// 远程网关 /// /// true if is remote; otherwise, false. public static bool IsRemote { get { return ZigBee.Device.ZbGateway.RemoteMqttClient != null && ZigBee.Device.ZbGateway.RemoteMqttClient.IsConnected; } } /// /// 网关保存路径 /// /// The file path. [Newtonsoft.Json.JsonIgnore] public override string FilePath { get { var deviceType = Type.ToString(); var fileName = "Gateway_" + deviceType + "_" + this.getGatewayBaseInfo?.gwID; return fileName; } } /// /// 局域网加密密码 /// string password; /// /// 局域网加密密钥 /// [Newtonsoft.Json.JsonIgnore] public string Password { get { if (password == null) { password = Guid.NewGuid().ToString().Substring(0, 16); } return password; } } #region variable /// /// 远程连接成功时的时间 /// public static DateTime LoginRemoteDateTime = DateTime.Now; /// /// 同步到远程的当前时间戳 /// Re public static ulong CurrentTimeStamp { get { return RemoteTimeStamp + (ulong)(DateTime.Now - LoginRemoteDateTime).TotalSeconds; } } /// /// 远程连接成功时的时间戳 /// public static ulong RemoteTimeStamp; /// /// 网关是否加密 /// [Newtonsoft.Json.JsonIgnore] public bool IsEncry; /// /// 网关当前公钥 /// [Newtonsoft.Json.JsonIgnore] public string PubKey; /// /// 所有的网关列表 /// [Newtonsoft.Json.JsonIgnore] public static List GateWayList = new List(); //当前网关中的设备列表 [Newtonsoft.Json.JsonIgnore] public List DeviceList = new List(); /// /// 所有网关中的设备列表 /// [Newtonsoft.Json.JsonIgnore] public List AllGatewayDeviceList = new List(); /// /// 网关中场景列表 /// 一个场景中包含所有信息,包括场景设备信息 /// [Newtonsoft.Json.JsonIgnore] public static List AllSceneList = new List(); /// /// 网关中场景的设备列表 /// [Newtonsoft.Json.JsonIgnore] public List SceneDeviceList = new List(); /// /// 网关中逻辑列表 /// [Newtonsoft.Json.JsonIgnore] public static List LogicList = new List(); /// /// 网关中hdl私有按键绑定列表 /// [Newtonsoft.Json.JsonIgnore] public List HdlButtonList = new List(); //网关中新的设备列表 [Newtonsoft.Json.JsonIgnore] public List ListNewDeviceInfoData = new List(); /// /// 私有按键信息列表 /// [Newtonsoft.Json.JsonIgnore] public System.Collections.Generic.Dictionary hdlButtonInfoList = new Dictionary(); /// /// 传感器信息列表 /// [Newtonsoft.Json.JsonIgnore] public System.Collections.Generic.Dictionary sceneTaskInfoList = new Dictionary(); #region action variable /// /// 接收数据后回调 /// [Newtonsoft.Json.JsonIgnore] Action action; /// /// 设置数据回调 /// public void SetAction(Action action, int timeOut = 1000) { this.action = action; } /// /// 网关推送数据 /// 第一个参数:如果为 DeviceInComingRespon:设备新上报 /// 第一个参数:如果为 DeviceStatusReport:设备上报 /// 第一个参数:如果为 IASInfoReport:IAS安防信息上报 /// 第一个参数:如果为 DeviceStatusReport:设备上报 /// 第一个参数:如果为 EnOrWithdrawSucceedReport:通过外部方式布防撤防成功时报告 /// 第一个参数:如果为 DownloadFileProgress:下载进度 /// 第一个参数:如果为 CordinatorUpgradePercent:协调器升级百分比 /// 第一个参数:如果为 DeviceUpgradePercent:节点设备升级百分比 /// 第一个参数:如果为 VirtualDriveUpgrade:虚拟设备升级进度 /// 第一个参数:如果为 ZoneTriggerReport:防区被触发时报告 /// 第一个参数:如果为 LogicExecuteReport:逻辑被调用反馈 /// 第一个参数:如果为 TimingWillArrive:时间点条件推迟执行 /// para>第一个参数: 如果为 ModeTriggerReport:模式安防动作被最终激活时发送报警信息 /// 第一个参数:如果为 EnOrWithdrawSucceedReport:通过外部方式布防撤防成功时报告息 /// 第一个参数:如果为 PushTargetInfoReport:胁迫密码撤防时短信推送 /// 第一个参数:如果为 DeviceDefaultAck:节点设备默认反馈 /// 第一个参数:如果为 DDevice/IsGetEpointInfo:有新设备加入zigbee网络反馈设备请求APP获取升级数据 /// 第一个参数:如果为 Device/DeviceJoinZbNet:获取新设备所有端点信息是否成功反馈 /// 第一个参数:如果为 DeviceRequestAcUpdateData: 设备请求空调发升级数据 /// "已经通知");//已经通知"); /// [Newtonsoft.Json.JsonIgnore] public Action ReportAction; /// /// 云端通讯错误数据上报 ///"ForwardGatewayNoOnLine", "当前操作的网关不在线" ///"AppTimeOut", "从云端获取数据超时,请重新获取" ///"AppNoLogin", "登录过期,请重新登录" /// [Newtonsoft.Json.JsonIgnore] public Action CloudErrorAction; /// /// 网关文件流内容通知 /// [Newtonsoft.Json.JsonIgnore] public Action FileContentAction; /// /// 网关回复数据内容通知 /// [Newtonsoft.Json.JsonIgnore] public Action GwResDataAction; /// /// 与网关通讯时发送和接收数据通知 /// [Newtonsoft.Json.JsonIgnore] public Action Actions; #endregion #endregion #endregion #region 网关API #region 网关信息 /// ///获取网关版本信息 /// gateway:当前网关 /// public async System.Threading.Tasks.Task GetZbGwVersionInfoAsync() { return await System.Threading.Tasks.Task.Run(async () => { GetGwVersionAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GetGwVersionAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GetGwVersionAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "GetZbGwVersionRespon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; gatewayTemp.getGwVersion = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.getGwVersion == null) { d = new GetGwVersionAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GetGwVersionAllData { getGwVersion = gatewayTemp.getGwVersion }; AppVersion = gatewayTemp.getGwVersion.AppVersion; ZigbeeVersion = gatewayTemp.getGwVersion.ZigbeeVersion; //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 获取网关信息 /// /// 获取网关信息 /// gateway:当前网关 /// public async System.Threading.Tasks.Task GetZbGwInfoAsync() { return await System.Threading.Tasks.Task.Run(async () => { GetGwAllData data = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; if (topic == gatewayID + "/" + "GetZbGwInfo_Respon") { var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; gatewayTemp.getGwInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.getGwInfo == null) { data = new GetGwAllData { errorMessageBase = "网关返回的数据为空" }; } else { data = new GetGwAllData { getGwData = gatewayTemp.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 读取协调器MAC地址. /// /// 读取协调器MAC地址/端点默认是08 /// public async System.Threading.Tasks.Task ReadMacAsync() { return await System.Threading.Tasks.Task.Run(async () => { GetMacResponData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GetMacResponData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GetMacResponData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbGw/GetMac_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject(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 修改网关名称 /// /// 修改网关名称 ///gwName:网关名称 /// public async System.Threading.Tasks.Task GwReNameAsync(string gwName) { return await System.Threading.Tasks.Task.Run(async () => { GwReNameAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GwReNameAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GwReNameAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "GwReName_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; gatewayTemp.gwRename = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.gwRename == null) { d = new GwReNameAllData { errorMessageBase = "网关返回的数据为空" }; } else { d = new GwReNameAllData { gwReNameData = gatewayTemp.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 /// /// 设定网关住宅id /// homeId:住宅id /// public async System.Threading.Tasks.Task GwSetHomeIdAsync(string homeId) { return await System.Threading.Tasks.Task.Run(async () => { GwSetHomeIdAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GwSetHomeIdAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GwSetHomeIdAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "GwSetHomeId_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; gatewayTemp.gwSetHomeId = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.gwSetHomeId == null) { d = new GwSetHomeIdAllData { errorMessageBase = "网关返回的数据为空" }; } else { d = new GwSetHomeIdAllData { gwSetHomeIdData = gatewayTemp.gwSetHomeId }; DebugPrintLog($"UI收到通知后的主题_{ topic}"); } } }; Actions += action; DebugPrintLog("GwReName_Actions 启动" + System.DateTime.Now.ToString()); try { var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } }; var data = new JObject { { "HomeId", homeId } }; jObject.Add("Data", data); Send("GwSetHomeId", 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 获取已入网设备信息 /// /// 获取网关设备信息(注意,这个接口会被去掉) /// public async System.Threading.Tasks.Task> GetGwDeviceList() { DeviceList.Clear(); return await System.Threading.Tasks.Task.Run((Func>>)(async () => { var dateTime = DateTime.Now; bool canBreak = false; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "DeviceInfoRespon") { dateTime = DateTime.Now; var totalNum = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"]["TotalNum"].ToString()); if (totalNum == 0) { canBreak = true; return; } var deviceID = jobject.Value("Device_ID"); switch ((DeviceType)(deviceID)) { //case DeviceType.DimmableLight: // var dimmableLight = new DimmableLight() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; // dimmableLight.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); // if (dimmableLight.DeviceInfo == null) // { // return; // } // var light = DeviceList.Find(obj => obj.DeviceID == dimmableLight.DeviceID && obj.DeviceAddr == dimmableLight.DeviceAddr && obj.DeviceEpoint == dimmableLight.DeviceEpoint); // if (light == null) // { // DeviceList.Add(dimmableLight); // dimmableLight.DeviceName = dimmableLight.DeviceInfo.MacName; // dimmableLight.DeviceEpointName = dimmableLight.DeviceInfo.DeviceName; // dimmableLight.ImgVersion = dimmableLight.DeviceInfo.ImgVersion; // dimmableLight.HwVersion = dimmableLight.DeviceInfo.HwVersion; // dimmableLight.IsOnline = dimmableLight.DeviceInfo.IsOnline; // dimmableLight.DriveCode = dimmableLight.DeviceInfo.DriveCode; // dimmableLight.ImgTypeId = dimmableLight.DeviceInfo.ImgTypeId; // dimmableLight.IasDeviceType = dimmableLight.DeviceInfo.DeviceType; // dimmableLight.Profile = dimmableLight.DeviceInfo.Profile; // dimmableLight.InClusterList = dimmableLight.DeviceInfo.InClusterList; // dimmableLight.OutClusterList = dimmableLight.DeviceInfo.OutClusterList; // dimmableLight.AttributeStatus = dimmableLight.DeviceInfo.AttributeStatus; // //dimmableLight.Save(); // } // else // { // light.DeviceInfo = dimmableLight.DeviceInfo; // light.DeviceName = dimmableLight.DeviceInfo.MacName; // light.DeviceEpointName = dimmableLight.DeviceInfo.DeviceName; // light.ImgVersion = dimmableLight.DeviceInfo.ImgVersion; // light.HwVersion = dimmableLight.DeviceInfo.HwVersion; // light.IsOnline = dimmableLight.DeviceInfo.IsOnline; // light.DriveCode = dimmableLight.DeviceInfo.DriveCode; // light.ImgTypeId = dimmableLight.DeviceInfo.ImgTypeId; // light.IasDeviceType = dimmableLight.DeviceInfo.DeviceType; // light.Profile = dimmableLight.DeviceInfo.Profile; // light.InClusterList = dimmableLight.DeviceInfo.InClusterList; // light.OutClusterList = dimmableLight.DeviceInfo.OutClusterList; // light.AttributeStatus = dimmableLight.DeviceInfo.AttributeStatus; // //dimmableLight.ReSave(); // } // DebugPrintLog($"UI收到通知后的主题_{ topic}"); // break; //case DeviceType.OnOffSwitch: // var panel = new Panel() { Time = jobject.Value("Time"), DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; // panel.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); // if (panel.DeviceInfo == null) // { // return; // } // var panelInfo = DeviceList.Find(obj => obj.DeviceID == panel.DeviceID && obj.DeviceAddr == panel.DeviceAddr && obj.DeviceEpoint == panel.DeviceEpoint); // if (panelInfo == null) // { // DeviceList.Add(panel); // panel.DeviceName = panel.DeviceInfo.MacName; // panel.DeviceEpointName = panel.DeviceInfo.DeviceName; // panel.ImgTypeId = panel.DeviceInfo.ImgTypeId; // panel.ImgVersion = panel.DeviceInfo.ImgVersion; // panel.HwVersion = panel.DeviceInfo.HwVersion; // panel.IasDeviceType = panel.DeviceInfo.DeviceType; // panel.IsOnline = panel.DeviceInfo.IsOnline; // panel.DriveCode = panel.DeviceInfo.DriveCode; // panel.Profile = panel.DeviceInfo.Profile; // panel.InClusterList = panel.DeviceInfo.InClusterList; // panel.OutClusterList = panel.DeviceInfo.OutClusterList; // panel.AttributeStatus = panel.DeviceInfo.AttributeStatus; // //panel.Save(); // } // else // { // panelInfo.DeviceInfo = panel.DeviceInfo; // panelInfo.DeviceName = panel.DeviceInfo.MacName; // panelInfo.DeviceEpointName = panel.DeviceInfo.DeviceName; // panelInfo.ImgVersion = panel.DeviceInfo.ImgVersion; // panelInfo.HwVersion = panel.DeviceInfo.HwVersion; // panelInfo.IsOnline = panel.DeviceInfo.IsOnline; // panelInfo.DriveCode = panel.DeviceInfo.DriveCode; // panelInfo.IasDeviceType = panel.DeviceInfo.DeviceType; // panelInfo.Profile = panel.DeviceInfo.Profile; // panelInfo.ImgTypeId = panel.DeviceInfo.ImgTypeId; // panelInfo.InClusterList = panel.DeviceInfo.InClusterList; // panelInfo.OutClusterList = panel.DeviceInfo.OutClusterList; // panelInfo.AttributeStatus = panel.DeviceInfo.AttributeStatus; // //panel.ReSave(); // } // DebugPrintLog($"UI收到通知后的主题_{ topic}"); // break; //case DeviceType.OnOffOutput: // var toggleLight = new ToggleLight() { Time = jobject.Value("Time"), DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; // toggleLight.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); // if (toggleLight.DeviceInfo == null) // { // return; // } // var toggleLightInfo = DeviceList.Find(obj => obj.DeviceID == toggleLight.DeviceID && obj.DeviceAddr == toggleLight.DeviceAddr && obj.DeviceEpoint == toggleLight.DeviceEpoint); // if (toggleLightInfo == null) // { // DeviceList.Add(toggleLight); // toggleLight.DeviceName = toggleLight.DeviceInfo.MacName; // toggleLight.DeviceEpointName = toggleLight.DeviceInfo.DeviceName; // toggleLight.ImgVersion = toggleLight.DeviceInfo.ImgVersion; // toggleLight.HwVersion = toggleLight.DeviceInfo.HwVersion; // toggleLight.IsOnline = toggleLight.DeviceInfo.IsOnline; // toggleLight.DriveCode = toggleLight.DeviceInfo.DriveCode; // toggleLight.IasDeviceType = toggleLight.DeviceInfo.DeviceType; // toggleLight.Profile = toggleLight.DeviceInfo.Profile; // toggleLight.ImgTypeId = toggleLight.DeviceInfo.ImgTypeId; // toggleLight.InClusterList = toggleLight.DeviceInfo.InClusterList; // toggleLight.OutClusterList = toggleLight.DeviceInfo.OutClusterList; // toggleLight.AttributeStatus = toggleLight.DeviceInfo.AttributeStatus; // //toggleLight.Save(); // } // else // { // toggleLightInfo.DeviceName = toggleLight.DeviceInfo.MacName; // toggleLightInfo.DeviceEpointName = toggleLight.DeviceInfo.DeviceName; // toggleLightInfo.ImgVersion = toggleLight.DeviceInfo.ImgVersion; // toggleLightInfo.HwVersion = toggleLight.DeviceInfo.HwVersion; // toggleLightInfo.IsOnline = toggleLight.DeviceInfo.IsOnline; // toggleLightInfo.DriveCode = toggleLight.DeviceInfo.DriveCode; // toggleLightInfo.IasDeviceType = toggleLight.DeviceInfo.DeviceType; // toggleLightInfo.Profile = toggleLight.DeviceInfo.Profile; // toggleLightInfo.ImgTypeId = toggleLight.DeviceInfo.ImgTypeId; // toggleLightInfo.InClusterList = toggleLight.DeviceInfo.InClusterList; // toggleLightInfo.OutClusterList = toggleLight.DeviceInfo.OutClusterList; // toggleLightInfo.AttributeStatus = toggleLight.DeviceInfo.AttributeStatus; // toggleLightInfo.DeviceInfo = toggleLight.DeviceInfo; // //toggleLightInfo.ReSave(); // } // DebugPrintLog($"UI收到通知后的主题_{ topic}"); // break; //case DeviceType.AirSwitch: // var airSwitch = new AirSwitch() { Time = jobject.Value("Time"), DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; // airSwitch.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); // if (airSwitch.DeviceInfo == null) // { // return; // } // var airSwitchInfo = DeviceList.Find(obj => obj.DeviceID == airSwitch.DeviceID && obj.DeviceAddr == airSwitch.DeviceAddr && obj.DeviceEpoint == airSwitch.DeviceEpoint); // if (airSwitchInfo == null) // { // DeviceList.Add(airSwitch); // airSwitch.DeviceName = airSwitch.DeviceInfo.MacName; // airSwitch.DeviceEpointName = airSwitch.DeviceInfo.DeviceName; // airSwitch.ImgVersion = airSwitch.DeviceInfo.ImgVersion; // airSwitch.HwVersion = airSwitch.DeviceInfo.HwVersion; // airSwitch.IsOnline = airSwitch.DeviceInfo.IsOnline; // airSwitch.DriveCode = airSwitch.DeviceInfo.DriveCode; // airSwitch.IasDeviceType = airSwitch.DeviceInfo.DeviceType; // airSwitch.Profile = airSwitch.DeviceInfo.Profile; // airSwitch.ImgTypeId = airSwitch.DeviceInfo.ImgTypeId; // airSwitch.InClusterList = airSwitch.DeviceInfo.InClusterList; // airSwitch.OutClusterList = airSwitch.DeviceInfo.OutClusterList; // airSwitch.AttributeStatus = airSwitch.DeviceInfo.AttributeStatus; // //airSwitch.Save(); // } // else // { // airSwitchInfo.DeviceName = airSwitch.DeviceInfo.MacName; // airSwitchInfo.DeviceEpointName = airSwitch.DeviceInfo.DeviceName; // airSwitchInfo.ImgVersion = airSwitch.DeviceInfo.ImgVersion; // airSwitchInfo.HwVersion = airSwitch.DeviceInfo.HwVersion; // airSwitchInfo.IsOnline = airSwitch.DeviceInfo.IsOnline; // airSwitchInfo.DriveCode = airSwitch.DeviceInfo.DriveCode; // airSwitchInfo.IasDeviceType = airSwitch.DeviceInfo.DeviceType; // airSwitchInfo.Profile = airSwitch.DeviceInfo.Profile; // airSwitchInfo.ImgTypeId = airSwitch.DeviceInfo.ImgTypeId; // airSwitchInfo.InClusterList = airSwitch.DeviceInfo.InClusterList; // airSwitchInfo.OutClusterList = airSwitch.DeviceInfo.OutClusterList; // airSwitchInfo.AttributeStatus = airSwitch.DeviceInfo.AttributeStatus; // airSwitchInfo.DeviceInfo = airSwitch.DeviceInfo; // // airSwitchInfo.ReSave(); // } // DebugPrintLog($"UI收到通知后的主题_{ topic}"); // break; //case DeviceType.WindowCoveringDevice: // var windowCovering = new Rollershade() { DeviceID = jobject.Value((object)"Device_ID"), DeviceAddr = jobject.Value((object)"DeviceAddr"), DeviceEpoint = jobject.Value((object)"Epoint"), DataID = jobject.Value((object)"Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; // windowCovering.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); // if (windowCovering.DeviceInfo == null) // { // return; // } // var wc = DeviceList.Find(obj => obj.DeviceID == windowCovering.DeviceID && obj.DeviceAddr == windowCovering.DeviceAddr && obj.DeviceEpoint == windowCovering.DeviceEpoint); // if (wc == null) // { // DeviceList.Add(windowCovering); // windowCovering.DeviceName = windowCovering.DeviceInfo.MacName; // windowCovering.DeviceEpointName = windowCovering.DeviceInfo.DeviceName; // windowCovering.ImgVersion = windowCovering.DeviceInfo.ImgVersion; // windowCovering.HwVersion = windowCovering.DeviceInfo.HwVersion; // windowCovering.IsOnline = windowCovering.DeviceInfo.IsOnline; // windowCovering.DriveCode = windowCovering.DeviceInfo.DriveCode; // windowCovering.IasDeviceType = windowCovering.DeviceInfo.DeviceType; // windowCovering.Profile = windowCovering.DeviceInfo.Profile; // windowCovering.ImgTypeId = windowCovering.DeviceInfo.ImgTypeId; // windowCovering.InClusterList = windowCovering.DeviceInfo.InClusterList; // windowCovering.OutClusterList = windowCovering.DeviceInfo.OutClusterList; // windowCovering.AttributeStatus = windowCovering.DeviceInfo.AttributeStatus; // //windowCovering.Save(); // } // else // { // wc.DeviceName = windowCovering.DeviceInfo.MacName; // wc.DeviceEpointName = windowCovering.DeviceInfo.DeviceName; // wc.DeviceInfo = windowCovering.DeviceInfo; // wc.ImgVersion = windowCovering.DeviceInfo.ImgVersion; // wc.HwVersion = windowCovering.DeviceInfo.HwVersion; // wc.IsOnline = windowCovering.DeviceInfo.IsOnline; // wc.DriveCode = windowCovering.DeviceInfo.DriveCode; // wc.IasDeviceType = windowCovering.DeviceInfo.DeviceType; // wc.Profile = windowCovering.DeviceInfo.Profile; // wc.ImgTypeId = windowCovering.DeviceInfo.ImgTypeId; // wc.InClusterList = windowCovering.DeviceInfo.InClusterList; // wc.OutClusterList = windowCovering.DeviceInfo.OutClusterList; // wc.AttributeStatus = windowCovering.DeviceInfo.AttributeStatus; // // wc.ReSave(); // } // DebugPrintLog($"UI收到通知后的主题_{ topic}"); // break; //case DeviceType.IASZone: // var ias = new IASZone() { Time = jobject.Value("Time"), DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; // ias.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); // if (ias.DeviceInfo == null) // { // return; // } // var infoIAS = DeviceList.Find(obj => obj.DeviceID == ias.DeviceID && obj.DeviceAddr == ias.DeviceAddr && obj.DeviceEpoint == ias.DeviceEpoint); // if (infoIAS == null) // { // DeviceList.Add(ias); // ias.DeviceName = ias.DeviceInfo.MacName; // ias.DeviceEpointName = ias.DeviceInfo.DeviceName; // ias.ImgVersion = ias.DeviceInfo.ImgVersion; // ias.HwVersion = ias.DeviceInfo.HwVersion; // ias.IsOnline = ias.DeviceInfo.IsOnline; // ias.DriveCode = ias.DeviceInfo.DriveCode; // ias.IasDeviceType = ias.DeviceInfo.DeviceType; // ias.Profile = ias.DeviceInfo.Profile; // ias.ImgTypeId = ias.DeviceInfo.ImgTypeId; // ias.InClusterList = ias.DeviceInfo.InClusterList; // ias.OutClusterList = ias.DeviceInfo.OutClusterList; // ias.AttributeStatus = ias.DeviceInfo.AttributeStatus; // //ias.Save(); // } // else // { // infoIAS.DeviceName = ias.DeviceInfo.MacName; // infoIAS.DeviceEpointName = ias.DeviceInfo.DeviceName; // infoIAS.DeviceEpointName = ias.DeviceInfo.DeviceName; // infoIAS.ImgVersion = ias.DeviceInfo.ImgVersion; // infoIAS.HwVersion = ias.DeviceInfo.HwVersion; // infoIAS.IsOnline = ias.DeviceInfo.IsOnline; // infoIAS.DriveCode = ias.DeviceInfo.DriveCode; // infoIAS.IasDeviceType = ias.DeviceInfo.DeviceType; // infoIAS.Profile = ias.DeviceInfo.Profile; // infoIAS.ImgTypeId = ias.DeviceInfo.ImgTypeId; // infoIAS.InClusterList = ias.DeviceInfo.InClusterList; // infoIAS.OutClusterList = ias.DeviceInfo.OutClusterList; // infoIAS.AttributeStatus = ias.DeviceInfo.AttributeStatus; // infoIAS.DeviceInfo = ias.DeviceInfo; // //ias.ReSave(); // } // DebugPrintLog($"UI收到通知后的主题_{ topic}"); // break; //case DeviceType.OtaDevice: //case DeviceType.OtaPanelDevice: //var ota = new OTADevice() { Time = jobject.Value("Time"), DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; //ota.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); //if (ota.DeviceInfo == null) //{ // return; //} //var infoOta = DeviceList.Find(obj => obj.DeviceID == ota.DeviceID && obj.DeviceAddr == ota.DeviceAddr && obj.DeviceEpoint == ota.DeviceEpoint); //if (infoOta == null) //{ // DeviceList.Add(ota); // ota.DeviceName = ota.DeviceInfo.MacName; // ota.DeviceEpointName = ota.DeviceInfo.DeviceName; // ota.ImgVersion = ota.DeviceInfo.ImgVersion; // ota.HwVersion = ota.DeviceInfo.HwVersion; // ota.IsOnline = ota.DeviceInfo.IsOnline; // ota.DriveCode = ota.DeviceInfo.DriveCode; // ota.IasDeviceType = ota.DeviceInfo.DeviceType; // ota.Profile = ota.DeviceInfo.Profile; // ota.ImgTypeId = ota.DeviceInfo.ImgTypeId; // ota.InClusterList = ota.DeviceInfo.InClusterList; // ota.OutClusterList = ota.DeviceInfo.OutClusterList; // ota.AttributeStatus = ota.DeviceInfo.AttributeStatus; // //ota.Save(); //} //else //{ // infoOta.DeviceName = ota.DeviceInfo.MacName; // infoOta.DeviceEpointName = ota.DeviceInfo.DeviceName; // infoOta.DeviceEpointName = ota.DeviceInfo.DeviceName; // infoOta.ImgVersion = ota.DeviceInfo.ImgVersion; // infoOta.HwVersion = ota.DeviceInfo.HwVersion; // infoOta.IsOnline = ota.DeviceInfo.IsOnline; // infoOta.DriveCode = ota.DeviceInfo.DriveCode; // infoOta.IasDeviceType = ota.DeviceInfo.DeviceType; // infoOta.Profile = ota.DeviceInfo.Profile; // infoOta.ImgTypeId = ota.DeviceInfo.ImgTypeId; // infoOta.InClusterList = ota.DeviceInfo.InClusterList; // infoOta.OutClusterList = ota.DeviceInfo.OutClusterList; // infoOta.AttributeStatus = ota.DeviceInfo.AttributeStatus; // infoOta.DeviceInfo = ota.DeviceInfo; // //ota.ReSave(); //} //DebugPrintLog($"UI收到通知后的主题_{ topic}"); //break; //case DeviceType.Thermostat: //var thermostat = new ThermostatObj() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gateway.getGatewayBaseInfo.gwID }; //thermostat.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); //if (thermostat.DeviceInfo == null) //{ // return; //} //var ther = gateway.DeviceList.Find(obj => obj.DeviceID == thermostat.DeviceID && obj.DeviceAddr == thermostat.DeviceAddr && obj.DeviceEpoint == thermostat.DeviceEpoint); //if (ther == null) //{ // gateway.DeviceList.Add(thermostat); // thermostat.DeviceName = thermostat.DeviceInfo.DeviceName; // IO.LocalFileUtils.SaveDeviceInfo(thermostat, thermostat.DeviceEpoint.ToString()); //} //else //{ // ther.DeviceName = thermostat.DeviceInfo.DeviceName; // ther.DeviceInfo = thermostat.DeviceInfo; // ZigBee.IO.LocalFileUtils.SaveDeviceInfo(ther, ther.DeviceEpoint.ToString()); //} //break; //case DeviceType.TemperatureSensor: //var temperatureSensor = new TemperatureSensor() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gateway.getGatewayBaseInfo.gwID }; //temperatureSensor.DeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); //if (temperatureSensor.DeviceInfo == null) //{ // return; //} //var ts = gateway.DeviceList.Find(obj => obj.DeviceID == temperatureSensor.DeviceID && obj.DeviceAddr == temperatureSensor.DeviceAddr && obj.DeviceEpoint == temperatureSensor.DeviceEpoint); //if (ts == null) //{ // gateway.DeviceList.Add(temperatureSensor); // temperatureSensor.DeviceName = temperatureSensor.DeviceInfo.DeviceName; // IO.LocalFileUtils.SaveDeviceInfo(temperatureSensor, temperatureSensor.DeviceEpoint.ToString()); //} //else //{ // ts.DeviceName = temperatureSensor.DeviceInfo.DeviceName; // ts.DeviceInfo = temperatureSensor.DeviceInfo; // IO.LocalFileUtils.SaveDeviceInfo(ts, ts.DeviceEpoint.ToString()); //} //break; } } else if (topic == gatewayID + "/" + "DeviceInfoResponEnd") { canBreak = true; } }; Actions += action; DebugPrintLog("DeviceInfo Actions 启动" + "_" + System.DateTime.Now.ToString()); try { var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 93 } }; Send("GetDeviceInfo", jObject.ToString()); } catch { } while (canBreak == false && (DateTime.Now - dateTime).TotalMilliseconds < 6000) { await System.Threading.Tasks.Task.Delay(10); } Actions -= action; DebugPrintLog("DeviceInfo_Actions 退出" + System.DateTime.Now.ToString()); return DeviceList; })); } #endregion #region 获取网关记录的设备属性状态 /// ///获取网关记录的设备属性状态 /// public async System.Threading.Tasks.Task GetStatusRecordAsync(string deviceAddr, int deviceEpoint) { return await System.Threading.Tasks.Task.Run(async () => { GetStatusRecordAllInfo d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GetStatusRecordAllInfo { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GetStatusRecordAllInfo { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "GetStatusRecord_Respon") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; gatewayTemp.getStatusRecordInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.getStatusRecordInfo == null) { d = new GetStatusRecordAllInfo { errorMessageBase = "网关返回的数据为空" }; } else { d = new GetStatusRecordAllInfo { getStatusRecordInfo = gatewayTemp.getStatusRecordInfo }; DebugPrintLog($"UI收到通知后的主题_{ topic}"); } } }; Actions += action; DebugPrintLog("GetStatusRecord_Actions 启动" + System.DateTime.Now.ToString()); try { var jObject = new JObject { { "DeviceAddr", deviceAddr }, { "Epoint", deviceEpoint }, { "Cluster_ID", 0 }, { "Command", 80 } }; Send("GetStatusRecord", 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 GetStatusRecordAllInfo { errorMessageBase = " 回复超时,请重新操作" }; } Actions -= action; DebugPrintLog("GetStatusRecord_Actions 退出" + System.DateTime.Now.ToString()); return d; }); } #endregion #region 允许设备入网 /// /// 搜索新入网的设备(允许设备入网) /// Time:0-255,0:关闭搜索,255:一直开启 /// public async void AddNewDeviceToGateway(int time = 3) { await System.Threading.Tasks.Task.Run(async () => { CommonDevice commonDev = null; Action 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 协调器恢复出厂设置 /// ///zigbee协调器恢复出厂设置 /// DelAllInfo:0/1 /// 0:仅将协调器恢复出厂设置,不删除网关保存的设备列表,组列表,场景列表等信息。 ///1:将协调器恢复出厂设置,并删除网关保存的设备列表,组列表,场景列表等信息。 /// public void GwOperationReset(int delAllInfo) { Action 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 网关恢复出厂设置 /// ///网关恢复出厂设置 /// 该指令用于网关linux系统恢复出厂设置。恢复出厂设置后,系统将自动重启 /// 0:命令已接收,系统即将恢复出厂并重启。 /// public async System.Threading.Tasks.Task GwLinuxResetAsync() { return await System.Threading.Tasks.Task.Run(async () => { GwLinuxResetResponData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GwLinuxResetResponData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GwLinuxResetResponData { errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "GwLinuxReset_Respon") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var result = Newtonsoft.Json.JsonConvert.DeserializeObject(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 重启网关系统 /// ///重启网关系统 /// 发送该指令将使网关主动断开所有mqtt连接并执行重启。重启时间大约需要60秒 /// 返回值是0:命令已接收,系统即将重启。 /// public async System.Threading.Tasks.Task GwRebootAsync() { return await System.Threading.Tasks.Task.Run(async () => { GwRebootResponAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GwRebootResponAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GwRebootResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "GwReboot_Respon") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var result = Newtonsoft.Json.JsonConvert.DeserializeObject(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 网关和协调器升级 /// ///保存zigbee协调器组网信息 /// public async System.Threading.Tasks.Task SaveNVFile(string imageName, string imagePath) { return await System.Threading.Tasks.Task.Run(async () => { SaveNVFileResponseAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new SaveNVFileResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new SaveNVFileResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbGwOperation/SaveNVFile_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.zbGwOperationSaveNVFileData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.zbGwOperationSaveNVFileData == null) { d = new SaveNVFileResponseAllData { errorMessageBase = "网关返回的数据为空" }; } else { d = new SaveNVFileResponseAllData { saveNVFileResponseData = gatewayTemp.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 协调器恢复组网信息 /// ///协调器恢复组网信息 /// public async System.Threading.Tasks.Task RestoreNV(string imageName, string imagePath) { return await System.Threading.Tasks.Task.Run(async () => { RestoreNVAllDtta d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new RestoreNVAllDtta { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new RestoreNVAllDtta { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbGwOperation/RestoreNV_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject(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 获取协调器当前信道. /// /// 获取协调器当前信道 /// public async System.Threading.Tasks.Task GetChannelAsync() { return await System.Threading.Tasks.Task.Run(async () => { GwGetChannelResponData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new GwGetChannelResponData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new GwGetChannelResponData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbGw/GetChannel_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; var channel = Newtonsoft.Json.JsonConvert.DeserializeObject(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 更改协调器当前信道 /// /// 更改协调器当前信道 /// Channel:要更改的信道: 11 -26 /// public async System.Threading.Tasks.Task ChangeChannelAsync(int channel) { return await System.Threading.Tasks.Task.Run(async () => { ChangeChannelResponAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new ChangeChannelResponAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new ChangeChannelResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbGw/ChangeChannel_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; var tempInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(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(数据是十六进制形式的字符串) /// ///客户端向节点设备透传数据,(数据是十六进制形式的字符串) /// deviceAddr:设备的mac地址 /// devicePoint:设备端口号 /// PassData:透传的数据,最大256个字符,也就是透传128个字节 /// public async void ClientDataPassthrough(string deviceAddr, int devicePoint, string passData) { await System.Threading.Tasks.Task.Run(async () => { Action 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(数据是二进制流) /// /// 客户端发送文件流到网关(数据是二进制流) /// passData: 透传数据 ///Result 0: 数据写入成功,请求发送下一个数据包 ///Result1:数据写入失败 ///Result2:数据解析错误 ///Result3:发送数据大小超出限制 /// public async System.Threading.Tasks.Task ClientDataPassthroughBytesAsync(string deviceAddr, int devicePoint, long dataLength, byte[] passData) { Panel.PanelSwitchLevelInfo result = null; if (Gateway == null) { result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "当前没有网关" }; return result; } return await System.Threading.Tasks.Task.Run(async () => { Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "网关错误回复,且数据是空" }; } else { result = new Panel.PanelSwitchLevelInfo { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbDataPassthrough") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.clientDataPassthroughResponseData == null) { result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "网关返回的数据为空" }; } else { if (gatewayTemp.clientDataPassthroughResponseData?.PassData != null) { var data = gatewayTemp.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}"); } } } } } }; Gateway.Actions += action; System.Console.WriteLine("ClientDataPassthrough_Actions 启动" + System.DateTime.Now.ToString()); try { var sendDataBytes = new byte[12 + dataLength]; sendDataBytes[0] = 0xfe; //设备端点,1个bytes sendDataBytes[1] = Convert.ToByte(devicePoint); //设备mac地址,小端结构,8个bytes //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个bytes 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 = " 回复超时,请重新操作" }; } Gateway.Actions -= action; System.Console.WriteLine("ClientDataPassthrough_Actions 退出" + System.DateTime.Now.ToString()); return result; }); } #endregion #endregion #region 启用或关闭透传数据上传接口 /// /// 启用或关闭透传数据上传接口 /// /// The scene new identifier async. /// Gateway. /// 0:关闭透传数据上传 ;1:开启透传数据上传 public async System.Threading.Tasks.Task GetSceneNewIdAsync(int IsOn) { return await System.Threading.Tasks.Task.Run(async () => { PassthroughAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new PassthroughAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new PassthroughAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbDataPassthrough") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.getGwVersion == null) { d = new PassthroughAllData { errorMessageBase = "网关返回的数据为空" }; } else { 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 网关升级 /// /// 网关升级 /// /// The upgrade async. /// Image name:(升级固件名称,名称中要带有“LINUXMODULE”标识,否则将不会升级。最大128字节 public async System.Threading.Tasks.Task LinuxUpgradeAsync(string imageName) { return await System.Threading.Tasks.Task.Run(async () => { LinuxUpgradeAllData d = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new LinuxUpgradeAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new LinuxUpgradeAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbGwOperation/LinuxUpgrade_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; var result = Newtonsoft.Json.JsonConvert.DeserializeObject(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 协调器升级 /// /// 协调器升级 /// /// The NVA sync. /// Image name:(升级镜像名称,名称中要带有“ZBMODULE”标识,否则不允许升级。最大128字节。) public async System.Threading.Tasks.Task UpgradeNVAsync(string imageName) { return await System.Threading.Tasks.Task.Run(async () => { ZbGwOperationUpgradeAllData d = null; ; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new ZbGwOperationUpgradeAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new ZbGwOperationUpgradeAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.zbGwOperationUpgradeData == null) { d = new ZbGwOperationUpgradeAllData { errorMessageBase = "网关返回的数据为空" }; } else { d = new ZbGwOperationUpgradeAllData { bGwOperationUpgradeData = gatewayTemp.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 下载云端固件. /// /// 下载云端网关或协调器固件. /// /// The file async. /// Distributed mark:固件唯一标识 /// Image name:固件版本 public async System.Threading.Tasks.Task DownloadFileAsync(string distributedMark, string imageName) { return await System.Threading.Tasks.Task.Run(async () => { DownloadFileResponAllData d = null; ; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new DownloadFileResponAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new DownloadFileResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "DownloadFile_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.downloadFileResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.downloadFileResponData == null) { d = new DownloadFileResponAllData { errorMessageBase = "网关返回的数据为空" }; } else { d = new DownloadFileResponAllData { downloadFileResponData = gatewayTemp.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 DownloadFileResponAllData { errorMessageBase = " 回复超时,请重新操作" }; } Actions -= action; DebugPrintLog("DownloadFile_Actions 退出" + System.DateTime.Now.ToString()); return d; }); } #endregion #region 查看网关记录的虚拟驱动. /// /// 查看网关记录的虚拟驱动 /// public async System.Threading.Tasks.Task CheckVDDriveCodeAsync() { return await System.Threading.Tasks.Task.Run(async () => { CheckVDDriveCodeResponseAllData d = null; ; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new CheckVDDriveCodeResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new CheckVDDriveCodeResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "VirtualDrive/CatDriveCode_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.vDriveDriveCodeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.vDriveDriveCodeResponData == null) { d = new CheckVDDriveCodeResponseAllData { errorMessageBase = "网关返回的数据为空" }; } else { d = new CheckVDDriveCodeResponseAllData { vDriveDriveCodeResponData = gatewayTemp.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 升级虚拟驱动设备. /// /// 升级虚拟驱动设备 /// oTAImageName:升级镜像名称 /// driveCode:驱动代号 /// public async System.Threading.Tasks.Task VirtualDriveUpgradeAsync(string imageName, int driveCode) { return await System.Threading.Tasks.Task.Run(async () => { VirtualDriveUpgradeResponseAllData d = null; ; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { d = new VirtualDriveUpgradeResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.virtualDriveUpgradeResponData == null) { d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = "网关返回的数据为空" }; } else { d = new VirtualDriveUpgradeResponseAllData { virtualDriveUpgradeResponData = gatewayTemp.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 上传私有数据 //private bool backupSuccess = false; /// /// 上传私有数据 /// /// The data to gateway. /// File name. /// Dev. //public async System.Threading.Tasks.Task BackupDataToGateway(string fileName, CommonDevice dev) //{ // return await System.Threading.Tasks.Task.Run(async () => // { // SendFileResponseAllData backUpStatus = null; // var file = await System.Threading.Tasks.Task.Factory.StartNew(() => Newtonsoft.Json.JsonConvert.SerializeObject(dev)); // var data = System.Text.Encoding.UTF8.GetBytes(file); // //网关中创建存储数据的文件 // var saveFileName = await dev.Gateway.CreateFileAsync(fileName); // if (saveFileName != null && saveFileName.Result == 0) // { // backupSuccess = false; // //上传数据到网关 // var saveData = await dev.Gateway.SendFileAsync(data); // if (saveData != null) // { // backUpStatus = new SendFileResponseAllData { Result = saveData.Result }; // } // } // var dateTime = DateTime.Now; // while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) // { // await System.Threading.Tasks.Task.Delay(10); // if (backUpStatus != null) // { // break; // } // } // if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) // { // backUpStatus = new SendFileResponseAllData { errorMessageBase = " 回复超时,请重新操作" }; // }; // return backUpStatus; // }); //} /// /// 下载私有数据 /// /// The data from gateway. /// File name. /// Dev. //public async System.Threading.Tasks.Task> DownloadDataFromGateway(string fileName, CommonDevice dev) //{ // return await System.Threading.Tasks.Task.Run(async () => // { // byteSource.Clear(); // System.Collections.Generic.List backUpData = null; // var dateTime = DateTime.Now; // //获取当前文件的具体信息 // //var getFileSize = await currentKey.Gateway.GetCurrentFileInfoAsync(fileName); // //下载文件 // var saveFileName = await dev.Gateway.SetDownloadFileAsync(fileName); // Action action = (topic, dataContent) => // { // if (topic.Split('/')[0] + "/" + topic.Split('/')[1] + "/" + topic.Split('/')[2] == topic.Split('/')[0] + "/" + "FileTransfer/DownloadFile") // { // dateTime = DateTime.Now; // byte[] fileBytes = dataContent; // if (fileBytes[5] != 1) // { // if (fileBytes.Length == 2056) // { // 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); // } // } // else // { // var tempBytes = new byte[fileBytes.Length - 8]; // System.Array.Copy(fileBytes, 8, tempBytes, 0, tempBytes.Length); // byteSource.AddRange(tempBytes); // if (byteSource != null ) // { // backUpData = byteSource; // } // } // } // }; // dev.Gateway.FileContentAction += action; // while ((DateTime.Now - dateTime).TotalMilliseconds < 2000) // { // await System.Threading.Tasks.Task.Delay(10); // } // dev.Gateway.FileContentAction -= action; // return byteSource; // }); //} //#endregion #region 客户端上传文件到网关. /// /// 客户端上传文件到网关 /// /// The admin password async. /// 上传文件后,保存的文件名称 /// 文件保存在系统的目录路径,如果目录不存在系统将自动创建该目录。如:/tmp/. public async System.Threading.Tasks.Task CreateFileAsync(string fileName, string filePath = "/etc/hdlDat") { return await System.Threading.Tasks.Task.Run(async () => { CreateFileResponseAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new CreateFileResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new CreateFileResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "FileTransfer/CreateFile_Respon") { var security = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var result = Newtonsoft.Json.JsonConvert.DeserializeObject(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 客户端发送文件流到网关 /// /// 客户端发送文件流到网关 ///Result 0: 数据写入成功,请求发送下一个数据包 ///Result1:数据写入失败 ///Result2:数据解析错误 ///Result3:发送数据大小超出限制 /// public async System.Threading.Tasks.Task 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 action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/FileTransfer/SendFile_Respon") { var gateway = new ZbGateway() { DataID = jobject.Value("Data_ID") }; var result = Newtonsoft.Json.JsonConvert.DeserializeObject(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 查看网关目录文件信息. /// /// 查看网关目录文件信息 /// /// The admin password async. /// 文件保存在系统的目录路径,如果目录不存在系统将自动创建该目录。如:/tmp/. public async System.Threading.Tasks.Task FileTransferLsDirAsync(string filePath = "/etc/hdlDat") { return await System.Threading.Tasks.Task.Run(async () => { FileTransferLsDiResponseAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new FileTransferLsDiResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new FileTransferLsDiResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "FileTransfer/lsDir_Respon") { var lsDir = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject(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 查看单个文件信息. /// /// 查看单个文件信息 /// /// The admin password async. /// 文件保存在系统的目录路径,如果目录不存在系统将自动创建该目录。如:/tmp/. public async System.Threading.Tasks.Task GetCurrentFileInfoAsync(string fileName, string filePath = "/etc/hdlDat/") { return await System.Threading.Tasks.Task.Run(async () => { FileTransferGetFileInfoResponseAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new FileTransferGetFileInfoResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new FileTransferGetFileInfoResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "FileTransfer/GetFileInfo_Respon") { var lsDir = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject(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 客户端设定要下载的文件名称和路径 /// /// 客户端设定要下载的文件名称和路径 /// fileName:下载的文件名称. /// blockStartAddress:可忽略,默认为0。下载开始地址,用于断点续传。如:文件总大小为1000Byte,客户端下载了200Byte后连接意外断开。当客户端重新连接后想继续下载后续文件流而不想从文件头重新开始下载,可将该参数设置为200,网关将从第2001Byte开始发送文件流。 /// filePath">文件所在系统的目录路径。如:/tmp. /// public async System.Threading.Tasks.Task SetDownloadFileAsync(string fileName, int blockStartAddress = 0, string filePath = "/etc/hdlDat") { return await System.Threading.Tasks.Task.Run(async () => { SetDownloadFileResponseAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new SetDownloadFileResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new SetDownloadFileResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "FileTransfer/SetDownloadFile_Respon") { var lsDir = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = CurrentGateWayId }; var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (tempData != null) { dataRes = new SetDownloadFileResponseAllData { }; var tempDa = new SetDownloadFileResponseData(); if (tempData.Result == 0) { ZbGateway.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 网关发送文件流到客户端 static System.Collections.Generic.List byteSource = new System.Collections.Generic.List(); /// /// 下载文件中的数据 /// 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 删除文件或目录 /// /// 删除文件或目录 /// /// The admin password async. /// 删除目录或文件的路径。如:/tmp/,则删除tmp目录。/tmp/aa.txt,则删除tmp目录下的aa.txt文件。 public async System.Threading.Tasks.Task DelFileOrDirAsync(string path = "/etc/hdlDat") { return await System.Threading.Tasks.Task.Run(async () => { DelFileOrDirResponseAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new DelFileOrDirResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new DelFileOrDirResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "FileTransfer/DelFileOrDir_Respon") { var lsDir = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = CurrentGateWayId }; var resultDelFileOrDir = Newtonsoft.Json.JsonConvert.DeserializeObject(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 创建一个目录. /// /// 创建一个目录 /// /// The admin password async. /// 删除目录或文件的路径。如:/tmp/,则删除tmp目录。/tmp/aa.txt,则删除tmp目录下的aa.txt文件。 public async System.Threading.Tasks.Task CreateDirAsync(string path = "/etc/hdlDat") { return await System.Threading.Tasks.Task.Run(async () => { CreateDirResponseAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new CreateDirResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new CreateDirResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "FileTransfer/CreateDir_Respon") { var lsDir = new ZbGateway() { DataID = jobject.Value("Data_ID"), CurrentGateWayId = CurrentGateWayId }; var resultCreateDir = Newtonsoft.Json.JsonConvert.DeserializeObject(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 客户端发送密钥到网关 /// /// 客户端发送DES密钥到网关 /// DES密钥经RSA公钥加密转成base64后所得的字符串信息 /// public async System.Threading.Tasks.Task SendAesKeyAsync(string aesKey) { return await System.Threading.Tasks.Task.Run(async () => { SendKeyResponData sendKeyResponData = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; if (topic == gatewayID + "/" + "SendAESKey_Respon") { var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; var result = Newtonsoft.Json.JsonConvert.DeserializeObject(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 设备状态更新 /// /// 设备状态监听列表 /// 进入当前界面时要添加 /// 退出当前界面时要关闭 /// public static readonly System.Collections.Generic.List StatusList = new System.Collections.Generic.List(); /// /// 设备状态更新 /// /// Common device. public static void UpdateDeviceStatus(CommonDevice commonDevice) { if (commonDevice == null) { return; } for (int i = 0; i < StatusList.Count; i++) { StatusList[i].Changed(commonDevice); } } /// /// 设备信息变化 /// type:如果为 DeviceInComingRespon:设备新上报 /// type:如果为 IASInfoReport:RemoveDeviceRespon /// type:如果为 DeviceStatusReport:设备上报 /// type:如果为 IASInfoReport:IAS安防信息上报 /// type:如果为 OnlineStatusChange: 设备在线状态更新 /// /// Common device. 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 通讯连接 /// /// 局域网的MQTT /// IMqttClient mqttClient; /// /// 手机标识 /// static Guid currentGuid = Guid.NewGuid(); /// /// 局域网的MQTT是否正在连接 /// object mqttIsConnecting = false.ToString(); public async System.Threading.Tasks.Task StartLocalMqtt(string brokerName) { await System.Threading.Tasks.Task.Factory.StartNew(async () => { try { lock (mqttIsConnecting) { if (mqttIsConnecting.ToString() == true.ToString() || brokerName == null) { return; } mqttIsConnecting = true.ToString(); if (mqttClient == null) { //(2)创建Mqtt客户端 mqttClient = new MqttClientFactory().CreateMqttClient(); //(3)当[连接Mqtt成功后]或者[Mqtt转发数据给网关成功后],处理接收到数据包响应时在mqttClient_ApplicationMessageReceived这个方法处理 mqttClient.ApplicationMessageReceived += (sender, e) => { if (mqttClient == null || !mqttClient.IsConnected) { 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 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; } } Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI); System.Console.WriteLine($"当前是网关Wi-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)连接到Mqtt客户端连接参数 var connectCloudMqttClientOptions = new MqttClientTcpOptions { Server = brokerName, //ip地址 ClientId = currentGuid.ToString(), CleanSession = true,// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接 KeepAlivePeriod = new TimeSpan(0, 5, 0),//设置心跳时间(最大值,2^16-1 = 65535秒 = 18小时。最小值可以为0,表示客户端不断开。一般设为几分钟,比如微信心跳周期为300秒。) DefaultCommunicationTimeout = new TimeSpan(0, 0, 100),//设置超时时间 }; await mqttClient.ConnectAsync(connectCloudMqttClientOptions); } catch (Exception ex) { #if DEBUG DebugPrintLog($"局域网通讯连接出异常:{ex.Message}"); #endif } finally { mqttIsConnecting = false.ToString(); } }); } /// /// 外网的MQTT是否正在连接 /// static bool remoteMqttIsConnecting; static bool IsLoginAgain; /// /// 远程MqttClient /// public static IMqttClient RemoteMqttClient; private int IsLogin = 0; [Newtonsoft.Json.JsonIgnore] static Action actionTemp; /// /// 启动远程Mqtt /// /// The start. /// Broker name. public static async System.Threading.Tasks.Task StartCloudMqtt() { await System.Threading.Tasks.Task.Factory.StartNew(async () => { try { if (remoteMqttIsConnecting || Shared.Common.Config.Instance.HomeId == "") { return; } 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(); //(3)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理 RemoteMqttClient.ApplicationMessageReceived += (sender, e) => { 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) { if (gateWayList.Count == 1) { gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true; } else { for (int i = 0; i < gateWayList.Count; i++) { var gateWay = gateWayList[i]; var info = await gateWay.GetZbGwInfoAsync(); if (info == null || info.getGwData == null) { continue; } if (info.getGwData.IsDominant == 1) { gateWay.getGatewayBaseInfo.IsMainGateWay = true; for (int j = i + 1; j < gateWayList.Count; j++) { gateWayList[j].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($"重新连接远程通讯失败,因为获取新的KEY失败"); #endif return; } //还有种情况是同一个ID 有多个设备用这个id连接(会导致中断) string clientId = Shared.Common.Config.Instance.ConnectZigbeeMqttClientId; string username = Shared.Common.Config.Instance.ConnectGuid; 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登录后获取到的连接云端Mqtt密码只能连接一次成功之后不能再使用相同的密码进行连接Mqtt否则会提示用户名密码失败,连接不上云端;) CleanSession = true,// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接 KeepAlivePeriod = new TimeSpan(0, 5, 0),//设置心跳时间(最大值,2^16-1 = 65535秒 = 18小时。最小值可以为0,表示客户端不断开。一般设为几分钟,比如微信心跳周期为300秒。) DefaultCommunicationTimeout = new TimeSpan(0, 0, 100),//设置超时时间 }; //远程通讯连接,连接云端服务器 await RemoteMqttClient.ConnectAsync(connectCloudMqttClientOptions); } catch (Exception ex) { #if DEBUG DebugPrintLog($"远程连接通讯连接出异常:{ex.Message}"); #endif } finally { remoteMqttIsConnecting = false; } }); } /// /// 断开服务器连接 /// public async System.Threading.Tasks.Task DisConnect(string s) { try { #if DEBUG DebugPrintLog($"主动断开_{System.DateTime.Now.ToString()}_{s}"); #endif if (mqttClient != null && mqttClient.IsConnected == true) { await mqttClient.DisconnectAsync(); } } catch (Exception ex) { #if DEBUG DebugPrintLog($"断开通讯连接出异常:{ex.Message}"); #endif } } #endregion /// /// 发送消息到服务器 /// /// The send. /// Topic. /// Cluster identifier. /// Commnand. /// Message. 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())); } /// /// 远程发送数据格式 /// async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, MQTTnet.Core.Protocol.MqttQualityOfServiceLevel qosLevel = MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, 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.Guid, RemoteOperatorConsts.CAP_NUMBER, Shared.Common.Config.Instance.MD5PWD); DebugPrintLog($"userNameAndPwdStr:{userNameAndPwdStr} "); //(2)将(1)转成Base64字符串,生成格式[Base64(用户名:密码)] var userNameAndPwdStrBaseSexFour = Convert.ToBase64String(ZigBee.Common.CommonInfo.EncodingUTF8.GetBytes(userNameAndPwdStr)); //(3)将(2)继续生成格式[Base64(用户名:密码):Timestamp] var userNameAndPwdStrBaseSexFourAndTimestamp = string.Concat(userNameAndPwdStrBaseSexFour, RemoteOperatorConsts.CAP_NUMBER, CurrentTimeStamp.ToString()); ///[Zigbee.Buspro]App/id(帐号Id)/Base64(DES[Base64(用户名:密码):Timestamp ]/网关唯一Id/转发给网关的主题/XX/XX //(4)生成上报主题,主题模式需要为 /ZigbeeApp/id(主子调试帐号Id)/Base64(DES[Base64(用户名:密码):Timestamp ]/网关唯一Id/topicName "000204022022" GateWayId 000204022022 var reportTopic = string.Format("/{0}/{1}/{2}/{3}/{4}", RemoteOperatorConsts.ZIGBEE_APP_STARTS_WITH, Shared.Common.Config.Instance.Guid, userNameAndPwdStrBaseSexFourAndTimestamp, this.getGatewayBaseInfo?.gwID, topicName); var aa = System.Text.Encoding.UTF8.GetString(message); DebugPrintLog($"AAAA发送到云端主题明文:{reportTopic}___BBBBB发送到云端内容明文:{aa}"); 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)); var bb = System.Text.Encoding.UTF8.GetString(message); DebugPrintLog($"CCCC发送到云端主题秘文:{topicEncStr}___DDDD发送到云端内容秘文:{bb}"); //(6)构建Mqtt需要发布的数据包,发布给云端的MqttBroker await RemoteMqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topicEncStr, message, qosLevel, retain)); } /// /// 发送消息到服务器 /// /// /// /// /// /// public async System.Threading.Tasks.Task Send(string topic, byte[] message, MQTTnet.Core.Protocol.MqttQualityOfServiceLevel qosLevel = MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, bool retain = false) { try { if (Shared.Common.Config.Instance.HomeId == "") { return; } 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 } 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); } 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()}"); } await mqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topic, message, qosLevel, retain)); } else { await mqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topic, message, qosLevel, retain)); } } } catch (Exception ex) { #if DEBUG DebugPrintLog($"Send:{ex.Message}"); #endif } } /// /// 发送消息到服务器 /// /// /// /// /// /// public async System.Threading.Tasks.Task Send(string topic, string message, MQTTnet.Core.Protocol.MqttQualityOfServiceLevel qosLevel = MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, bool retain = false) { if (string.IsNullOrEmpty(message)) { return; } await Send(topic, System.Text.Encoding.UTF8.GetBytes(message), qosLevel, retain); } [Serializable] public class CloudTimeResponse { public string StateCode; public string Info; public string CloudTimestamp; } /// /// 接收远程数据处理 /// /// Sender. /// E. static void mqttRemoteClient_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { try { var topic = e.ApplicationMessage.Topic.TrimStart('/'); var message = string.Empty; //你当前的IP及端口在云端不存在,请重新登录连接下! if (topic == "YouIpAndPortNoRecord") { 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$分布式住宅Id=XXX尚未登录,请重新登录后再连接后再进行发布操作,如果您当前是别人共享给你的连接,则请重新请求获取连接信息一下,再初始化连接再次发布远程控制即可!! else if (topic == "AppNoLogin") { message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); } 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 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(message); if (cloudMqttResult != null) { if (topic == "AppConnectMqttBrokerSuccess") { 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; } else { switch (cloudMqttResult.StateCode) { 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; } } } ReceiveMessage(topic, message, e); } catch (Exception ex) { #if DEBUG DebugPrintLog($"接收云端数据异常:{ex.Message}"); #endif } } /// /// 接收局域网中的数据 /// 当订阅消息成功后,该事件会被调用 /// /// Sender. /// E. void mqttClient_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { try { var topic = e.ApplicationMessage.Topic; var message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); 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); } } else if (topic == topic.Split('/')[0] + "/" + "SendAESKey_Respon") { }//回复主题是秘文,数据是明文 else { message = Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Password); } } else { topic = e.ApplicationMessage.Topic; } #if DEBUG DebugPrintLog($"网关返回的主题:{topic}_网关返回的负载:{message}_{System.DateTime.Now.ToString()}"); #endif ReceiveMessage(topic, message, e); } catch (Exception ex) { #if DEBUG DebugPrintLog($"接收网关数据异常:{ex.Message}"); #endif } } /// /// 数据接收处理 /// /// Topic. /// Message. /// E. static void ReceiveMessage(string topic, string message, MqttApplicationMessageReceivedEventArgs e) { try { if (string.IsNullOrEmpty(message)) { message = "{}"; } var gatewayID = topic.Split('/')[0];//网关返回的网关ID var reportStatus = ""; reportStatus = topic.Split('/')[1];//主题为设备上报的主题 string addr = "";//上报的设备addr string epoint = "";//上报的设备epoint string cluID = "";//上报的设备cluID string attrId = "";//上报的设备attrId if (reportStatus == "DeviceStatusReport") { addr = topic.Split('/')[2]; epoint = topic.Split('/')[3]; cluID = topic.Split('/')[4]; attrId = topic.Split('/')[5]; } var gwa = ZigBee.Device.ZbGateway.GateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == gatewayID); if (gwa == null) { return; } if (gwa.Actions != null) { gwa?.Actions(topic, message); } if (gwa.GwResDataAction != null) { gwa.GwResDataAction(topic, message); } gwa.CurrentGateWayId = gatewayID; Newtonsoft.Json.Linq.JObject 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()}"); return; } } else { jobject = Newtonsoft.Json.Linq.JObject.Parse(message); } //全局接收网关推送的的逻辑(为了执行速度,尽可能的别加耗时的操作) Shared.Phone.UserCenter.HdlGatewayReceiveLogic.GatewayOverallMsgReceive(gatewayID, topic, jobject); #region 云端通知 var cloudMqttResult = Newtonsoft.Json.JsonConvert.DeserializeObject(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) { if (topic == gatewayID + "/" + "BeMainGw_Report") { var gwData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); 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; } } } } } } #endregion #region 设备新上报 //步骤1)网关告知客户端有新设备加入zigbee网络。 if (topic == gatewayID + "/" + "Device/DeviceJoinZbNet_Respon") { var gatewayTemp = new ZbGateway() { DeviceAddr = jobject.Value("DeviceAddr"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; gatewayTemp.deviceDeviceJoinZbNetResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.deviceDeviceJoinZbNetResponData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("Device/DeviceJoinZbNet已经通知"); gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值 gwa.ReportAction("Device/DeviceJoinZbNet", gatewayTemp); } } //步骤2)网关告知客户端获取新设备所有端点信息是否成功 if (topic == gatewayID + "/" + "Device/IsGetEpointInfo_Respon") { var gatewayTemp = new ZbGateway() { DeviceAddr = jobject.Value("DeviceAddr"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; gatewayTemp.deviceIsGetEpointInfoResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.deviceIsGetEpointInfoResponData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("Device/IsGetEpointInfo已经通知"); gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值 gwa.ReportAction("Device/IsGetEpointInfo", gatewayTemp); } } //步骤3)网关上报节点设备所有端点信息 if (topic == gatewayID + "/" + "DeviceInComingRespon") { //新设备上报,重新发获取所有的设备 var tempDevice = new CommonDevice() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; tempDevice.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gwa.ReportAction != null) { DebugPrintLog("DeviceInComingRespon已经通知"); gwa.ReportAction("DeviceInComingRespon", tempDevice.getNewDeviceInfo); } UpdateDeviceInfo(tempDevice, "DeviceInComingRespon"); UpdateDeviceStatus(gwa); } #endregion #region 设备在线状态更新反馈 else if (topic == gatewayID + "/" + "OnlineStatusChange_Respon") { var tempDevice = new CommonDevice() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; tempDevice.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject(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); UpdateDeviceStatus(tempDevice); UpdateDeviceInfo(tempDevice, "OnlineStatusChange"); } else { if (infoTempDevice.DeviceInfo != null) { infoTempDevice.DeviceInfo.IsOnline = infoTempDevice.IsOnline; } UpdateDeviceInfo(infoTempDevice, "OnlineStatusChange"); UpdateDeviceStatus(infoTempDevice); } } #endregion #region 设备被删除上报 else if (topic == gatewayID + "/" + "RemoveDeviceRespon") { var gatewayTemp = new ZbGateway() { DeviceAddr = jobject.Value("DeviceAddr"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; gatewayTemp.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.removeDeviceResponseData != null) { try { if (gatewayTemp.removeDeviceResponseData.Result == 0) { foreach (var delD in gatewayTemp.removeDeviceResponseData.DeviceList) { var tempDevice = new CommonDevice() { DeviceAddr = jobject.Value("DeviceAddr"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; tempDevice.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (tempDevice.removeDeviceResponseData == null) { return; } else { UpdateDeviceStatus(tempDevice); 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); } } } } } } catch { } } } #endregion #region 设备状态上报 else if (topic == gatewayID + "/" + "DeviceStatusReport" + "/" + addr + "/" + epoint + "/" + cluID + "/" + attrId) { var deviceID = jobject.Value("Device_ID"); var deviceAddr = jobject.Value("DeviceAddr"); var tempEpoint = jobject.Value("Epoint"); var dataId = jobject.Value("Data_ID"); var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId }; tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); UpdateDeviceStatus(tempDevice); UpdateDeviceInfo(tempDevice, "DeviceStatusReport"); } #endregion #region 门锁操作事件通知 else if (topic == gatewayID + "/" + "DoorLock/DoorLockOperatingEventNotificationCommand") { var deviceID = jobject.Value("Device_ID"); switch ((DeviceType)(deviceID)) { case DeviceType.DoorLock: var doorLock = new DoorLock() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; var OperatingEventNotificationDatad = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (OperatingEventNotificationDatad != null) { doorLock.doorLockOperatingEventNotificationCommand = OperatingEventNotificationDatad; } if (gwa.ReportAction != null) { DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知"); gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock); } UpdateDeviceStatus(doorLock); UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand"); break; } } #endregion #region 门锁编程事件通知 else if (topic == gatewayID + "/" + "DoorLock/DoorLockProgrammingEventNotificationCommand") { var deviceID = jobject.Value("Device_ID"); switch ((DeviceType)(deviceID)) { case DeviceType.DoorLock: var doorLock = new DoorLock() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; var ProgrammingEventNotificationData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (ProgrammingEventNotificationData != null) { doorLock.doorLockProgrammingEventNotificationCommand = ProgrammingEventNotificationData; } if (gwa.ReportAction != null) { DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知"); gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock); } UpdateDeviceStatus(doorLock); UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand"); break; } } #endregion #region IAS安防信息上报 else if (topic == gatewayID + "/" + "IASInfoReport") { var deviceID = jobject.Value("Device_ID"); switch ((DeviceType)(deviceID)) { case DeviceType.IASZone: var ias = new IASZone() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; ias.iASInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); //上报类型通知,必需先调用,然后才有通知,否则是空不会通知的 if (gwa.ReportAction != null) { DebugPrintLog("IASInfoReport已经通知"); //ias.Save(); gwa.ReportAction("IASInfoReport", ias.iASInfo); } UpdateDeviceStatus(ias); UpdateDeviceInfo(ias, "IASInfoReport"); break; } } #endregion #region 下载进度上报 else if (topic == gatewayID + "/" + "DownloadFile_Progress") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.downloadFileProgressResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.downloadFileProgressResponData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("DownloadFileProgress"); gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值 gwa.ReportAction("DownloadFileProgress", gatewayTemp); } } else if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.zbGwOperationUpgradeData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("协调器升级百分比"); gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值 gwa.ReportAction("CordinatorUpgradePercent", gatewayTemp); } } else if (topic == gatewayID + "/" + "OTA/Schedule_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.oTAScheduleResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.oTAScheduleResponData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("节点设备升级百分比"); gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值 gwa.ReportAction("DeviceUpgradePercent", gatewayTemp); } } else if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.virtualDriveUpgradeResponData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("虚拟驱动升级百分比"); gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值 gwa.ReportAction("VirtualDriveUpgrade", gatewayTemp); } } #endregion #region 重启网关系统 else if (topic == gatewayID + "/" + "GwReboot_Respon") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID") }; gatewayTemp.gwRebootResponData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.gwRebootResponData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("GwReboot_Respon已经通知"); gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值 gwa.ReportAction("GwReboot_Respon", gatewayTemp); } } #endregion #region 防区被触发时报告 else if (topic == gatewayID + "/" + "Security/ZoneTriggerReport") { var ias = new Safeguard() { DataID = jobject.Value("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; ias.zoneTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject(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("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject(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("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject(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("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; ias.modeTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject(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("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; ias.enOrWithdrawSucceedReportData = Newtonsoft.Json.JsonConvert.DeserializeObject(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("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID }; ias.coercedPWDWithdrawReportData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (ias.coercedPWDWithdrawReportData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("PushTargetInfoReport"); gwa.ReportAction("PushTargetInfoReport", ias.coercedPWDWithdrawReportData); } } #endregion #region 节点设备默认反馈 else if (topic == gatewayID + "/" + "DeviceDefaultAck") { var deviceDefaultAck = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID }; if (deviceDefaultAck == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("DeviceDefaultAck"); gwa.ReportAction("DeviceDefaultAck", deviceDefaultAck); } } #endregion #region 设备请求APP获取升级数据 else if (topic == gatewayID + "/" + "ZbDataPassthrough") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.clientDataPassthroughResponseData == null) { return; } //上报类型通知 if (gwa.ReportAction != null) { DebugPrintLog("DeviceRequestAcUpdateData"); gwa.ReportAction("DeviceRequestAcUpdateData", gatewayTemp.clientDataPassthroughResponseData); } } #endregion DebugPrintLog("网关返回数据通知"); } catch (Exception ex) { DebugPrintLog($"处理回复的数据抛出异常:{ex.Message}"); } } } }