using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using ZigBee.Device;
using ZigBee.Common;
using Shared.Common;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace Shared.Phone.Device.Logic
{
public class Send
{
#region ----Logic所有发送命令
///
/// 获取LogicId的方法
///
/// The logic identifier.
public static async System.Threading.Tasks.Task> GetLogicId(int LogicType)
{
return await System.Threading.Tasks.Task.Run(async () =>
{
List logicIdList = new List();
bool if_theme = false;
int if_number = -1;
Action action = (topic, data) =>
{
var gatewayID = topic.Split('/')[0];
var jObjectdata = JObject.Parse(data);
if (jObjectdata == null)
{
return;
}
if (topic == $"{gatewayID}/Logic/GetLogicList_Respon")
{
if_theme = true;
var list = Newtonsoft.Json.JsonConvert.DeserializeObject>>(jObjectdata["Data"]["LogicList"].ToString());
if_number = list.Count;
if (list.Count == 0)
{
return;
}
foreach (var listIfon in list)
{
var logicId = int.Parse(listIfon["LogicId"]);
logicIdList.Add(logicId);
}
}
};
var mainGateWay = ZbGateway.MainGateWay;
if (mainGateWay == null)
{
Console.WriteLine("没有主网关");
return logicIdList;
}
mainGateWay.GwResDataAction += action;
try
{
var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2004 } };
var jObjectdata1 = new JObject { { "LogicType", LogicType } };
jObject.Add("Data", jObjectdata1);
mainGateWay?.Send("Logic/GetLogicList", jObject.ToString());
}
catch(Exception e) {
var d = e.Message;
}
//await System.Threading.Tasks.Task.Run(async () =>
//{
var dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds < 3 * 1000)
{
await System.Threading.Tasks.Task.Delay(100);
if (if_theme)
{
if (if_number == 0 || if_number == logicIdList.Count)
{
break;//回复没有数据立刻返回
}
}
}
ZbGateway.MainGateWay.GwResDataAction -= action;
//});
return logicIdList;
});
}
///
/// 获取Logic的方法
///
/// The logic identifier.
public static async System.Threading.Tasks.Task GetLogic(int LogicId, int LogicType)
{
return await System.Threading.Tasks.Task.Run(async () =>
{
Common.Logic logic = null;
Action action = (topic, data) =>
{
var gatewayID = topic.Split('/')[0];
var jObjectdata = JObject.Parse(data);
if (jObjectdata == null)
{
return;
}
if (topic == $"{gatewayID}/Logic/GetLogicInfo_Respon")
{
logic = new Common.Logic();
var Logicifon = jObjectdata["Data"];
logic.LogicId = int.Parse(Logicifon["LogicId"]?.ToString());
logic.IsEnable = int.Parse(Logicifon["IsEnable"]?.ToString());
logic.LogicName = Logicifon["LogicName"]?.ToString();
logic.Relationship = int.Parse(Logicifon["Relationship"]?.ToString());
logic.TimeAttribute = Newtonsoft.Json.JsonConvert.DeserializeObject(Logicifon["TimeAttribute"].ToString());
logic.Conditions = Newtonsoft.Json.JsonConvert.DeserializeObject>>(Logicifon["Conditions"].ToString());
logic.Accounts = Newtonsoft.Json.JsonConvert.DeserializeObject>>(Logicifon["Accounts"].ToString());
var listactions = Newtonsoft.Json.JsonConvert.DeserializeObject>>(Logicifon["Actions"].ToString());
if (listactions != null)
{
foreach (var actions in listactions)
{
Dictionary actionsdictionary = new Dictionary();
List> tasklist = new List>();
if (actions["LinkType"].ToString() == "0")
{
actionsdictionary.Add("LinkType", actions["LinkType"]);
actionsdictionary.Add("DeviceAddr", actions["DeviceAddr"]);
actionsdictionary.Add("Epoint", actions["Epoint"]);
actionsdictionary.Add("Time", actions["Time"]);
var list = JArray.Parse(actions["TaskList"].ToString());
foreach (var taskIfon in list)
{
Dictionary dictionary = new Dictionary();
dictionary.Add("TaskType", taskIfon["TaskType"].ToString());
dictionary.Add("Data1", taskIfon["Data1"].ToString());
dictionary.Add("Data2", taskIfon["Data2"].ToString());
tasklist.Add(dictionary);
}
actionsdictionary.Add("TaskList", tasklist);
}
else
{
actionsdictionary = actions;
}
logic.Actions.Add(actionsdictionary);
}
}
}
};
var mainGateWay = ZbGateway.MainGateWay;
if (mainGateWay == null)
{
Console.WriteLine("没有主网关");
return logic;
}
mainGateWay.GwResDataAction += action;
try
{
var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2002 } };
var data = new JObject {
{ "LogicId",LogicId},
{ "LogicType",LogicType}
};
jObject.Add("Data", data);
ZbGateway.MainGateWay?.Send("Logic/GetLogicInfo", jObject.ToString());
}
catch { }
var dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds < 3 * 1000)
{
await System.Threading.Tasks.Task.Delay(100);
if (logic != null)
{
break;
}
}
ZbGateway.MainGateWay.GwResDataAction -= action;
return logic;
});
}
///
/// 删除逻辑(0成功,其它值:失败)
///
public static async System.Threading.Tasks.Task DelLogic(int LogicId)
{
return await System.Threading.Tasks.Task.Run(async () =>
{
//Result:0成功,1失败;
int Result = 3;
Action action = (topic, dataleng) =>
{
var gatewayID = topic.Split('/')[0];
var jobject = JObject.Parse(dataleng);
if (topic == gatewayID + "/" + "Logic/DelLogic_Respon")
{
Result = int.Parse(jobject["Data"]["Result"].ToString());
}
};
var mainGateWay = ZbGateway.MainGateWay;
if (mainGateWay == null)
{
Console.WriteLine("没有主网关");
return Result;
}
ZbGateway.MainGateWay.Actions += action;
var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2009 } };
var data = new JObject {
{ "LogicId",LogicId}
};
jObject.Add("Data", data);
ZbGateway.MainGateWay?.Send("Logic/DelLogic", jObject.ToString());
var dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds < 3 * 1000)
{
await System.Threading.Tasks.Task.Delay(100);
if (Result != 3)
{
break;
}
}
ZbGateway.MainGateWay.Actions -= action;
return Result;
});
}
///
/// 添加或修改逻辑
///
public static async System.Threading.Tasks.Task AddModifyLogic(Common.Logic logic)
{
return await System.Threading.Tasks.Task.Run(async () =>
{
Common.Logic Logicifon = null;
Action action = (topic, datastring) =>
{
var gatewayID = topic.Split('/')[0];
var jObjectdata = JObject.Parse(datastring);
if (jObjectdata == null)
{
return;
}
if (topic == gatewayID + "/Logic/AddLogic_Respon")
{
try
{
Logicifon = Newtonsoft.Json.JsonConvert.DeserializeObject(jObjectdata["Data"].ToString());
}
catch (Exception ex)
{
var mess = ex.Message;
}
}
};
var mainGateWay = ZbGateway.MainGateWay;
if (mainGateWay == null)
{
Console.WriteLine("没有主网关");
return Logicifon;
}
ZbGateway.MainGateWay.Actions += action;
try
{
var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2000 } };
var selectMonthList = new JArray { };
foreach (var intvalue in logic.TimeAttribute.SelectMonDate)
{
selectMonthList.Add(intvalue);
}
var timeAttribute = new JObject{
{ "Calendar",logic.TimeAttribute.Calendar},
{ "Repeat", logic.TimeAttribute.Repeat} ,
{ "WeekDay", logic.TimeAttribute.WeekDay} ,
{ "SetYear",logic.TimeAttribute.SetYear} ,
{ "MonthDate", logic.TimeAttribute.MonthDate} ,
{ "SelectMonth", logic.TimeAttribute.SelectMonth} ,
{ "SelectMonDate", selectMonthList},
};
var conditions = new JArray();
foreach (var dictionary in logic.Conditions)
{
var Type = int.Parse(dictionary["Type"]);
// (0:时间点条件;1:设备状态变化条件;2:其他逻辑条件;3:计数器条件;4:倒计时;5:时间段条件)
switch (Type)
{
case 0:
var tInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["DateType"] = int.Parse(dictionary["DateType"]),
["RemindTime"] = int.Parse(dictionary["RemindTime"]),
["EnDelay"] = int.Parse(dictionary["EnDelay"]),
["DelayTime"] = int.Parse(dictionary["DelayTime"]),
["DoorLockOpenDelayTime"] = int.Parse(dictionary["DoorLockOpenDelayTime"]),
};
if (dictionary["DateType"].ToString() == "0")
{
tInfo.Add("StartHour", int.Parse(dictionary["StartHour"]));
tInfo.Add("StartMin", int.Parse(dictionary["StartMin"]));
}
else
{
tInfo.Add("AdjustTime", int.Parse(dictionary["AdjustTime"]));
}
conditions.Add(tInfo);
break;
case 1:
var dInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["MacAddr"] = dictionary["MacAddr"],
["Epoint"] = int.Parse(dictionary["Epoint"]),
["Cluster_ID"] = int.Parse(dictionary["Cluster_ID"]),
["AttriButeId"] = int.Parse(dictionary["AttriButeId"]),
["AttriButeData1"] = int.Parse(dictionary["AttriButeData1"]),
["AttriButeData2"] = int.Parse(dictionary["AttriButeData2"]),
["Range"] = int.Parse(dictionary["Range"])
};
if (dictionary.ContainsKey("IgnoreTime"))
{
dInfo.Add("IgnoreTime", int.Parse(dictionary["IgnoreTime"]));
}
conditions.Add(dInfo);
break;
case 2:
var lInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["Condition_LogicId"] = int.Parse(dictionary["Condition_LogicId"]),
};
conditions.Add(lInfo);
break;
case 3:
var cInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["MacAddr"] = dictionary["MacAddr"],
["Epoint"] = int.Parse(dictionary["Epoint"]),
["Cluster_ID"] = int.Parse(dictionary["Cluster_ID"]),
["AttriButeId"] = int.Parse(dictionary["AttriButeId"]),
["AttriButeData1"] = int.Parse(dictionary["AttriButeData1"]),
["AttriButeData2"] = int.Parse(dictionary["AttriButeData2"]),
["Range"] = int.Parse(dictionary["Range"]),
["Number"] = int.Parse(dictionary["Number"]),
["Time"] = int.Parse(dictionary["Time"]),
["Cycle"] = int.Parse(dictionary["Cycle"]),
};
conditions.Add(cInfo);
break;
case 4:
var cdInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["Time"] = int.Parse(dictionary["Time"]),
};
conditions.Add(cdInfo);
break;
case 5:
var tbInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["StartHour"] = int.Parse(dictionary["StartHour"]),
["StartMin"] = int.Parse(dictionary["StartMin"]),
["StopHour"] = int.Parse(dictionary["StopHour"]),
["StopMin"] = int.Parse(dictionary["StopMin"]),
};
conditions.Add(tbInfo);
break;
case 6:
var sInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["EnOrWithdrawMode"] = int.Parse(dictionary["EnOrWithdrawMode"]),
["ModeId"] = int.Parse(dictionary["ModeId"]),
};
conditions.Add(sInfo);
break;
case 7:
var diliInfo = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["IsValid"] = int.Parse(dictionary["IsValid"]),
["AtHome"] = int.Parse(dictionary["AtHome"]),
["WhoSiteUId"] = dictionary["WhoSiteUId"],
};
conditions.Add(diliInfo);
break;
}
}
var actions = new JArray();
foreach (var dictionary in logic.Actions)
{
var linkType = int.Parse(dictionary["LinkType"].ToString());
switch (linkType)
{
case 0:
var taskList = new JArray();
var TaskList = dictionary["TaskList"] as List>;
foreach (var taskInfo in TaskList)
{
var info = new JObject
{
["TaskType"] = int.Parse(taskInfo["TaskType"].ToString()),
["Data1"] = int.Parse(taskInfo["Data1"].ToString()),
["Data2"] = int.Parse(taskInfo["Data2"].ToString()),
};
taskList.Add(info);
}
var tInfo = new JObject
{
["LinkType"] = int.Parse(dictionary["LinkType"].ToString()),
["DeviceAddr"] = dictionary["DeviceAddr"].ToString(),
["Epoint"] = int.Parse(dictionary["Epoint"].ToString()),
["Time"] = int.Parse(dictionary["Time"].ToString()),
["taskList"] = taskList,
};
actions.Add(tInfo);
break;
case 2:
var dInfo = new JObject
{
["LinkType"] = int.Parse(dictionary["LinkType"].ToString()),
["DeviceAddr"] = int.Parse(dictionary["DeviceAddr"].ToString()),
};
actions.Add(dInfo);
break;
case 4:
var lInfo = new JObject
{
["LinkType"] = int.Parse(dictionary["LinkType"].ToString()),
["DeviceAddr"] = int.Parse(dictionary["DeviceAddr"].ToString()),
["EnableLogic"] = int.Parse(dictionary["EnableLogic"].ToString()),
};
actions.Add(lInfo);
break;
case 6:
var cdInfo = new JObject
{
["LinkType"] = int.Parse(dictionary["LinkType"].ToString()),
["SecuritySetting"] = int.Parse(dictionary["SecuritySetting"].ToString()),
["SecurityModeId"] = int.Parse(dictionary["SecurityModeId"].ToString()),
["CheckIASStatus"] = int.Parse(dictionary["CheckIASStatus"].ToString()),
["IsDelayStart"] = int.Parse(dictionary["IsDelayStart"].ToString()),
["Password"] = dictionary["Password"].ToString(),
};
actions.Add(cdInfo);
break;
case 7:
var timeInfo = new JObject
{
["LinkType"] = int.Parse(dictionary["LinkType"].ToString()),
["DelayTime"] = int.Parse(dictionary["DelayTime"].ToString()),
};
actions.Add(timeInfo);
break;
case 8:
var lockInfo = new JObject
{
["LinkType"] = int.Parse(dictionary["LinkType"].ToString()),
["DeviceAddr"] = dictionary["DeviceAddr"].ToString(),
["Epoint"] = int.Parse(dictionary["Epoint"].ToString()),
["PassData"] =dictionary["PassData"].ToString(),
};
actions.Add(lockInfo);
break;
}
}
var accounts = new JArray();
foreach (var dictionary in logic.Accounts)
{
var Type = int.Parse(dictionary["Type"]);
switch (Type)
{
case 1:
{
///
if (logic.LogicType == 1)
{
var accounts1 = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["Account"] = dictionary["Account"],
["UserId"] = dictionary["UserId"],
["AccountName"] = dictionary["AccountName"],
};
if (dictionary.ContainsKey("Option4"))
{
accounts1.Add("Option4",dictionary["Option4"]);
}
if (dictionary.ContainsKey("Option2"))
{
accounts1.Add("Option2", int.Parse(dictionary["Option2"]));
}
accounts.Add(accounts1);
}
}
break;
case 7:
{
var location = new JObject
{
["Type"] = int.Parse(dictionary["Type"]),
["Account"] = dictionary["Account"],
["Longitude"] = int.Parse(dictionary["Longitude"]),
["Latitude"] = int.Parse(dictionary["Latitude"]),
["Radius"] = int.Parse(dictionary["Radius"]),
};
accounts.Add(location);
}
break;
case 8:
{
var accounts1 = new JObject();
if (dictionary.ContainsKey("Type"))
{
accounts1.Add("Type", int.Parse(dictionary["Type"]));
}
if (dictionary.ContainsKey("Option4"))
{
accounts1.Add("Option4", dictionary["Option4"]);
}
if (dictionary.ContainsKey("Option2"))
{
accounts1.Add("Option2", int.Parse(dictionary["Option2"]));
}
accounts.Add(accounts1);
}
break;
}
}
var data = new JObject{
{ "LogicId",logic.LogicId},
{ "IsEnable", logic.IsEnable} ,
{ "LogicName", logic.LogicName},
{ "Relationship",logic.Relationship} ,
{ "LogicType",logic.LogicType} ,
{ "LogicCustomPushText",logic.LogicCustomPushText} ,
{ "LogicIsCustomPushText",logic.LogicIsCustomPushText} ,
{ "TimeAttribute", timeAttribute} ,
{ "Conditions", conditions },
{ "Actions", actions },
{ "Accounts", accounts },
};
jObject.Add("Data", data);
ZbGateway.MainGateWay?.Send("Logic/AddLogic", jObject.ToString());
}
catch (Exception e)
{
var dd = e.Message;
}
var dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds < 3 * 1000)
{
await System.Threading.Tasks.Task.Delay(100);
if (Logicifon != null)
{
break;
}
}
ZbGateway.MainGateWay.Actions -= action;
return Logicifon;
});
}
///
/// 单独控制自动化开关属性
///
///
public static async System.Threading.Tasks.Task LogicControlSwitch(Common.Logic logic)
{
return await System.Threading.Tasks.Task.Run(async () =>
{
int intvalue = 3;
Action action = (topic, data) =>
{
var gatewayID = topic.Split('/')[0];
var jObjectdata = JObject.Parse(data);
if (jObjectdata == null)
{
return;
}
if (topic == $"{gatewayID}/Logic/ReviseAttribute_Respon")
{
intvalue = int.Parse(jObjectdata["Data"]["Result"].ToString());
}
};
var mainGateWay = ZbGateway.MainGateWay;
if (mainGateWay == null)
{
Console.WriteLine("没有主网关");
return intvalue;
}
mainGateWay.GwResDataAction += action;
var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2001 } };
var date = new JObject();
jObject.Add("Data", date);
date.Add("LogicId", logic.LogicId);
date.Add("IsEnable", logic.IsEnable);
date.Add("LogicName", logic.LogicName);
date.Add("Relationship", logic.Relationship);
date.Add("LogicCustomPushText", logic.LogicCustomPushText);
date.Add("LogicIsCustomPushText", logic.LogicIsCustomPushText);
mainGateWay?.Send("Logic/ReviseAttribute", jObject.ToString());
//await System.Threading.Tasks.Task.Run(async () =>
//{
var dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds < 3 * 1000)
{
await System.Threading.Tasks.Task.Delay(100);
if (intvalue != 3)
{
break;
}
}
ZbGateway.MainGateWay.GwResDataAction -= action;
//});
return intvalue;
});
}
///
/// 获取Logic列表的方法
///
/// The logic identifier.
public static async System.Threading.Tasks.Task> ReadList(int sum, int LogicType)
{
return await System.Threading.Tasks.Task.Run(async () =>
{
var listLogic = new List();
Action action = (topic, data) =>
{
var gatewayID = topic.Split('/')[0];
var jObjectdata = JObject.Parse(data);
if (jObjectdata == null)
{
return;
}
if (topic == $"{gatewayID}/Logic/GetAllLogicListInfo_Respon")
{
var logic = new Common.Logic();
var Logicifon = jObjectdata["Data"];
logic.LogicId = int.Parse(Logicifon["LogicId"].ToString());
logic.IsEnable = int.Parse(Logicifon["IsEnable"].ToString());
logic.LogicName = Logicifon["LogicName"].ToString();
logic.LogicType = int.Parse(Logicifon["LogicType"].ToString());
logic.Relationship = int.Parse(Logicifon["Relationship"].ToString());
logic.LogicCustomPushText = Logicifon["LogicCustomPushText"].ToString();
logic.LogicIsCustomPushText = int.Parse(Logicifon["LogicIsCustomPushText"].ToString());
logic.TimeAttribute = Newtonsoft.Json.JsonConvert.DeserializeObject(Logicifon["TimeAttribute"].ToString());
logic.Conditions = Newtonsoft.Json.JsonConvert.DeserializeObject>>(Logicifon["Conditions"].ToString());
logic.Accounts = Newtonsoft.Json.JsonConvert.DeserializeObject>>(Logicifon["Accounts"].ToString());
List> listactions = new List>();
listactions = Newtonsoft.Json.JsonConvert.DeserializeObject>>(Logicifon["Actions"].ToString());
if (listactions != null)
{
foreach (var actions in listactions)
{
Dictionary actionsdictionary = new Dictionary();
List> tasklist = new List>();
if (actions["LinkType"].ToString() == "0")
{
actionsdictionary.Add("LinkType", actions["LinkType"]);
actionsdictionary.Add("DeviceAddr", actions["DeviceAddr"]);
actionsdictionary.Add("Epoint", actions["Epoint"]);
actionsdictionary.Add("Time", actions["Time"]);
var list = JArray.Parse(actions["TaskList"].ToString());
foreach (var taskIfon in list)
{
Dictionary dictionary = new Dictionary();
dictionary.Add("TaskType", taskIfon["TaskType"].ToString());
dictionary.Add("Data1", taskIfon["Data1"].ToString());
dictionary.Add("Data2", taskIfon["Data2"].ToString());
tasklist.Add(dictionary);
}
actionsdictionary.Add("TaskList", tasklist);
}
else
{
actionsdictionary = actions;
}
logic.Actions.Add(actionsdictionary);
}
}
lock (listLogic)
{
var @null = listLogic.Find((o) => { return o.LogicId == logic.LogicId; });
if (@null == null)
{
listLogic.Add(logic);
}
}
}
};
var mainGateWay = ZbGateway.MainGateWay;
if (mainGateWay == null)
{
Console.WriteLine("没有主网关");
return listLogic;
}
mainGateWay.GwResDataAction += action;
try
{
var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2015 } };
var jObjectdata = new JObject { { "LogicType", LogicType } };
jObject.Add("Data", jObjectdata);
ZbGateway.MainGateWay?.Send("Logic/GetAllLogicListInfo", jObject.ToString());
}
catch { }
var dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds < 5* 1000)
{
await System.Threading.Tasks.Task.Delay(100);
if (sum == listLogic.Count)
{
break;
}
}
ZbGateway.MainGateWay.GwResDataAction -= action;
return listLogic;
});
}
///
/// 获取场景信息的方法
///
///
///
public static async System.Threading.Tasks.Task GetScene(int SceneId)
{
SceneUI sceneui = null;
return await System.Threading.Tasks.Task.Run(async () =>
{
Action action = (topic, data) =>
{
var gatewayID = topic.Split('/')[0];
var jObjectdata = JObject.Parse(data);
if (jObjectdata == null)
{
return;
}
if (topic == $"{gatewayID}/Scene/GetDeviceList_Respon")
{
sceneui = new SceneUI();
sceneui.Name = jObjectdata["Data"]["ScenesName"].ToString();
sceneui.Id = int.Parse(jObjectdata["Data"]["ScenesId"].ToString());
}
};
var mainGateWay = ZbGateway.MainGateWay;
if (mainGateWay == null)
{
Console.WriteLine("没有主网关");
return sceneui;
}
mainGateWay.GwResDataAction += action;
var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 806 } };
var jObjectdata1 = new JObject { { "ScenesId", SceneId } };
jObject.Add("Data", jObjectdata1);
mainGateWay?.Send("Scene/GetDeviceList", jObject.ToString());
var dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds < 3 * 1000)
{
await System.Threading.Tasks.Task.Delay(100);
if (sceneui != null && sceneui.Id > 0)
{
break;
}
}
ZbGateway.MainGateWay.GwResDataAction -= action;
return sceneui;
});
}
#endregion
#region ----获取门锁
///
/// 获取自己+其他成员信息
///
/// 门锁Mac+端口
///
public static async System.Threading.Tasks.Task> AllMembers(string doorlockMac)
{
var userlist = new List();
///判断APP登录进来用户身份(主人,管理员,成员)
var AllUserIfon = await ReadUserListIfon(doorlockMac);
var currUserIfon = new MembershipIfon();
currUserIfon.CloudAccountId = Config.Instance.Guid;
if (string.IsNullOrEmpty(HdlUserCenterResourse.UserInfo.NickName))
{
///如果昵称为空,此时,登陆账号为默认昵称;
currUserIfon.UserName = HdlUserCenterResourse.UserInfo.Account;
}
else
{
currUserIfon.UserName = HdlUserCenterResourse.UserInfo.NickName;
}
foreach (var o in AllUserIfon)
{
if (o.IsFreezeUser || string.IsNullOrEmpty(o.UserId))
{
///过滤掉冻结的成员和UserId为空的数据;
continue;
}
if (string.IsNullOrEmpty(currUserIfon.DoorLockMacPort))
{
currUserIfon.DoorLockMacPort = o.DoorLockMacPort;
}
if (o.CloudAccountId == Config.Instance.Guid)
{
UnlockingMode unlockingMode = new UnlockingMode();
unlockingMode.OpenMode = o.OpenMode;
unlockingMode.UserId = o.UserId;
unlockingMode.ModeName = o.ModeName;
currUserIfon.UserIdMode.Add(unlockingMode);
}
}
if (currUserIfon.UserIdMode.Count != 0)
{
userlist.Add(currUserIfon);
}
if (HdlUserCenterResourse.ResidenceOption.AuthorityNo != 3)
{
List listInfo = null;
if (AllUserIfon.Count != 0)
{
//服务返回来没有门锁成员信息,没有必要再去请求成员列表,
//原因:节约时间,体验效果好;
listInfo = HdlMemberLogic.Current.GetMemberListInfo();
}
if (listInfo == null)
{
//防止为空抛异常;
return userlist;
}
for (int i = 0; i < listInfo.Count; i++)
{
var userIfon = new MembershipIfon();
//☆マーク☆
//var user = listInfo[i];
//userIfon.CloudAccountId = user.SubAccountDistributedMark;
//if (string.IsNullOrEmpty(user.UserName))
//{
// ///如果昵称为空,此时,登陆账号为默认昵称;
// userIfon.UserName = user.Account;
//}
//else
//{
// userIfon.UserName = user.UserName;
//}
for (int j = 0; j < AllUserIfon.Count; j++)
{
if (AllUserIfon[j].IsFreezeUser || string.IsNullOrEmpty(AllUserIfon[j].UserId))
{
///过滤掉冻结的成员和UserId为空的数据;
continue;
}
if (string.IsNullOrEmpty(userIfon.DoorLockMacPort))
{
userIfon.DoorLockMacPort = AllUserIfon[j].DoorLockMacPort;
}
//☆マーク☆
///查找成员以及成员门锁触发源(1按键/3卡/15指纹)
//if (user.SubAccountDistributedMark == AllUserIfon[j].CloudAccountId)
//{
// UnlockingMode unlockingMode = new UnlockingMode();
// unlockingMode.OpenMode = AllUserIfon[j].OpenMode;
// unlockingMode.UserId = AllUserIfon[j].UserId;
// unlockingMode.ModeName = AllUserIfon[j].ModeName;
// userIfon.UserIdMode.Add(unlockingMode);
//}
}
if (userIfon.UserIdMode.Count != 0)
{
//☆マーク☆
///过滤掉重复数据;
//var str = userlist.Find((c) => { return c.CloudAccountId == user.SubAccountDistributedMark; });
//if (str == null)
//{
// userlist.Add(userIfon);
//}
}
}
}
return userlist;
}
///
/// 读取门锁所有成员信息
///
/// 门锁Mac
///
public static async System.Threading.Tasks.Task> ReadUserListIfon(string doorlockMac)
{
var list = new List();
var s = await ReadUserList(doorlockMac);
var jObject = JObject.Parse(s);
if (jObject == null || jObject["StateCode"].ToString() != "Success")
{
return null;
}
var pageData = jObject["ResponseData"]["PageData"].ToString();
var datalist = JArray.Parse(pageData);
for (int i = 0; i < datalist.Count; i++)
{
var data = JObject.Parse(datalist[i].ToString());
var user = new User();
user.UserId = data["DoorLockLocalUserId"].ToString();
user.OpenMode = int.Parse(data["OpenLockMode"].ToString());
user.CloudAccountId = data["CloudAccountId"].ToString();
user.DoorLockMacPort = data["DoorLockId"].ToString();
user.ModeName = data["UserIdRemarks"].ToString();
user.IsFreezeUser = Convert.ToBoolean(data["IsFreezeUser"].ToString());
list.Add(user);
}
return list;
}
public static async System.Threading.Tasks.Task ReadUserList(string doorlockMac)
{
string s = null;
var str = await WebClientAsync(0, HdlHttpLogic.Current.RequestHttpsHost + "/App/GetHomePager");//不同区域域名前缀不一样
var jObject = JObject.Parse(str);
if (jObject == null || jObject["StateCode"].ToString() != "Success")
{
return null;
}
var pageData = jObject["ResponseData"]["PageData"].ToString();
var datalist = JArray.Parse(pageData);
for (int i = 0; i < datalist.Count; i++)
{
var data = JObject.Parse(datalist[i].ToString());
if (Config.Instance.HomeId == data["Id"].ToString())
{
Residential residential = new Residential();
if (Convert.ToBoolean(data["IsOthreShare"].ToString()))
{
//分享者ID
residential.Id = data["Id"].ToString();
//是否是分享账号[true(是分享);false;(不是分享)];
residential.IsOthreShare = Convert.ToBoolean(data["IsOthreShare"].ToString());
//分享者住宅ID
residential.MainUserDistributedMark = data["MainUserDistributedMark"].ToString();
residential.IsOtherAccountCtrl = true;
residential.doorlockmac = doorlockMac;
residential.Url = HdlHttpLogic.Current.RequestHttpsHost + "/App/GetSharedHomeApiControl";
s = await ReadUserDoorLock(residential);
}
else
{
residential.Url = HdlHttpLogic.Current.RequestHttpsHost + "/DoorLock/GetDoorLockPager";
residential.Token = Config.Instance.Token;
residential.Id = Config.Instance.HomeId;
residential.IsOtherAccountCtrl = false;
residential.doorlockmac = doorlockMac;
s = await WebClientAsync(2, residential.Url, residential);
}
}
}
return s;
}
public static async System.Threading.Tasks.Task ReadUserDoorLock(Residential residential)
{
var s = await WebClientAsync(1, residential.Url, residential);
var jObject = JObject.Parse(s);
if (jObject == null || jObject["StateCode"].ToString() != "Success")
{
return null;
}
var RequestBaseUrl = jObject["ResponseData"]["RequestBaseUrl"].ToString();
var RequestToken = jObject["ResponseData"]["RequestToken"].ToString();
Residential lockifon = new Residential();
lockifon.Url = RequestBaseUrl + "/DoorLock/GetDoorLockPager";
lockifon.Token = RequestToken;
lockifon.Id = Config.Instance.HomeId;
lockifon.IsOtherAccountCtrl = true;
lockifon.doorlockmac = residential.doorlockmac;
return await WebClientAsync(2, lockifon.Url, lockifon);
}
public class Residential
{
///
/// 住宅ID
///
public string Id = string.Empty;
///
/// 当前住宅是不是其他主帐号分享过来的
///
public bool IsOthreShare;
///
/// 当前住宅是不是其他主帐号分享过来的主帐号的分布式Id
///
public string MainUserDistributedMark = string.Empty;
public string Url = string.Empty;
public string Token = string.Empty;
public bool IsOtherAccountCtrl;
///
/// 当前门锁mac
///
public string doorlockmac;
}
public class MembershipIfon
{
///
/// 识别用户身份
///
public string CloudAccountId = string.Empty;
///
/// 门锁Mac+Port,识别门锁;
///
public string DoorLockMacPort = string.Empty;
///
/// 触发源列表
///
public List UserIdMode = new List();
///
/// 用户昵称
///
public string UserName = string.Empty;
///
/// 是否冻结该成员(true已冻结)
///
public bool IsFreezeUser;
}
public class UnlockingMode
{
///
/// 触发源ID
///
public string UserId = string.Empty;
///
/// 触发源模式(0:密码;3:卡;15:指纹;)
///
public int OpenMode;
///
/// 自定义触发源名称
///
public string ModeName = string.Empty;
}
public class User
{
///
/// 识别用户身份
///
public string CloudAccountId = string.Empty;
///
/// 触发源ID
///
public string UserId = string.Empty;
///
/// 触发源模式(0:密码;3:卡;15:指纹;)
///
public int OpenMode;
///
/// 自定义触发源名称
///
public string ModeName = string.Empty;
///
/// 门锁Mac+Port,识别门锁;
///
public string DoorLockMacPort = string.Empty;
///
/// 是否冻结该成员(true已冻结)
///
public bool IsFreezeUser;
}
///
/// 门锁列表
///
public static List LockList = new List();
///
/// 当前门锁
///
public static ZigBee.Device.DoorLock CurrentDoorLock = null;
///
/// 当前用户的信息
///
public static MemberInfoRes UserMemberInfoRes = null;
#endregion
///
/// 自己用的发送的方法
///
/// 标记是那条命令
/// 逻辑对象
public static void Zj(bool tag, Common.Logic logic)
{
if (string.IsNullOrEmpty(logic.LogicCustomPushText))
{
///默认推送自定义内容
string str = logic.LogicName + Language.StringByID(R.MyInternationalizationString.defaulttext);
logic.LogicCustomPushText = str;
}
new System.Threading.Thread(() =>
{
if (logic.LogicId != 0)
{
if (tag)
{
Data("添加/更新", "/App/HomeLogicConfig", "POST");
}
else
{
Data("删除", "/App/DelHomeLogicConfig", "POST");
}
///只改推送内容;
LogicControlSwitch(logic);
}
})
{ IsBackground = true }.Start();
}
#region 请求服务器方法---
///
/// 请求数据的封装方法
///
/// 识别命令判断字符串
/// 请求地址
/// 请求方式为POST/GET
/// 存储发送数据的对象
///
public static async System.Threading.Tasks.Task Data(string command, string url, string method, object obj = null)
{
var getUrl = "";
var jObject = new JObject();
if (HdlUserCenterResourse.ResidenceOption.AuthorityNo == 1)
{
//☆マーク☆
//getUrl = HdlHttpLogic.Current.RequestHttpsHost + url;//请求地址;
jObject.Add("IsOtherAccountCtrl", false);
jObject.Add("LoginAccessToken", Config.Instance.Token);
}
else
{
//☆マーク☆
//getUrl = Config.Instance.AdminRequestBaseUrl + url;//请求地址;
jObject.Add("IsOtherAccountCtrl", true);
//jObject.Add("LoginAccessToken", Config.Instance.AdminRequestToken);
}
switch (command)
{
case "添加/更新":
{
jObject.Add("RequestVersion", CommonPage.RequestVersion);
//jObject.Add("LoginAccessToken", Config.Instance.Token);
jObject.Add("HomeId", Config.Instance.HomeId);
jObject.Add("LogicID", Common.Logic.CurrentLogic.LogicId);
jObject.Add("PushUserIds", new JArray { Config.Instance.Guid });
jObject.Add("PushContent", Common.Logic.CurrentLogic.LogicCustomPushText);
}
break;
case "删除":
{
jObject.Add("RequestVersion", CommonPage.RequestVersion);
//jObject.Add("LoginAccessToken", Config.Instance.Token);
jObject.Add("HomeId", Config.Instance.HomeId);
jObject.Add("LogicID", Common.Logic.CurrentLogic.LogicId);
}
break;
}
return await HttpWebRequest(getUrl, jObject.ToString(), method);
}
///
/// 请求服务器的方法(支持请求方式为POST/GET)
///
/// 请求的地址
/// 请求数据
/// 请求方式为POST/GET
/// 超时时间
///
public static async System.Threading.Tasks.Task HttpWebRequest(string getUrl, string str, string method, int second = 3, bool _bool = false)
{
try
{
HttpWebRequest request = WebRequest.Create(getUrl) as HttpWebRequest; //创建请求
request.Method = method; //请求方式为POST/GET
request.ContentType = "application/json";
request.Timeout = second * 1000;//超时时间
if (_bool)
{
//用于高胜可视对讲接口
request.Headers.Add("Authorization", Config.Instance.Token);
}
if (method == "POST")
{
byte[] jsonbyte = System.Text.Encoding.UTF8.GetBytes(str);
request.ContentLength = jsonbyte.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, 0, jsonbyte.Length);
postStream.Close();
}
//发送请求并获取相应回应数据
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
string content = sr.ReadToEnd(); //获得响应字符串
return content;
}
catch
{
return null;
}
}
///
/// 请求服务器的方法
///
/// 区分发送命令的数据判断值
/// 请求的地址
/// 装数据的对象
///
public static async System.Threading.Tasks.Task WebClientAsync(int value, string url, Residential residential = null)
{
NameValueCollection postValues = new NameValueCollection();
switch (value)
{
case 0:
{
postValues.Add("RequestVersion", CommonPage.RequestVersion);
postValues.Add("ReqDto.LoginAccessToken", Config.Instance.Token);
postValues.Add("ReqDto.PageSetting.PageSize", Int32.MaxValue.ToString());//
}
break;
case 1:
{
postValues.Add("RequestVersion", CommonPage.RequestVersion);
postValues.Add("LoginAccessToken", Config.Instance.Token);
postValues.Add("MainAccountId", residential.MainUserDistributedMark);
postValues.Add("SharedHid", residential.Id);
}
break;
case 2:
{
postValues.Add("RequestVersion", CommonPage.RequestVersion);
postValues.Add("LoginAccessToken", residential.Token);
postValues.Add("HomeId", residential.Id);
postValues.Add("DoorLockId", residential.doorlockmac);//门锁Mac+端口
postValues.Add("IsOtherAccountCtrl", residential.IsOtherAccountCtrl.ToString());
postValues.Add("PageSetting.PageSize", Int32.MaxValue.ToString());
}
break;
}
//PrintKeysAndValues2(postValues);
System.Net.WebClient webClient = new System.Net.WebClient();
byte[] responseArray = webClient.UploadValues(url, postValues);
var s = System.Text.Encoding.UTF8.GetString(responseArray);
return s;
}
#endregion
#region 存取本地文件的方法 ---暂时不用合并该方法---
///
/// 判断是否开启GPS服务
///
public static string If_Exist
{
get
{
string value = ReadLocalFile(Config.Instance.HomeId+"_GPS_File");
//读取本地GPS服务状态
if (value == "0"||string.IsNullOrEmpty(value))
{
return "0";
}
return "1";
}
}
///
/// 文件保存
///
/// 文件路径
/// 需要序列化数据
public static void SaveLocalFile(string FileName, object obj)
{
//先序列化数据;
var data = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
//数据转换为字节流;
var byteData = System.Text.Encoding.UTF8.GetBytes(data);
//写入数据;
Shared.IO.FileUtils.WriteFileByBytes(FileName, byteData);
}
///
/// 文件保存
///
/// 文件路径
/// 字符串
public static void SaveLocalFile(string FileName, string data)
{
//先序列化数据;
//数据转换为字节流;
var byteData = System.Text.Encoding.UTF8.GetBytes(data);
//写入数据;
Shared.IO.FileUtils.WriteFileByBytes(FileName, byteData);
}
///
/// 文件读取
///
/// 文件路径
///
public static string ReadLocalFile(string FileName)
{
//读出保存该路径的文件;
var varByte = Shared.IO.FileUtils.ReadFile(FileName);
//字节流转换为字符串;
return System.Text.Encoding.UTF8.GetString(varByte);
}
#endregion
///
/// 判断字典是否存在的方法
///
///
/// 键
/// 键值
public static void dictionary(Dictionary deviceConditionsInfo, string Key, string Value)
{
if (deviceConditionsInfo.ContainsKey(Key))
{
deviceConditionsInfo.Remove(Key);
}
deviceConditionsInfo.Add(Key, Value);
}
}
}