陈嘉乐
2020-09-02 652243206427f35a256400a149a1734085824cb9
ZigbeeApp/Shared/Phone/Device/Logic/Send.cs
old mode 100644 new mode 100755
@@ -12,7 +12,8 @@
{
    public class Send
    {
        #region  ----获取Logic
        #region  ----Logic所有发送命令
        /// <summary>
        /// 获取LogicId的方法
        /// </summary>
@@ -22,6 +23,9 @@
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                List<int> logicIdList = new List<int>();
                bool if_theme = false;
                int if_number = -1;
                Action<string, string> action = (topic, data) =>
                {
                    var gatewayID = topic.Split('/')[0];
@@ -30,21 +34,22 @@
                    {
                        return;
                    }
                    if (topic == $"{gatewayID}/Logic/GetLogicList_Respon")
                    {
                        var list = jObjectdata["Data"]["LogicList"];
                        if (list == null)
                        if_theme = true;
                        var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jObjectdata["Data"]["LogicList"].ToString());
                        if_number = list.Count;
                        if (list.Count == 0)
                        {
                            return;
                        }
                        foreach (var listIfon in list)
                        {
                            var logicId = int.Parse(listIfon["LogicId"].ToString());
                            var logicId = int.Parse(listIfon["LogicId"]);
                            logicIdList.Add(logicId);
                        }
                    }
                };
                var mainGateWay = ZbGateway.MainGateWay;
@@ -54,20 +59,29 @@
                    return logicIdList;
                }
                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());
                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 (logicIdList.Count != 0)
                    if (if_theme)
                    {
                        break;
                        if (if_number == 0 || if_number == logicIdList.Count)
                        {
                            break;//回复没有数据立刻返回
                        }
                    }
                }
                ZbGateway.MainGateWay.GwResDataAction -= action;
@@ -96,7 +110,6 @@
                    if (topic == $"{gatewayID}/Logic/GetLogicInfo_Respon")
                    {
                        logic = new Common.Logic();
                        var Logicifon = jObjectdata["Data"];
                        logic.LogicId = int.Parse(Logicifon["LogicId"]?.ToString());
@@ -175,7 +188,7 @@
            });
        }
        ///<summary>
        /// 删除逻辑
        /// 删除逻辑(0成功,其它值:失败)
        /// </summary>
        public static async System.Threading.Tasks.Task<int> DelLogic(int LogicId)
        {
@@ -241,7 +254,6 @@
                    {
                        try
                        {
                            Logicifon = new Common.Logic();
                            Logicifon = Newtonsoft.Json.JsonConvert.DeserializeObject<Common.Logic>(jObjectdata["Data"].ToString());
                        }
                        catch (Exception ex)
@@ -260,7 +272,7 @@
                try
                {
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 2000 } };
                    var selectMonthList = new JArray { };
                    foreach (var intvalue in logic.TimeAttribute.SelectMonDate)
@@ -292,6 +304,7 @@
                                    ["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")
                                {
@@ -388,7 +401,7 @@
                                    ["Type"] = int.Parse(dictionary["Type"]),
                                    ["IsValid"] = int.Parse(dictionary["IsValid"]),
                                    ["AtHome"] = int.Parse(dictionary["AtHome"]),
                                    ["WhoSiteUId"] =dictionary["WhoSiteUId"],
                                    ["WhoSiteUId"] = dictionary["WhoSiteUId"],
                                };
                                conditions.Add(diliInfo);
                                break;
@@ -462,6 +475,16 @@
                                };
                                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();
@@ -480,8 +503,18 @@
                                            ["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);
                                    }
                                }
@@ -500,9 +533,28 @@
                                    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} ,
@@ -605,7 +657,6 @@
            {
                var listLogic = new List<Common.Logic>();
                // bool @bool = false;
                Action<string, string> action = (topic, data) =>
                {
                    var gatewayID = topic.Split('/')[0];
@@ -617,7 +668,6 @@
                    if (topic == $"{gatewayID}/Logic/GetAllLogicListInfo_Respon")
                    {
                        var logic = new Common.Logic();
                        var Logicifon = jObjectdata["Data"];
                        logic.LogicId = int.Parse(Logicifon["LogicId"].ToString());
@@ -625,7 +675,7 @@
                        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.LogicCustomPushText = Logicifon["LogicCustomPushText"].ToString();
                        logic.LogicIsCustomPushText = int.Parse(Logicifon["LogicIsCustomPushText"].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());
@@ -676,10 +726,7 @@
                        }
                    }
                    //if (topic == $"{gatewayID}/Logic/AllLogicNum_Respon")
                    //{
                    //    @bool = true;
                    //}
                };
                var mainGateWay = ZbGateway.MainGateWay;
                if (mainGateWay == null)
@@ -697,60 +744,18 @@
                }
                catch { }
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < 8 * 1000)
                while ((DateTime.Now - dateTime).TotalMilliseconds < 5* 1000)
                {
                    await System.Threading.Tasks.Task.Delay(100);
                    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();
            btnregionname.Text = room.GetRoomNameByDevice(device);
        }
        public static List<Common.Room> GetRoomList(string floorId)
        {
            return Common.Room.Lists.FindAll((obj) => obj.FloorId == floorId);
            //var list1 = new List<Common.Room>();
            /////找到某楼层房间列表;
            //var list = Common.Room.Lists.FindAll((obj) => obj.FloorId == floorId);
            //for (int i = 0; i < list.Count; i++)
            //{
            //    if (str == "device")
            //    {
            //        if (list[i].DeviceUIList.Count != 0)
            //        {   ///过滤掉没有设备的房间
            //            list1.Add(list[i]);
            //        }
            //    }
            //    else
            //    {
            //        if (list[i].SceneUIList.Count != 0)
            //        {   ///过滤掉没有场景的房间
            //            list1.Add(list[i]);
            //        }
            //    }
            //}
            /////返回房间列表;
            //return list1;
        }
        /// <summary>
        /// 获取场景信息的方法
@@ -776,7 +781,7 @@
                        sceneui = new SceneUI();
                        sceneui.Name = jObjectdata["Data"]["ScenesName"].ToString();
                        sceneui.Id = int.Parse(jObjectdata["Data"]["ScenesId"].ToString());
                    }
                };
                var mainGateWay = ZbGateway.MainGateWay;
@@ -795,7 +800,7 @@
                while ((DateTime.Now - dateTime).TotalMilliseconds < 3 * 1000)
                {
                    await System.Threading.Tasks.Task.Delay(100);
                    if (sceneui!=null)
                    if (sceneui != null && sceneui.Id > 0)
                    {
                        break;
                    }
@@ -807,7 +812,7 @@
        #endregion
        #region  ----获取门锁
        /// <summary>
        /// 获取自己+其他成员信息
        /// </summary>
@@ -858,8 +863,24 @@
            if (UserCenter.UserCenterResourse.UserInfo.AuthorityNo != 3)
            {
                var pra = new UserCenter.MemberListInfoPra();
                string result = await UserCenter.UserCenterLogic.GetResponseDataByRequestHttps("ZigbeeUsers/GetSubAccountByDistributedMark", false, pra);
                var listInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<List<UserCenter.MemberInfoRes>>(result);
                string result = "";
                if (AllUserIfon.Count != 0)
                {
                    //服务返回来没有门锁成员信息,没有必要再去请求成员列表,
                    //原因:节约时间,体验效果好;
                    result = UserCenter.UserCenterLogic.GetResponseDataByRequestHttps("ZigbeeUsers/GetSubAccountByDistributedMark", false, pra);
                }
                if (string.IsNullOrEmpty(result))
                {
                    //防止为空抛异常;
                    return userlist;
                }
                var listInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<List<UserCenter.MemberInfoRes>>(result);
                if (listInfo == null)
                {
                    //防止为空抛异常;
                    return userlist;
                }
                for (int i = 0; i < listInfo.Count; i++)
                {
@@ -949,7 +970,7 @@
        {
            string s = null;
            var str = await WebClientAsync(0, CommonPage.RequestHttpsHost + "/App/GetHomePager");//不同区域域名前缀不一样
           // var str = await WebClientAsync(0, "https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetHomePager");
            var jObject = JObject.Parse(str);
            if (jObject == null || jObject["StateCode"].ToString() != "Success")
            {
@@ -974,13 +995,11 @@
                        residential.IsOtherAccountCtrl = true;
                        residential.doorlockmac = doorlockMac;
                        residential.Url = CommonPage.RequestHttpsHost + "/App/GetSharedHomeApiControl";
                        //residential.Url = "https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSharedHomeApiControl";
                        s = await ReadUserDoorLock(residential);
                    }
                    else
                    {
                        residential.Url = CommonPage.RequestHttpsHost + "/DoorLock/GetDoorLockPager";
                        //residential.Url = "https://global.hdlcontrol.com/HangZhouHdlCloudApi/DoorLock/GetDoorLockPager";
                        residential.Token = Config.Instance.Token;
                        residential.Id = Config.Instance.HomeId;
                        residential.IsOtherAccountCtrl = false;
@@ -1013,16 +1032,7 @@
            lockifon.doorlockmac = residential.doorlockmac;
            return await WebClientAsync(2, lockifon.Url, lockifon);
        }
        //打印NameValueCollection()显示索引, 键,值
        public static void PrintKeysAndValues2(NameValueCollection myCol)
        {
            for (int i = 0; i < myCol.Count; i++)
            {
                //打印显示索引, 键,值
                Console.WriteLine("[{0}]{1,-10} {2}", i, myCol.GetKey(i), myCol.Get(i));
            }
        }
        public class Residential
        {
            /// <summary>
@@ -1131,6 +1141,41 @@
        public static UserCenter.MemberInfoRes UserMemberInfoRes = null;
        #endregion
        /// <summary>
        /// 自己用的发送的方法
        /// </summary>
        /// <param name="tag">标记是那条命令</param>
        /// <param name="logic">逻辑对象</param>
        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  请求服务器方法---
        /// <summary>
        /// 请求数据的封装方法
@@ -1140,9 +1185,9 @@
        /// <param name="method">请求方式为POST/GET</param>
        /// <param name="obj">存储发送数据的对象</param>
        /// <returns></returns>
        public static async System.Threading.Tasks.Task<string>Data(string command, string url, string method, object obj = null)
        public static async System.Threading.Tasks.Task<string> Data(string command, string url, string method, object obj = null)
        {
            var getUrl ="";
            var getUrl = "";
            var jObject = new JObject();
            if (UserCenter.UserCenterResourse.UserInfo.AuthorityNo == 1)
            {
@@ -1187,33 +1232,45 @@
        /// <param name="method">请求方式为POST/GET</param>
        /// <param name="second">超时时间</param>
        /// <returns></returns>
        public static async System.Threading.Tasks.Task<string>HttpWebRequest(string getUrl, string str, string method,int second= 3)
        public static async System.Threading.Tasks.Task<string> HttpWebRequest(string getUrl, string str, string method, int second = 3, bool _bool = false)
        {
            HttpWebRequest request = WebRequest.Create(getUrl) as HttpWebRequest; //创建请求
            request.Method = method; //请求方式为POST/GET
            request.ContentType = "application/json";
            request.Timeout = second * 1000;//超时时间
            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();
            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;
            }
            //发送请求并获取相应回应数据
            HttpWebResponse res;
            try
            {
                res = (HttpWebResponse)request.GetResponse();
            catch
            {
                return null;
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
            StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
            string content = sr.ReadToEnd(); //获得响应字符串
            return content;
        }
        /// <summary>
        /// 请求服务器的方法
@@ -1240,7 +1297,6 @@
                        postValues.Add("LoginAccessToken", Config.Instance.Token);
                        postValues.Add("MainAccountId", residential.MainUserDistributedMark);
                        postValues.Add("SharedHid", residential.Id);
                    }
                    break;
                case 2:
@@ -1264,6 +1320,23 @@
        #region  存取本地文件的方法 ---暂时不用合并该方法---
        /// <summary>
        /// 判断是否开启GPS服务
        /// </summary>
        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";
            }
        }
        /// <summary>
        /// 文件保存
        /// </summary>
        /// <param name="FileName">文件路径</param>
@@ -1277,7 +1350,19 @@
            //写入数据;
            Shared.IO.FileUtils.WriteFileByBytes(FileName, byteData);
        }
        /// <summary>
        /// 文件保存
        /// </summary>
        /// <param name="FileName">文件路径</param>
        /// <param name="data">字符串</param>
        public static void SaveLocalFile(string FileName, string data)
        {
            //先序列化数据;
            //数据转换为字节流;
            var byteData = System.Text.Encoding.UTF8.GetBytes(data);
            //写入数据;
            Shared.IO.FileUtils.WriteFileByBytes(FileName, byteData);
        }
        /// <summary>
        /// 文件读取
        /// </summary>
@@ -1285,16 +1370,28 @@
        /// <returns></returns>
        public static string ReadLocalFile(string FileName)
        {
            if (System.IO.File.Exists(FileName) == false)
            {
                ///判断是否有文件;
                return null;
            }
            //读出保存该路径的文件;
            var varByte = Shared.IO.FileUtils.ReadFile(FileName);
            //字节流转换为字符串;
            return System.Text.Encoding.UTF8.GetString(varByte);
        }
        #endregion
        /// <summary>
        /// 判断字典是否存在的方法
        /// </summary>
        /// <param name="deviceConditionsInfo"></param>
        /// <param name="Key">键</param>
        /// <param name="Value">键值</param>
        public static void dictionary(Dictionary<string, string> deviceConditionsInfo, string Key, string Value)
        {
            if (deviceConditionsInfo.ContainsKey(Key))
            {
                deviceConditionsInfo.Remove(Key);
            }
            deviceConditionsInfo.Add(Key, Value);
        }
    }
}