gxc
2019-10-29 081ea8d273048fd03756718ac6fb48a3c09218e9
ZigbeeApp/Shared/Phone/Device/Logic/Send.cs
@@ -3,16 +3,18 @@
using Newtonsoft.Json.Linq;
using ZigBee.Device;
using ZigBee.Common;
using Shared.Common;
namespace Shared.Phone.Device.Logic
{
    public class Send
    {
        /// <summary>
        /// 获取LogicId的方法
        /// </summary>
        /// <returns>The logic identifier.</returns>
        public static async System.Threading.Tasks.Task<List<int>> GetLogicId()
        public static async System.Threading.Tasks.Task<List<int>> GetLogicId(int LogicType)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
@@ -51,6 +53,8 @@
                mainGateWay.GwResDataAction += action;
                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());
                //await System.Threading.Tasks.Task.Run(async () =>
                //{
@@ -72,7 +76,7 @@
        /// 获取Logic的方法
        /// </summary>
        /// <returns>The logic identifier.</returns>
        public static async System.Threading.Tasks.Task<Common.Logic> GetLogic(int LogicId)
        public static async System.Threading.Tasks.Task<Common.Logic> GetLogic(int LogicId,int LogicType)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
@@ -97,8 +101,9 @@
                        logic.LogicName = Logicifon["LogicName"]?.ToString();
                        logic.Relationship = int.Parse(Logicifon["Relationship"]?.ToString());
                        logic.TimeAttribute = Newtonsoft.Json.JsonConvert.DeserializeObject<Common.TimeAttributeObj>(Logicifon["TimeAttribute"].ToString());
                        logic.TimeAttribute = Newtonsoft.Json.JsonConvert.DeserializeObject<TimeAttributeObj>(Logicifon["TimeAttribute"].ToString());
                        logic.Conditions = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(Logicifon["Conditions"].ToString());
                        logic.Accounts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(Logicifon["Accounts"].ToString());
                        var listactions = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(Logicifon["Actions"].ToString());
                        if (listactions != null)
                        {
@@ -133,7 +138,7 @@
                        }
                    };
                    }
                };
                var mainGateWay = ZbGateway.MainGateWay;
                if (mainGateWay == null)
@@ -146,7 +151,8 @@
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2002 } };
                    var data = new JObject {
                        { "LogicId",LogicId}
                        { "LogicId",LogicId},
                        { "LogicType",LogicType}
                        };
                    jObject.Add("Data", data);
                    ZbGateway.MainGateWay?.Send("Logic/GetLogicInfo", jObject.ToString());
@@ -251,10 +257,6 @@
                try
                {
                    //var bytes = new byte[64];
                    //var LogicNameBytes = System.Text.Encoding.UTF8.GetBytes(logic.LogicName);
                    //Array.Copy(LogicNameBytes, 0, bytes, 0, 64 < LogicNameBytes.Length ? 64 : LogicNameBytes.Length);
                    //logic.LogicName = System.Text.Encoding.UTF8.GetString(bytes);
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2000 } };
                    var selectMonthList = new JArray { };
@@ -310,8 +312,13 @@
                                    ["AttriButeId"] = int.Parse(dictionary["AttriButeId"]),
                                    ["AttriButeData1"] = int.Parse(dictionary["AttriButeData1"]),
                                    ["AttriButeData2"] = int.Parse(dictionary["AttriButeData2"]),
                                    ["Range"] = int.Parse(dictionary["Range"]),
                                    ["Range"] = int.Parse(dictionary["Range"])
                                };
                                if (dictionary.ContainsKey("IgnoreTime"))
                                {
                                    dInfo.Add("IgnoreTime", int.Parse(dictionary["IgnoreTime"]));
                                }
                                conditions.Add(dInfo);
                                break;
                            case 2:
@@ -434,16 +441,51 @@
                                };
                                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;
                        }
                    }
                    var accounts = new JArray();
                    foreach (var dictionary in logic.Accounts) {
                        var Type = int.Parse(dictionary["Type"]);
                        switch (Type)
                        {
                            case 1: {
                                    ///
                                } 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;
                        }
                    }
                    var data = new JObject{
                        { "LogicId",logic.LogicId},
                        { "IsEnable", logic.IsEnable} ,
                        { "LogicName", logic.LogicName},
                        { "Relationship",logic.Relationship} ,
                        { "LogicCustomPushText",logic.LogicCustomPushText} ,
                        { "TimeAttribute", timeAttribute} ,
                        { "Conditions", conditions },
                        { "Actions", actions },
                        { "Accounts", accounts },
                    };
                    jObject.Add("Data", data);
                    ZbGateway.MainGateWay?.Send("Logic/AddLogic", jObject.ToString());
@@ -503,8 +545,9 @@
                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("LogicName", logic.LogicName);
                date.Add("Relationship", logic.Relationship);
                date.Add("LogicCustomPushText", logic.LogicCustomPushText);
                mainGateWay?.Send("Logic/ReviseAttribute", jObject.ToString());
                //await System.Threading.Tasks.Task.Run(async () =>
                //{
@@ -526,13 +569,13 @@
        /// 获取Logic列表的方法
        /// </summary>
        /// <returns>The logic identifier.</returns>
        public static async System.Threading.Tasks.Task<List<Common.Logic>> ReadList(int sum)
        public static async System.Threading.Tasks.Task<List<Common.Logic>> ReadList(int sum,int LogicType)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                var listLogic = new List<Common.Logic>();
                bool @bool = false;
               // bool @bool = false;
                Action<string, string> action = (topic, data) =>
                {
                    var gatewayID = topic.Split('/')[0];
@@ -550,6 +593,7 @@
                        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.TimeAttribute = Newtonsoft.Json.JsonConvert.DeserializeObject<Common.TimeAttributeObj>(Logicifon["TimeAttribute"].ToString());
                        logic.Conditions = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(Logicifon["Conditions"].ToString());
@@ -599,10 +643,10 @@
                        }
                    }
                    if (topic == $"{gatewayID}/Logic/AllLogicNum_Respon")
                    {
                        @bool = true;
                    }
                    //if (topic == $"{gatewayID}/Logic/AllLogicNum_Respon")
                    //{
                    //    @bool = true;
                    //}
                };
                var mainGateWay = ZbGateway.MainGateWay;
                if (mainGateWay == null)
@@ -614,6 +658,8 @@
                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 { }
@@ -621,28 +667,241 @@
                while ((DateTime.Now - dateTime).TotalMilliseconds < 8 * 1000)
                {
                    await System.Threading.Tasks.Task.Delay(100);
                    //if (sum == listLogic.Count)
                    //{
                    //    break;
                    //}
                    if (@bool)
                    if (sum == listLogic.Count)
                    {
                        break;
                    }
                    //if (@bool)
                    //{
                    //    break;
                    //}
                }
                ZbGateway.MainGateWay.GwResDataAction -= action;
                return listLogic;
            });
        }
        // <summary>
        /// 通过设备找到区域(房间)名称
        /// 通过设备找到区域(房间)名称
        /// </summary>
        /// <param name="btnregionname">Btnregionname.</param>
        /// <param name="device">Device.</param>
        public static void RoomNmae(Button btnregionname, CommonDevice device)
        {
            var room = new Common.Room();
            var room = new Common.Room();
            btnregionname.Text = room.GetRoomNameByDevice(device);
        }
        public static List<Common.Room> GetRoomList(string floorId)
        {
            return Common.Room.Lists.FindAll((obj) => obj.FloorId == floorId);
        }
        #region  ----获取门锁
        public static List<DoorLock> ReadDoorLockIfon(string doorlockMac)
        {
            List<DoorLock> list = new List<DoorLock>();
            string url = "https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetHomePager";//子账号和主账号可能链接不同
            System.Net.WebClient webClient = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection postValues = new System.Collections.Specialized.NameValueCollection();
            postValues.Add("RequestVersion", CommonPage.RequestVersion);
            postValues.Add("ReqDto.LoginAccessToken", Config.Instance.Token);
            System.Threading.Tasks.Task.Run(() =>
           {
               try
               {
                   byte[] responseArray = webClient.UploadValues(url, postValues);
                   var str = System.Text.Encoding.UTF8.GetString(responseArray);
                   var jObject = JObject.Parse(str);
                   if (jObject == null || jObject["StateCode"].ToString() != "Success")
                   {
                       return;
                   }
                   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;
                               list = ReadToken(residential);
                           }
                           else
                           {
                               residential.Url = "https://global.hdlcontrol.com/HangZhouHdlCloudApi/DoorLock/GetDoorLockPager";
                               residential.Token = Config.Instance.Token;
                               residential.Id = Config.Instance.HomeId;
                               residential.IsOtherAccountCtrl = false;
                               residential.doorlockmac = doorlockMac;
                               list = ReadDoorLock(residential);
                           }
                       }
                   }
               }
               catch { }
           });
            var datetime = DateTime.Now;
            while ((DateTime.Now - datetime).TotalMilliseconds < 3*1000)
            {
                if (list.Count != 0)
                {
                    break;
                }
            }
            return list;
        }
        public static List<DoorLock> ReadToken(Residential residential)
        {
            List<DoorLock> list = new List<DoorLock>();
            string url = "https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSharedHomeApiControl";
            System.Net.WebClient webClient = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection postValues = new System.Collections.Specialized.NameValueCollection();
            postValues.Add("RequestVersion", CommonPage.RequestVersion);
            postValues.Add("LoginAccessToken", Config.Instance.Token);
            postValues.Add("MainAccountId", residential.MainUserDistributedMark);
            postValues.Add("SharedHid", residential.Id);
            System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    byte[] responseArray = webClient.UploadValues(url, postValues);
                    var str = System.Text.Encoding.UTF8.GetString(responseArray);
                    var jObject = JObject.Parse(str);
                    if (jObject == null || jObject["StateCode"].ToString() != "Success")
                    {
                        return;
                    }
                    var RequestBaseUrl = jObject["ResponseData"]["RequestBaseUrl"].ToString();
                    var RequestToken = jObject["ResponseData"]["RequestToken"].ToString();
                    Residential lockifon = new Residential();
                    lockifon.Url = RequestBaseUrl + "/App/GetDoorLockPager";
                    lockifon.Token = RequestToken;
                    lockifon.Id = Config.Instance.HomeId;
                    lockifon.IsOtherAccountCtrl = true;
                    lockifon.doorlockmac = residential.doorlockmac;
                    list = ReadDoorLock(lockifon);
                }
                catch { }
            });
            var datetime = DateTime.Now;
            while ((DateTime.Now - datetime).TotalMilliseconds < 3 * 1000)
            {
                if (list.Count != 0)
                {
                    break;
                }
            }
            return list;
        }
        public static List<DoorLock> ReadDoorLock(Residential lockifon)
        {
            List<DoorLock> list = new List<DoorLock>();
            System.Net.WebClient webClient = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection postValues = new System.Collections.Specialized.NameValueCollection();
            postValues.Add("RequestVersion", CommonPage.RequestVersion);
            postValues.Add("LoginAccessToken", lockifon.Token);
            postValues.Add("HomeId", lockifon.Id);
            postValues.Add("DoorLockId", lockifon.doorlockmac);//门锁Mac19091
            postValues.Add("IsOtherAccountCtrl", lockifon.IsOtherAccountCtrl.ToString());
            System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    byte[] responseArray = webClient.UploadValues(lockifon.Url, postValues);
                    var str = System.Text.Encoding.UTF8.GetString(responseArray);
                    var jObject = JObject.Parse(str);
                    if (jObject == null || jObject["StateCode"].ToString() != "Success")
                    {
                        return;
                    }
                    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());
                        DoorLock doorLock = new DoorLock();
                        doorLock.DoorLockLocalUserId = data["DoorLockLocalUserId"].ToString();
                        doorLock.OpenLockMode = int.Parse(data["OpenLockMode"].ToString());
                        doorLock.CloudAccountId = data["CloudAccountId"].ToString();
                        list.Add(doorLock);
                    }
                }
                catch
                {
                }
            });
            var datetime = DateTime.Now;
            while ((DateTime.Now - datetime).TotalMilliseconds < 3 * 1000)
            {
                if (list.Count != 0)
                {
                    break;
                }
            }
            return list;
        }
        public class Residential
        {
            public string Id = string.Empty;
            public bool IsOthreShare;
            public string MainUserDistributedMark = string.Empty;
            public string Url = string.Empty;
            public string Token = string.Empty;
            public bool IsOtherAccountCtrl;
            public string doorlockmac;
        }
        public class DoorLock
        {
            public string DoorLockLocalUserId = string.Empty;
            public int OpenLockMode;
            public string CloudAccountId = string.Empty;
            /// <summary>
            /// 身份+触发源(0按键/3卡/15指纹)
            /// </summary>
            public string UserIdMode
            {
                get
                {
                    return DoorLockLocalUserId + "_" + OpenLockMode.ToString();
                }
            }
        }
        public class MembershipIfon
        {
            public string MembershipId = string.Empty;
            public List<string> UserIdMode=new List<string>();
            public string MembershipName = string.Empty;
        }
        public static List<MembershipIfon> UserList = new List<MembershipIfon>();
        #endregion
    }
}