wei
2020-12-22 d07d62be7111d78b2aaa44c9cdee23a7d22b4dda
HDL_ON/Entity/Function/Scene.cs
@@ -1,45 +1,137 @@
using System;
using System.Collections.Generic;
using HDL_ON.DAL.Server;
using Shared;
namespace HDL_ON.Entity
{
    public class Scene : Function
    public class SceneApiPack
    {
        static SceneApiPack _ScenePack;
        public static SceneApiPack ScenePack
        {
            get
            {
                if(_ScenePack == null)
                {
                    _ScenePack = new SceneApiPack();
                }
                return _ScenePack;
            }
        }
    }
    public class Scene
    {
        public Scene()
        {
            sid = NewSid();
            if (!DB_ResidenceData.Instance.CheckWhetherGatewayIdIsNull())
            {
                gatewayId = DB_ResidenceData.Instance.HomeGateway.gatewayId;
            }
        }
        /// <summary>
        /// 云端唯一ID
        /// </summary>
        public string userSceneId = null;
        /// <summary>
        /// 场景sid
        /// </summary>
        public string sid = "";
        /// <summary>
        /// 场景名称
        /// </summary>
        public string name = "";
        /// <summary>
        /// 网关ID
        /// </summary>
        public string gatewayId = "";
        /// <summary>
        /// 云端oss存储图片的路径
        /// </summary>
        public string image = "";
        /// <summary>
        /// 所属房间列表
        /// </summary>
        public List<string> roomIds = new List<string>();
        /// <summary>
        /// 所属房间列表
        /// </summary>
        public List<string> uids = new List<string>();
        /// <summary>
        /// 延时
        /// </summary>
        public string delay = "0";
        /// <summary>
        /// 场景的最好一次执行时间
        /// </summary>
        public string LastExecutionTime = "";
        /// <summary>
        /// 场景分组
        /// </summary>
        public string group = "1";
        /// <summary>
        /// 场景类型
        /// </summary>
        public SceneType sceneType = SceneType.OrdinaryScenes;
        /// <summary>
        /// 场景背景
        /// 收藏标记
        /// </summary>
        public string ImagePath = "Intelligence/Gallery/scenebg1.png";//"FunctionIcon/Scene/s1.png";
        public bool collect = false;
        ///// <summary>
        ///// 场景背景
        ///// </summary>
        //public string ImagePath = "Intelligence/Gallery/scenebg1.png";//"FunctionIcon/Scene/s1.png";
        ///// <summary>
        ///// 场景背景
        ///// </summary>
        public string ImagePath
        {
            get
            {
                if (string.IsNullOrEmpty(image))
                {
                    return "Intelligence/Gallery/scenebg1.png";
                }
                else
                {
                    return image;
                }
            }
            set
            {
                image = value;
            }
        }
        /// <summary>
        /// 场景功能列表
        /// </summary>
        public List<Function> sceneFunctionList = new List<Function>();
        public List<SceneFunction> functions = new List<SceneFunction>();
        /// <summary>
        /// 场景推送配置列表
        /// </summary>
        public List<ScenePushConfig> pushConfigs = new List<ScenePushConfig>();
        /// <summary>
        /// 生成场景sid
        /// 生成逻辑sid方法
        /// </summary>
        public void NewSid()
        public string NewSid()
        {
            string sSceneid = "";
            string sceneId = "";
            try
            {
                string sOidBeginsWith = "000101";//厂商 + 通讯方式
                DateTime dt = DateTime.Now;
                DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(2020, 1, 1));
                long m = (long)((dt - startTime).TotalMilliseconds / 10);
                string sTimeSpan = "00000000";
                byte[] arry = new byte[4];
                arry[0] = (byte)(m & 0xFF);
@@ -53,239 +145,305 @@
                {
                    sTimeSpan = sTimeSpan.Substring(0, 8);
                }
                else
                else
                {
                    sTimeSpan = "00000000";
                }
                sSceneid = sOidBeginsWith + sTimeSpan;
                sceneId = sOidBeginsWith + sTimeSpan;
                sSceneid += "0A";
                sSceneid += "0A01";
                //0A01 物模型为场景, 0001 表示 1 号场景功能
                int iTopSceneId = 1;
                sceneId += "0A";
                sceneId += "0A01";
                int maxId = 1;
                Random random = new Random();
                iTopSceneId = random.Next(0, 255);
                iTopSceneId += random.Next(0, 255);
                sSceneid += iTopSceneId.ToString("X4");//场景号 两个byte
                sSceneid += "1100";
                sid = sSceneid;
                for (int i = 0; i < FunctionList.List.scenes.Count; i++)
                {
                    string s = FunctionList.List.scenes[i].sid.Substring(20, 4);
                    int iThisSceneId = Convert.ToInt16(s, 16);
                    if (iThisSceneId > maxId)
                        maxId = iThisSceneId;
                }
                sceneId += (maxId + 1).ToString("X4");
                sceneId += "0000";
            }
            catch
            {
                sid = sSceneid;
                return sceneId;
            }
            return sceneId;
        }
        /// <summary>
        /// 获取设备添加到房间的房间名称
        /// </summary>
        /// <returns></returns>
        public string GetRoomListName()
        {
            string roomNameList = "";
            foreach (var roomId in roomIds)
            {
                var findRoom = SpatialInfo.CurrentSpatial.RoomList.Find(obj => obj.roomId == roomId);
                if (findRoom == null)
                {
                    continue;
                }
                if (roomNameList != "")
                {
                    roomNameList += ",";
                }
                roomNameList += findRoom.floorName + findRoom.roomName;
            }
            if (roomNameList == "" )
            {
                roomNameList = Shared.Language.StringByID(StringId.WholeZone);
            }
            return roomNameList;
        }
        /// <summary>
        /// 数据存储文件名
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public string savePath
        {
            get
            {
                return "SceneData_" + sid;
            }
        }
        /// <summary>
        /// 场景执行\倒计时
        /// </summary>
        /// <param name="btnShowDelay"></param>
        public void SceneCountDown(Button btnShowDelay)
        {
            //场景正在倒计时执行中
            if (LastExecutionTime != "" && Convert.ToDouble(LastExecutionTime) + Convert.ToDouble(delay) > Convert.ToDouble(Utlis.GetTimestamp(false)))
            {
                int time = 0;
                int.TryParse(Convert.ToInt32(
                    Convert.ToDouble(LastExecutionTime) + Convert.ToDouble(delay) - Convert.ToDouble(Utlis.GetTimestamp(false))
                    ).ToString(), out time);
                if (time > 0)
                {
                    new System.Threading.Thread(() =>
                    {
                        if (time > 0)
                        {
                            while (time > 0)
                            {
                                Application.RunOnMainThread(() =>
                                {
                                    if (time > 60)
                                    {
                                        btnShowDelay.Text = (time / 60).ToString() + "min" + time % 60 + "s";
                                    }
                                    else
                                    {
                                        btnShowDelay.Text = time.ToString() + "s";
                                    }
                                });
                                System.Threading.Thread.Sleep(1000);
                                time--;
                            }
                            Application.RunOnMainThread(() =>
                            {
                                btnShowDelay.Text = "";
                            });
                        }
                    })
                    { IsBackground = true, Priority = System.Threading.ThreadPriority.BelowNormal }.Start();
                }
            }
        }
        /// <summary>
        /// 保存功能数据
        /// </summary>
        public void SaveSceneData(bool upServer)
        {
            if (upServer)
            {
                UploadScene();
            }
            else
            {
                var ssd = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(this));
                Common.FileUtlis.Files.WriteFileByBytes(savePath, ssd);
                MainPage.Log($"Save Scene Data : {savePath}");
            }
        }
        /// <summary>
        /// 收藏场景
        /// </summary>
        /// <returns></returns>
        public string CollectScene()
        {
            var pm = new HttpServerRequest();
            if (this.collect)
            {
                var revPack = pm.CollectScene(this.userSceneId);
                return revPack;
            }
            else
            {
                var revPack = pm.CancelCollectScene(this.userSceneId);
                return revPack;
            }
        }
        /// <summary>
        /// 编辑场景
        /// </summary>
        public string EditScene()
        {
            var pm = new HttpServerRequest();
            var revPack = pm.EditScene(this);
            if (revPack.Code == StateCode.SUCCESS)
            {
                var scenes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Scene>>(revPack.Data.ToString());
                var tempScene = scenes.Find((obj) => obj.sid == sid);
                if (tempScene != null)
                {
                    var ssd = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(tempScene));
                    Common.FileUtlis.Files.WriteFileByBytes(savePath, ssd);
                }
            }
            return revPack.Code;
        }
        /// <summary>
        /// 修改场景
        /// </summary>
        public string UpdateScene()
        {
            var pm = new HttpServerRequest();
            var revPack = pm.EditScene(this);
            if (revPack.Code == StateCode.SUCCESS)
            {
                var scenes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Scene>>(revPack.Data.ToString());
                var tempScene = scenes.Find((obj) => obj.sid == sid);
                if (tempScene != null)
                {
                    var ssd = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(tempScene));
                    Common.FileUtlis.Files.WriteFileByBytes(savePath, ssd);
                }
            }
            return revPack.Code;
        }
        /// <summary>
        /// 上传数据到云端
        /// </summary>
        void UploadScene()
        {
            var pm = new HttpServerRequest();
            ResponsePackNew revPack;
            if (string.IsNullOrEmpty(createTime) && string.IsNullOrEmpty(modifyTime))
            {
                revPack = pm.AddScene(this);
                if (revPack.Code == StateCode.SUCCESS)
                {
                    var ssd = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(this));
                    Common.FileUtlis.Files.WriteFileByBytes(savePath, ssd);
                }
            }
            else if (!string.IsNullOrEmpty(createTime) && !string.IsNullOrEmpty(modifyTime))
            {
                revPack = pm.EditScene(this);
                if (revPack.Code == StateCode.SUCCESS)
                {
                    var scenes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Scene>>(revPack.Data.ToString());
                    var tempScene = scenes.Find((obj) => obj.sid == sid);
                    if (tempScene != null)
                    {
                        var ssd = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(tempScene));
                        Common.FileUtlis.Files.WriteFileByBytes(savePath, ssd);
                    }
                }
            }
        }
        /// <summary>
        /// 云端数据创建的时间
        /// </summary>
        public string createTime = "";
        /// <summary>
        /// 云端数据修改的最后时间
        /// </summary>
        public string modifyTime = "";
    }
    /// <summary>
    /// 场景功能对象
    /// </summary>
    public class SceneFunction
    {
        public string sid = "";
        public List<SceneFunctionStatus> status = new List<SceneFunctionStatus>();
        /// <summary>
        /// 功能延时
        /// </summary>
        public string delay = "0";
        Function _localFunction;
        /// <summary>
        /// 本地对应的功能
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Function localFunction
        {
            get
            {
                if (_localFunction == null)
                {
                    _localFunction = ConvertFunctionObject();
                }
                return _localFunction;
            }
        }
        /// <summary>
        /// 转换成功能对象
        /// </summary>
        /// <returns></returns>
        Function ConvertFunctionObject()
        {
            var localFunction = FunctionList.List.GetDeviceFunctionList().Find((obj) => obj.sid == sid);
            return localFunction;
        }
    }
    /// <summary>
    /// 场景功能属性
    /// </summary>
    public class SceneFunctionStatus
    {
        public string key = "";
        public string value = "";
    }
    /// <summary>
    /// 场景推送配置
    /// </summary>
    public class ScenePushConfig
    {
        /// <summary>
        /// 推送方式
        /// </summary>
        public string pushMethod = "";
        /// <summary>
        /// 推送内容
        /// </summary>
        public string pushContent = "";
        /// <summary>
        /// 推送目标集合
        /// </summary>
        public List<string> pushTarget = new List<string>();
    }
}
//5.1.14获取场景列表
//请求参数
//{
//   "namespace": "HDL",
//   "type": "scene",
//   "command": "get_list"
//}
//返回值 json格式 所有场景id及场景里执行的目标数据
//返回例子
//{
//   "namespace": "HDL",
//   "command": "get_list_respond",
//   "type": "scene",
//   "number": [{
//      "scene_id": "0001",
//      "scene_name": "dinner",
//      "objects": [{
//            "sid": "00010019101209000025670100010001",
//"data_type": "string ",
//         "value": "on"
//        }]
//   }]
//}
//说明 获取场景列表和属性,只开,只关,既开又关
//5.1.15创建场景
//请求参数
//{
//   "namespace": "HDL",
//   "command": "create",
//   "type": "scene",
//   "objects": [{
//      "scene_name": "Away ",
//      "status": "single_off"
//   }]
//}
//返回值 json格式
//返回例子   {
//   "namespace": "HDL",
//   "command": "create_respond",
//   "type": "scene",
//   "objects": [{
//      "scene_id": "0004",
//      "name": "Away",
//      "status": "single_off"
//   }]
//}
//说明 创建场景
//5.1.16添加目标到场景
//请求参数
//{
//   "namespace": "HDL",
//   "command": "add_member",
//   "type": "scene",
//   "number": [{
//      "scene_id": "0001",
//      "objects": [{
//         "sid": "00010019101209000025670100010001",
//         "function": [{
//            "attri": "switch",
//"data_type": "string ",
//            "value": "on"
//         }]
//      }]
//   }, {
//      "scene_id": "0002",
//      "objects": [{
//         "sid": "00010019101209000025670200010001",
//         "function": [{
//            "attri": "brightness",
//"data_type": "int",
//            "value": 50
//         }]
//      }]
//   }]
//}
//返回值 json格式
//返回例子   {
//   "namespace": "HDL",
//   "command": "add_member_respond",
//   "type": "scene",
//   "scene_id": "0001",
//   "value": "success"
//}
//说明 成功添加目标的场景列表
//5.1.17删除场景命令
//请求参数
//{
//   "namespace": "HDL",
//   "command": "delete",
//   "type": "scene",
//   "objects": [{
//      "scene_id": "0001"
//   }]
//}
//返回值 json格式
//返回例子   {
//   "namespace": "HDL",
//   "command": "delete_respond",
//   "type": "scene",
//   "scene_id": "0001",
//   "value": "success"
//}
//说明 删除场景
//5.1.18删除场景里的目标
//请求参数
//{
//   "Namespace": "HDL",
//   "Command": "delete_member",
//   "type": "scene",
//   "number": [{
//      "scene_id": "0001",
//      "objects": [{
//         "sid": "00010019101209000025670100010001"
//      }, {
//         "sid": "00010019101209000025670100010002"
//      }]
//   }]
//}
//返回值 json格式
//返回例子   {
//   "namespace": "HDL",
//   "command": "delete_member_respond",
//   "type": "scene",
//   "scenesid": "0001",
//   "sid": "00010019101209000025670100010001",
//   "value": "success"
//}
//说明 删除场景内设备
//5.1.19配置场景分组(足内场景状态自动记录最后一次记录)
//请求参数   {
//   "namespace": "HDL",
//   "command": "group",
//   "type": "scene",
//   "objects": [{
//      "group_id": 1,
//      "scene_ids": [{
//         "scene_id": "0001"
//      }, {
//         "scene_id": "0002"
//      }]
//   }]
//}
//返回值 json格式
//返回例子   {
//   "namespace": "HDL",
//   "command": "group_respond",
//   "type": "scene",
//   "group_id": "0001",
//   "value": "success"
//}
//说明 控制场景
//5.1.20读取场景分组
//请求参数
//{
//   "namespace": "HDL",
//   "command": "read_group",
//   "type": "scene",
//   "objects": [{
//      "group_id": 1
//   }]
//}
//返回值 json格式
//返回例子   {
//   "namespace": "HDL",
//   "command": "read_group_respond",
//   "type": "scene",
//   "objects": [{
//      "group_id": 1,
//      "scene_ids": [{
//         "scene_id": "0001"
//      }, {
//         "scene_id": "0002"
//      }]
//   }]
//}
//说明 控制场景
//5.1.21控制场景
//请求参数
//{
//   "namespace": "HDL",
//   "command": "contrl",
//   "type": "scene",
//   "objects": [{
//      "scene_id": "0001",
//      "value": “on”
//   }]
//}
//返回值 json格式
//返回例子   {
//   "namespace": "HDL",
//   "command": "contrl_respond",
//   "type": "scene",
//      "scene_id": "0001",
//      "value": "success"
//}
//说明 控制场景