using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using WebSite.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using Service;
using Domain;
using Common;
using CommonEntity;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Caching;
using System.Text;
using RestSharp;
using System.Net;
using System.Configuration;

namespace WebSite.Controllers
{
    public class IoTController : BaseController
    {
        private static string _huawei_vtId = System.Configuration.ConfigurationManager.AppSettings["huawei_vtId"];
        private static string _huawei_cuid = System.Configuration.ConfigurationManager.AppSettings["huawei_cuid"];
        private const int AuthorityID = 13;
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(IoTController));
        public IHostManager HostManager { get; set; }
        public ISysHotelManager SysHotelManager { get; set; }
        public IHostModalManager HostModalManager { get; set; }
        public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }
        public ILightControlManager LightControlManager { get; set; }
        public IRoomTypeWXMenusManager RoomTypeWXMenusManager { get; set; }
        public IRoomTypeChannelsManager RoomTypeChannelsManager { get; set; }

        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 如果存在取电服务记录，且不是打开状态，则返回false，不可控制设备（除了空调）,不存在取电服务，可以控制
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        private bool CheckGetPower(Host host)
        {
            bool JieGuo = false;
            bool Result = BBB(host);
            try
            {
                string KKK1 = CacheKey.TakeCardOnLine + "_" + host.HostNumber;
                CommonEntity.DataTongJi.MTakeCardData Chaka = CSRedisCacheHelper.Get_Partition<CommonEntity.DataTongJi.MTakeCardData>(KKK1, 5);

                byte isChaKa = 0x02;
                if (Chaka != null)
                {
                    string KeyFilter1 = "NEWDiff";
                    string KeyFilter2 = "OLDDiff";

                    isChaKa = Chaka.Status;
                    if (Chaka.Status == 0x01 && Result == false)
                    {
                        RCUHost.RCUHostCommon.tools.LanJieData(KeyFilter1, host.SysHotel.Code);
                    }

                    if (Chaka.Status == 0x02 && Result == true)
                    {
                        RCUHost.RCUHostCommon.tools.LanJieData(KeyFilter2, host.SysHotel.Code);
                    }

                }
                bool NewResult = Result || Chaka.Status == 0x01;
                if (NewResult == true)
                {
                    JieGuo = true;
                    return true;
                }
                else
                {
                    JieGuo = false;
                    return false;
                }
            }
            catch (Exception ex)
            {
                JieGuo = false;
                logger.Error("取电数据不同" + ex.Message);
            }
            return JieGuo;
        }
        public static bool BBB(Host host)
        {
            if (!host.SysHotel.IsVoincePowerOn)
            {
                return true;//不需要取电服务打开即可控制
            }
            //if (host.RoomCard != null)
            //{
            //    return true;//已插卡即可控制
            //}

            string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + "004000001";
            var hostModal = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
            if (hostModal == null)
            {
                return false;
            }
            if (hostModal != null && hostModal.Status != 1)
            {
                return false;
            }
            return true;
        }
        public static List<int> ButString = new List<int>() { 1697, 1866, 1601, 2170 };

        public bool AssertFault(int hotelcode)
        {
            if (ButString.Contains(hotelcode))
            {
                return true;
            }
            return false;
        }
        #region 小度对接（同时支持TCL电视新版）


        public string ControlClass_Disconvery = "发现设备";
        public string ControlClass_KongZhiSheBei = "设备控制";
        public string ControlClass_SceneKongZhi = "场景控制";

        [HttpPost()]
        public ActionResult DeleteCUID(string Key)
        {
            HttpContext.Cache.Remove(Key);
            return Json(new { result = "success" }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 小度对接
        /// </summary>
        /// <returns></returns>
        public ActionResult XiaoDu()
        {
            string IP = "";
            string PPP = Request.UserHostAddress;
            string III = Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(III))
            {
                IP = PPP;
            }
            else
            {
                IP = III;
            }


            string g_requestid = "";
            int g_hotelcode = 0;
            string g_hotelid = "";
            string g_roomnum = "";
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            string platformName = "小度音箱";
            try
            {
                Domain.IoTXiaoDuEntity.Request.AppliancesRequest request = JsonConvert.DeserializeObject<Domain.IoTXiaoDuEntity.Request.AppliancesRequest>(reqData);//得到小度请求
                if (string.IsNullOrEmpty(request.payload.cuid))
                {
                    //logger.Error("设备cuid不能为空：" + reqData + "，来自：" + GetClientIP());
                    return Json(ReturnXiaoDuError(request.header, "UnexpectedInformationReceivedError"), JsonRequestBehavior.AllowGet);//该消息表示由于请求消息中属性信息错误，导致技能无法处理请求消息。
                }
                Host host = null;

                string xiaoduCUID = request.payload.cuid;
                string NameSpaceName = request.header.@namespace;
                if (NameSpaceName.StartsWith("X2BOS"))
                {
                    platformName = "TCL电视";
                    //host = HostManager.GetByTCLCUID(request.payload.cuid);
                    host = TCLDataQuery(xiaoduCUID);
                }
                else if (NameSpaceName.StartsWith("DuerOS"))
                {
                    //host = HostManager.GetByXiaoDuCUID(request.payload.cuid);//根据小度音箱序列号获取对应RCU主机  
                    host = XiaoDuQuery(xiaoduCUID);
                }
                else
                {
                    if (string.IsNullOrEmpty(NameSpaceName))
                    {
                        NameSpaceName = "未知平台";
                    }
                    platformName = NameSpaceName;
                }
                //if (request.header.@namespace.StartsWith("X2BOS"))
                //{
                //    platformName = "TCL电视";
                //    host = HostManager.GetByTCLCUID(request.payload.cuid);
                //}
                //else
                //{
                //    host = HostManager.GetByXiaoDuCUID(request.payload.cuid);//根据小度音箱序列号获取对应RCU主机  
                //}

                string messageid = request.header.messageId;
                string messageid1 = request.payload.cuid;

                if (string.IsNullOrEmpty(messageid))
                {
                    messageid = System.Guid.NewGuid().ToString("");
                }

                string logmsgid = messageid;
                if (!string.IsNullOrEmpty(messageid1))
                {
                    logmsgid = messageid + messageid1;
                }

                if (host == null)
                {
                    //logger.Error(platformName + "cuid(" + request.payload.cuid + ")尚未绑定客房主机");
                    return Json(ReturnXiaoDuError(request.header, "TargetHardwareMalfunctionError"), JsonRequestBehavior.AllowGet);//"小度音箱(" + request.payload.cuid + ")尚未绑定客房主机"
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期");
                    return Json(ReturnXiaoDuError(request.header, "ExpiredAccessTokenError"), JsonRequestBehavior.AllowGet);//该消息表示请求消息中access token过期，不能使用。
                }

                string a = host.SysHotel.ID.ToString();
                string hotelname = host.SysHotel.Name;
                string b = host.RoomNumber;
                string c = host.SysHotel.Code;

                int hotel_code = 0;
                int.TryParse(c, out hotel_code);

                g_hotelid = a;
                g_hotelcode = hotel_code;
                g_roomnum = b;
                g_requestid = messageid;

                string Key = CacheKey.IOTKey;
                bool is_monitor = true;
                //永远统计
                //var qqq = CSRedisCacheHelper.ForeverGet<List<IOT_Monitor_Host>>(Key);
                //if (qqq != null && qqq.Count > 0)
                //{
                //    var df = qqq.Where(A => A.HotelID.Equals(a) && A.RoomNumber.Equals(b));
                //    if (df.Count() > 0)
                //    {
                //        is_monitor = true;
                //    }
                //}
                if (is_monitor)
                {
                    IOTMonitorData i = new IOTMonitorData();
                    i.RemoteIP = IP;
                    i.Step = 0;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");

                    i.CreateTime = DateTime.Now;
                    i.TriggerTime = ti;
                    i.HotelId = a;
                    i.HotelCode = hotel_code;
                    i.RoomNumber = b;
                    i.RequestId = logmsgid;
                    i.Platform = platformName;
                    i.CommandDescription = reqData;
                    SendMQTTData.Send(i);
                }

                switch (request.header.@namespace)
                {
                    #region 发现设备
                    case "DuerOS.ConnectedHome.Discovery"://小度平台发现设备
                    case "X2BOS.ConnectedHome.Discovery"://TCL平台发现设备
                        {

                            if (is_monitor)
                            {
                                string sss = "发现设备";
                                IOTMonitorData i = new IOTMonitorData();
                                i.ControlClass = ControlClass_KongZhiSheBei;
                                i.Step = 1;
                                i.CreateTime = DateTime.Now;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.HotelCode = hotel_code;
                                i.RoomNumber = b;
                                i.RequestId = logmsgid;
                                i.Platform = platformName;
                                i.CommandDescription = sss;
                                SendMQTTData.Send(i);
                            }

                            //小度精灵统计
                            string KKK = platformName + "Discovery";
                            RCUHost.RCUHostCommon.tools.LanJieData(KKK, host.SysHotel.Code);

                            Domain.IoTXiaoDuEntity.DiscoverResponse.AppliancesResponse response = null;

                            //string MyCacheKey = platformName + "Discovery_" + b + "_" + c;
                            //string MyCacheKey = platformName + "Discovery_" + a + "_" + b;
                            //var Data = HttpContext.Cache.Get(MyCacheKey);
                            //if (Data != null)
                            //{
                            //    response = Data as Domain.IoTXiaoDuEntity.DiscoverResponse.AppliancesResponse;
                            //}
                            //else
                            {
                                List<Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredAppliances> appliances = new List<Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredAppliances>();
                                //获取需要控制设备的分组信息
                                List<Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredGroups> groups = new List<Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredGroups>();
                                List<string> applianceIds = new List<string>();
                                //获取需要控制的场景
                                IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                                foreach (RoomTypeScene scene in sceneModals)
                                {
                                    string aliasName = string.IsNullOrEmpty(scene.AliasName) ? scene.Name : scene.AliasName;//获取别名
                                    appliances.Add(new Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredAppliances
                                    {
                                        actions = new List<string> { "turnOn" },
                                        applianceTypes = new List<string> { "SCENE_TRIGGER" },
                                        additionalApplianceDetails = new Dictionary<string, string>() { { "TYPE", "SCENE_TRIGGER" } },
                                        applianceId = scene.ID.ToString(),
                                        friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + scene.Name,
                                        friendlyName = scene.Name,
                                        nicknames = new List<string>(aliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)), //new List<string> { scene.Name },
                                        manufacturerName = "宝来威(Boonlive)",
                                        modelName = Common.Tools.GetDescription(scene.Type),
                                        version = "V1",
                                        reachable = true
                                    });
                                    applianceIds.Add(scene.ID.ToString());
                                }
                                //场景分组
                                groups.Add(new Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredGroups
                                {
                                    groupName = "",
                                    applianceIds = applianceIds,
                                    groupNotes = "Boonlive-" + host.SysHotel.Name + "(" + host.RoomNumber + ")" + "场景分组",
                                    additionalGroupDetails = new Dictionary<string, string>()
                                });
                                applianceIds = new List<string>();
                                //获取需要控制的设备信息
                                IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();

                                #region TCL设备 其实组设备也可以使用
                                //获取 组设备
                                List<HostModal> TTT = new List<HostModal>();
                                var Q = hostModals.Where(A => A.Modal.MultipleGroupID != 0);
                                if (Q.Count() > 0)
                                {
                                    var P = Q.GroupBy(A => A.Modal.MultipleGroupID);

                                    foreach (var item in P)
                                    {
                                        //获取每一组的数据
                                        int ID = item.Key;
                                        var ll = item.Select(A => A.Modal.ModalAddress).ToArray();
                                        //这个是组名字，每一个数据的组名字都一样的
                                        string NNN = item.FirstOrDefault().Modal.MultipleTCLName;
                                        //每一组的数据
                                        HostModal hh = new HostModal();
                                        hh.Modal = new RoomTypeModal();
                                        hh.Modal.Name = NNN;
                                        hh.Modal.Type = item.FirstOrDefault().Modal.Type;
                                        hh.Modal.ModalAddress = string.Join("_", ll);
                                        TTT.Add(hh);
                                    }
                                }
                                var QQ = hostModals.Where(A => A.Modal.MultipleGroupID == 0).ToList();
                                #endregion

                                //组数据和非组数据 合在一块
                                QQ.AddRange(TTT);
                                hostModals = QQ;
                                foreach (HostModal hostModal in QQ)
                                {
                                    List<string> applianceTypes = new List<string>();
                                    List<string> actions = new List<string>();
                                    switch (hostModal.Modal.Type)
                                    {
                                        case DeviceType.Dimmer://LED调光
                                        case DeviceType.Traic://可控硅调光
                                        case DeviceType.PWMDimmer://PWM调光
                                        case DeviceType.PWMExpand://PWM扩展
                                        case DeviceType.PBLED:
                                        case DeviceType.LVout://弱电输出
                                        case DeviceType.Strip://灯带调光
                                        case DeviceType.PB20:
                                        case DeviceType.PB20_LD:
                                        case DeviceType.PB20_LS:
                                            applianceTypes.Add("LIGHT");
                                            actions.Add("turnOn");
                                            actions.Add("turnOff");
                                            actions.Add("setBrightnessPercentage");
                                            actions.Add("incrementBrightnessPercentage");
                                            actions.Add("decrementBrightnessPercentage");
                                            //阿宝添加的RGB
                                            // 这和文档上不一样，是那边的工作人员给我说的
                                            //actions.Add("setLightingRgbColour");
                                            actions.Add("setLightingRgb");
                                            break;
                                        case DeviceType.ColorTemp://色温
                                            applianceTypes.Add("LIGHT");
                                            actions.Add("turnOn");
                                            actions.Add("turnOff");
                                            actions.Add("setBrightnessPercentage");
                                            actions.Add("incrementBrightnessPercentage");
                                            actions.Add("decrementBrightnessPercentage");
                                            actions.Add("setColorTemperature");
                                            actions.Add("incrementColorTemperature");
                                            actions.Add("decrementColorTemperature");
                                            break;
                                        case DeviceType.AirConditioner:
                                            applianceTypes.Add("AIR_CONDITION");
                                            actions.Add("turnOn");
                                            actions.Add("turnOff");
                                            actions.Add("setTemperature");
                                            actions.Add("incrementTemperature");
                                            actions.Add("decrementTemperature");
                                            actions.Add("setFanSpeed");
                                            actions.Add("incrementFanSpeed");
                                            actions.Add("decrementFanSpeed");
                                            actions.Add("setMode");
                                            //actions.Add("getTemperatureReading");
                                            //actions.Add("getTargetTemperature");
                                            break;
                                        case DeviceType.Curtain:
                                            if (hostModal.Modal.Name.IndexOf("窗帘") > -1)
                                            {
                                                applianceTypes.Add("CURTAIN");//窗帘
                                            }
                                            else if (hostModal.Modal.Name.IndexOf("窗纱") > -1)
                                            {
                                                applianceTypes.Add("CURT_SIMP");//窗纱
                                            }
                                            else
                                            {
                                                applianceTypes.Add("SWITCH");//卷帘、天幕等
                                            }
                                            actions.Add("turnOn");
                                            actions.Add("turnOff");
                                            actions.Add("pause");
                                            actions.Add("continue");
                                            break;
                                        case DeviceType.TV:
                                            applianceTypes.Add("TV_SET");
                                            actions.Add("turnOn");
                                            actions.Add("turnOff");
                                            actions.Add("setTVChannel");
                                            actions.Add("decrementTVChannel");
                                            actions.Add("incrementTVChannel");
                                            actions.Add("returnTVChannel");
                                            actions.Add("setVolume");
                                            actions.Add("setVolumeMute");
                                            actions.Add("incrementVolume");
                                            actions.Add("decrementVolume");
                                            actions.Add("setDirection");
                                            break;
                                        case DeviceType.Music:
                                            applianceTypes.Add("TV_SET");
                                            actions.Add("turnOn");
                                            actions.Add("turnOff");
                                            actions.Add("setVolume");
                                            actions.Add("incrementVolume");
                                            actions.Add("decrementVolume");
                                            actions.Add("setVolumeMute");
                                            break;
                                        default:
                                            if (hostModal.Modal.ModalAddress.Equals("004000010"))
                                            {
                                                applianceTypes.Add("DOOR_LOCK");
                                            }
                                            else
                                            {
                                                if ((hostModal.Modal.Name != null && hostModal.Modal.Name.IndexOf("灯") > -1) ||
                                                    (hostModal.Modal.EnglishName != null && hostModal.Modal.EnglishName.ToLower().IndexOf("light") > -1) ||
                                                    (hostModal.Modal.TWName != null && hostModal.Modal.TWName.IndexOf("燈") > -1))
                                                {
                                                    applianceTypes.Add("LIGHT");
                                                }
                                                else
                                                {
                                                    applianceTypes.Add("SWITCH");
                                                }
                                            }
                                            actions.Add("turnOn");
                                            actions.Add("turnOff");
                                            break;
                                    }
                                    string aliasName = string.IsNullOrEmpty(hostModal.Modal.AliasName) ? hostModal.Modal.Name : hostModal.Modal.AliasName;//获取别名
                                    appliances.Add(new Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredAppliances
                                    {
                                        actions = actions,
                                        applianceTypes = applianceTypes,
                                        additionalApplianceDetails = new Dictionary<string, string>() { { "TYPE", applianceTypes[0] } },
                                        applianceId = hostModal.Modal.ModalAddress,
                                        friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + hostModal.Modal.Name,
                                        friendlyName = hostModal.Modal.Name,
                                        nicknames = new List<string>(aliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)),
                                        manufacturerName = "宝来威(Boonlive)",
                                        modelName = Common.Tools.GetDescription(hostModal.Modal.Type),
                                        version = "V1",
                                        reachable = true
                                    });
                                    applianceIds.Add(hostModal.Modal.ModalAddress);// + "#" + applianceTypes[0]);
                                }
                                //添加所有灯虚拟回路
                                appliances.Add(new Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredAppliances
                                {
                                    actions = new List<string>() { "turnOn", "turnOff", "setBrightnessPercentage", "incrementBrightnessPercentage", "decrementBrightnessPercentage" },
                                    applianceTypes = new List<string>() { "LIGHT" },
                                    additionalApplianceDetails = new Dictionary<string, string>() { { "TYPE", "LIGHT" } },
                                    applianceId = "000000001",
                                    friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->所有灯",
                                    friendlyName = "所有灯",
                                    //nicknames = new List<string> { "所有灯", "打开灯", "关闭灯", "开灯", "关灯", "灯" },
                                    manufacturerName = "宝来威(Boonlive)",
                                    modelName = "所有灯",
                                    version = "V1",
                                    reachable = true
                                });
                                applianceIds.Add("000000001");//#LIGHT");
                                //房间分组
                                groups.Add(new Domain.IoTXiaoDuEntity.DiscoverResponse.DiscoveredGroups
                                {
                                    groupName = "",//分组为空
                                    applianceIds = applianceIds,
                                    groupNotes = "Boonlive-" + host.SysHotel.Name + "(" + host.RoomNumber + ")" + "房间分组",
                                    additionalGroupDetails = new Dictionary<string, string>() { }
                                });
                                //找到可控场景和设备，响应小度DuerOS
                                response = new Domain.IoTXiaoDuEntity.DiscoverResponse.AppliancesResponse
                                {
                                    header = new Domain.IoTXiaoDuEntity.Header
                                    {
                                        messageId = request.header.messageId,
                                        @namespace = request.header.@namespace,
                                        name = "DiscoverAppliancesResponse",
                                        payloadVersion = request.header.payloadVersion
                                    },
                                    payload = new Domain.IoTXiaoDuEntity.DiscoverResponse.Payload
                                    {
                                        discoveredAppliances = appliances,
                                        discoveredGroups = groups
                                    }
                                };
                                //HttpContext.Cache.Insert(MyCacheKey, response, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration);
                            }

                            if (is_monitor)
                            {
                                IOTMonitorData i = new IOTMonitorData();
                                i.Step = 4;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.CreateTime = DateTime.Now;
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.HotelCode = hotel_code;
                                i.RoomNumber = b;
                                i.RequestId = logmsgid;
                                i.Platform = platformName;
                                i.CommandDescription = "DiscoveryResponse";
                                SendMQTTData.Send(i);
                            }
                            //logger.Error(string.Format("{3}(酒店：{0}，房号：{1})本次获取设备数量：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, response.payload.discoveredAppliances.Count.ToString(), platformName));
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    #endregion
                    case "DuerOS.ConnectedHome.Control"://小度控制消息
                    case "X2BOS.ConnectedHome.Control"://TCL平台控制设备
                        {
                            //小度精灵统计
                            string KKK = platformName + "Control";
                            RCUHost.RCUHostCommon.tools.LanJieData(KKK, host.SysHotel.Code);
                            bool is_online = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);

                            if (is_monitor)
                            {
                                string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号:(" + host.RoomNumber + ") is_online: " + is_online.ToString();
                                IOTMonitorData i = new IOTMonitorData();
                                i.ControlClass = ControlClass_KongZhiSheBei;
                                i.Step = 1;
                                i.CreateTime = DateTime.Now;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.HotelCode = hotel_code;
                                i.RoomNumber = b;
                                i.RequestId = logmsgid; i.Platform = platformName;
                                i.CommandDescription = sss;
                                SendMQTTData.Send(i);
                            }
                            if (!is_online)
                            {
                                logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");
                                return Json(ReturnXiaoDuError(request.header, "TargetOfflineError"), JsonRequestBehavior.AllowGet);//当技能检测到目标设备没有连接到设备云或者设备云不在线时，会给DuerOS发送TargetOfflineError消息。
                            }


                            bool is_take_card = CheckGetPower(host);

                            if (is_monitor)
                            {
                                string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号：(" + host.RoomNumber + ") 取电: " + is_take_card.ToString();
                                IOTMonitorData i = new IOTMonitorData();
                                i.Step = 2;
                                i.CreateTime = DateTime.Now;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.HotelCode = hotel_code;
                                i.RoomNumber = b;
                                i.RequestId = logmsgid; i.Platform = platformName;
                                i.CommandDescription = sss;
                                SendMQTTData.Send(i);
                            }
                            if (!is_take_card)
                            {
                                logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");
                                return Json(ReturnXiaoDuError(request.header, "UnsupportedOperationError"), JsonRequestBehavior.AllowGet);
                            }

                            //正常情况下
                            //"appliance":{"additionalApplianceDetails":{"TYPE":"LIGHT"}
                            string applianceType = "SCENE_TRIGGER";//设备类型
                            if (request.payload.appliance.additionalApplianceDetails.ContainsKey("TYPE"))
                            {
                                applianceType = request.payload.appliance.additionalApplianceDetails["TYPE"];
                            }
                            string modalAddress = request.payload.appliance.applianceId;//设备地址或场景ID
                            if (modalAddress.IndexOf("&") > -1)
                            {
                                modalAddress = modalAddress.Split('&')[0];
                            }
                            string confirmationName = "TurnOnConfirmation";
                            Domain.IoTXiaoDuEntity.ControlResponse.Payload payload = new Domain.IoTXiaoDuEntity.ControlResponse.Payload();
                            List<Domain.IoTXiaoDuEntity.ControlResponse.Attributes> attributes = new List<Domain.IoTXiaoDuEntity.ControlResponse.Attributes>();

                            if (modalAddress.StartsWith("00000000"))//所有灯控制
                            {
                                #region 所有灯控制
                                var devices = new List<RCUHost.Protocols.Device>();
                                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                sb.Append("控制客房(" + host.RoomNumber + ")所有灯：");
                                var hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.Name.Contains("灯") && r.Modal.WXActiveIndicator).ToList();

                                List<IotDeviceData> devicelist = new List<IotDeviceData>();
                                foreach (HostModal hostModal in hostModals)
                                {
                                    switch (hostModal.Modal.Type)
                                    {
                                        case DeviceType.Relay:
                                        case DeviceType.Expand:
                                        case DeviceType.Dimmer:
                                        case DeviceType.Traic:
                                        case DeviceType.Strip:
                                        case DeviceType.PWMDimmer:
                                        case DeviceType.PWMExpand:
                                        case DeviceType.PBLED:
                                        case DeviceType.A9IORelay:
                                        case DeviceType.PB20:
                                        case DeviceType.PB20_LD:
                                        case DeviceType.PB20_LS:
                                        case DeviceType.ColorTemp:
                                            Domain.IoTXiaoDuEntity.ControlResponse.PreviousState previousState = new Domain.IoTXiaoDuEntity.ControlResponse.PreviousState();
                                            previousState.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(hostModal.Brightness) };//原来的亮度
                                            int status = hostModal.Status;
                                            int brightness = hostModal.Brightness;
                                            var device = new RCUHost.Protocols.Device();
                                            device.Address = hostModal.Modal.ModalAddress;
                                            device.AddressType = RCUHost.Protocols.AddressType.DeviceAddress;
                                            device.Type = hostModal.Modal.Type;

                                            string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID.ToString() + "_" + device.Address;
                                            var hostModal_T = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                                            switch (request.header.name)
                                            {
                                                case "TurnOnRequest"://打开
                                                    confirmationName = "TurnOnConfirmation";
                                                    status = 1;
                                                    brightness = 100;
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    break;
                                                case "TurnOffRequest"://关闭
                                                    confirmationName = "TurnOffConfirmation";
                                                    status = 2;
                                                    brightness = 0;
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    break;
                                                case "SetBrightnessPercentageRequest"://设置亮度
                                                    if (hotel_code == 1085 || hotel_code == 1001 || hotel_code == 1003 || hotel_code > 2000)
                                                    {
                                                        //logger.Error("查询的Key值:"+KKey);
                                                        if (hostModal_T != null && hostModal_T.Status == 2) { continue; }
                                                    }
                                                    confirmationName = "SetBrightnessPercentageConfirmation";
                                                    status = 1;
                                                    brightness = Convert.ToInt16(request.payload.brightness.value);
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    break;
                                                case "IncrementBrightnessPercentageRequest"://调亮
                                                    if (hotel_code == 1085 || hotel_code == 1001 || hotel_code == 1003 || hotel_code > 2000)
                                                    {
                                                        if (hostModal_T != null && hostModal_T.Status == 2) { continue; }
                                                    }
                                                    confirmationName = "IncrementBrightnessPercentageConfirmation";
                                                    status = 1;
                                                    brightness += Convert.ToInt16(request.payload.deltaPercentage.value);
                                                    if (brightness > 100)
                                                    {
                                                        brightness = 100;
                                                    }
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    break;
                                                case "DecrementBrightnessPercentageRequest"://调暗
                                                    if (hotel_code == 1085 || hotel_code == 1001 || hotel_code == 1003 || hotel_code > 2000)
                                                    {
                                                        if (hostModal_T != null && hostModal_T.Status == 2) { continue; }
                                                    }
                                                    confirmationName = "DecrementBrightnessPercentageConfirmation";
                                                    status = 1;
                                                    brightness -= Convert.ToInt16(request.payload.deltaPercentage.value);
                                                    if (brightness < 0)
                                                    {
                                                        brightness = 0;
                                                        status = 2;
                                                    }
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    break;
                                            }
                                            attributes.Add(new Domain.IoTXiaoDuEntity.ControlResponse.Attributes() { name = "name", value = "所有灯", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                            attributes.Add(new Domain.IoTXiaoDuEntity.ControlResponse.Attributes() { name = "turnOnState", value = status == 1 ? "ON" : "OFF", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                            device.Status = (byte)status;
                                            device.Brightness = (byte)brightness;
                                            devices.Add(device);
                                            sb.Append(hostModal.Modal.Name + "，");
                                            break;
                                    }
                                    IotDeviceData iii = new IotDeviceData();
                                    iii.DeviceAddress = hostModal.Modal.ModalAddress;
                                    iii.DeviceName = hostModal.Modal.Name;
                                    devicelist.Add(iii);
                                }
                                string JKKey = System.Guid.NewGuid().ToString("N");
                                //if (hotel_code == 1697||hotel_code==1866||hotel_code==1601)
                                if (AssertFault(hotel_code))
                                {
                                    for (int i = 0; i < 3; i++)
                                    {
                                        Thread.Sleep(200);
                                        LightControlManager.AllDeviceControl_Repeat(JKKey, host, devices);
                                    }
                                }
                                else
                                {
                                    LightControlManager.AllDeviceControl(host, devices);
                                }
                                sb.Append("动作：" + request.header.name);
                                switch (request.header.name)
                                {
                                    case "SetBrightnessPercentageRequest":
                                        sb.Append("，设定值：" + request.payload.brightness.value);
                                        break;
                                    case "IncrementBrightnessPercentageRequest":
                                        sb.Append("，增加值：" + request.payload.deltaPercentage.value);
                                        break;
                                    case "DecrementBrightnessPercentageRequest":
                                        sb.Append("，减少值：" + request.payload.deltaPercentage.value);
                                        break;
                                }

                                if (is_monitor)
                                {
                                    IOTMonitorData i = new IOTMonitorData();
                                    i.ControlClass = ControlClass_KongZhiSheBei;
                                    i.WhichOneDevice = devicelist;
                                    i.Step = 3;
                                    i.CreateTime = DateTime.Now;
                                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                    i.TriggerTime = ti;
                                    i.HotelId = a;
                                    i.HotelCode = hotel_code;
                                    i.RoomNumber = b;
                                    i.RequestId = logmsgid;
                                    i.Platform = platformName;
                                    i.CommandDescription = sb.ToString();
                                    SendMQTTData.Send(i);
                                }
                                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                                #endregion
                            }
                            else
                            {
                                switch (applianceType)
                                {
                                    #region 场景控制
                                    case "SCENE_TRIGGER"://场景控制
                                    case "ACTIVITY_TRIGGER":
                                        {
                                            var scene = RoomTypeSceneManager.Get(int.Parse(modalAddress));
                                            if (scene == null)
                                            {
                                                if (is_monitor)
                                                {
                                                    IOTMonitorData i = new IOTMonitorData();
                                                    i.Step = 3.01;
                                                    i.CreateTime = DateTime.Now;
                                                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                    i.TriggerTime = ti;
                                                    i.HotelId = a;
                                                    i.HotelCode = hotel_code;
                                                    i.RoomNumber = b;
                                                    i.RequestId = logmsgid;
                                                    i.Platform = platformName;
                                                    string sss = string.Format("找不到此情景");
                                                    i.CommandDescription = sss.ToString();
                                                    SendMQTTData.Send(i);
                                                }
                                                logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的场景，ID：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress, platformName));
                                                return Json(ReturnXiaoDuError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                            }

                                            if (is_monitor)
                                            {
                                                IOTMonitorData i = new IOTMonitorData();
                                                i.ControlClass = ControlClass_SceneKongZhi;
                                                i.SceneName = scene.Name;
                                                i.Step = 3;
                                                i.CreateTime = DateTime.Now;
                                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                i.TriggerTime = ti;
                                                i.HotelId = a;
                                                i.HotelCode = hotel_code;
                                                i.RoomNumber = b;
                                                i.RequestId = logmsgid;
                                                i.Platform = platformName;
                                                i.CommandDescription = "场景控制";
                                                SendMQTTData.Send(i);
                                            }
                                            attributes.Add(new Domain.IoTXiaoDuEntity.ControlResponse.Attributes() { name = "name", value = scene.Name, scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                            attributes.Add(new Domain.IoTXiaoDuEntity.ControlResponse.Attributes() { name = "turnOnState", value = "ON", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });

                                            string KeyRepeat = System.Guid.NewGuid().ToString("N");
                                            //if (hotel_code == 1697||hotel_code==1866||hotel_code==1601)
                                            if (AssertFault(hotel_code))
                                            {

                                                for (int i = 0; i < 3; i++)
                                                {
                                                    Thread.Sleep(200);
                                                    // LightControlManager.ApplyScene(host, scene);
                                                    LightControlManager.ApplyScene_Repeat(KeyRepeat, host, scene);
                                                }
                                            }
                                            else
                                            {
                                                LightControlManager.ApplyScene(host, scene);
                                            }

                                            if (is_monitor)
                                            {
                                                IOTMonitorData i = new IOTMonitorData();
                                                i.Step = 3.1;
                                                i.CreateTime = DateTime.Now;
                                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                i.TriggerTime = ti;
                                                i.HotelId = a;
                                                i.HotelCode = hotel_code;
                                                i.RoomNumber = b;
                                                i.RequestId = logmsgid;
                                                i.Platform = platformName;
                                                string sss = string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID);
                                                i.CommandDescription = sss.ToString();
                                                SendMQTTData.Send(i);
                                            }
                                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, platformName, host.SysHotel.ID);
                                        }
                                        break;
                                    #endregion

                                    #region 单控制
                                    default:
                                        {
                                            //var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);//设备控制


                                            var rgb_rgb = request.payload.lightingRgb;
                                            HostModal hostModal = null;
                                            List<HostModal> hostmodal_L = new List<HostModal>();
                                            if (modalAddress.Contains("_"))
                                            {
                                                string[] mmm = modalAddress.Split('_');
                                                foreach (var item in mmm)
                                                {
                                                    hostModal = GetDataFromCache(host, item);
                                                    if (hostModal != null)
                                                    {
                                                        hostmodal_L.Add(hostModal);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                hostModal = GetDataFromCache(host, modalAddress);
                                            }

                                            if (hostmodal_L.Count == 0 && hostModal == null)
                                            {
                                                logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的回路，Address：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress, platformName));
                                                return Json(ReturnXiaoDuError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                            }
                                            int status = 0;
                                            int brightness = 100;
                                            int temperature = 25;
                                            int fanSpeed = 1;
                                            int mode = 1;
                                            int valve = 1;
                                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                            Domain.IoTXiaoDuEntity.ControlResponse.PreviousState previousState = new Domain.IoTXiaoDuEntity.ControlResponse.PreviousState();
                                            if (hostmodal_L.Count == 0)
                                            {
                                                status = hostModal.Status;
                                                brightness = hostModal.Brightness;
                                                temperature = hostModal.SettingTemp;
                                                fanSpeed = hostModal.FanSpeed;
                                                mode = hostModal.Mode;
                                                valve = hostModal.Valve;
                                                sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：");
                                                previousState.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(hostModal.Brightness) };//原来的亮度
                                            }
                                            else
                                            {
                                                previousState.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = 0 };//原来的亮度
                                            }

                                            #region 判断控制方式
                                            switch (request.header.name)
                                            {

                                                //灯光亮度百分比控制
                                                case "SetCurtainPercentageRequest":
                                                    break;
                                                //RGB灯光颜色控制
                                                case "SetLightingRgbRequest":
                                                    var rgb = request.payload.lightingRgb;
                                                    confirmationName = "SetLightingRgbConfirmation";
                                                    status = 1;
                                                    brightness = 100;
                                                    //每个设备的控制值要变一下
                                                    foreach (var item in hostmodal_L)
                                                    {
                                                        int rrr = 0;
                                                        if (item.Modal.TCLDeviceName.Equals("红"))
                                                        {
                                                            //传过来的是0-255
                                                            //这边用的是0-100
                                                            int.TryParse(rgb.value.r, out rrr);
                                                        }
                                                        else if (item.Modal.TCLDeviceName.Equals("绿"))
                                                        {

                                                            int.TryParse(rgb.value.g, out rrr);
                                                        }
                                                        else if (item.Modal.TCLDeviceName.Equals("蓝"))
                                                        {

                                                            int.TryParse(rgb.value.b, out rrr);
                                                        }
                                                        double everydata = rrr / 2.55;
                                                        int roundedNumber = (int)Math.Round(everydata);
                                                        item.Status = status;
                                                        item.Brightness = roundedNumber;
                                                    }
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    sb.Append("状态：RGB调光");
                                                    break;

                                                case "TurnOnRequest"://打开
                                                    confirmationName = "TurnOnConfirmation";
                                                    status = 1;
                                                    brightness = 100;

                                                    foreach (var item in hostmodal_L)
                                                    {
                                                        item.Status = status;
                                                        item.Brightness = brightness;
                                                    }

                                                    if (hostModal.Modal.Type == DeviceType.TV)//电视开关时，内容传0
                                                    {
                                                        mode = 0;
                                                    }
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    sb.Append("状态：打开");
                                                    break;
                                                case "TurnOffRequest"://关闭                   
                                                    confirmationName = "TurnOffConfirmation";
                                                    status = 2;
                                                    brightness = 0;

                                                    foreach (var item in hostmodal_L)
                                                    {
                                                        item.Status = status;
                                                        item.Brightness = brightness;
                                                    }

                                                    if (hostModal.Modal.Type == DeviceType.TV)//电视开关时，内容传0
                                                    {
                                                        mode = 0;
                                                    }
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    sb.Append("状态：关闭");
                                                    break;
                                                case "SetBrightnessPercentageRequest"://设置亮度
                                                    confirmationName = "SetBrightnessPercentageConfirmation";
                                                    status = 1;
                                                    brightness = Convert.ToInt16(request.payload.brightness.value);
                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    sb.Append("设亮度：" + brightness);

                                                    #region RGB组设备的控制
                                                    if (rgb_rgb != null)
                                                    {
                                                        //这个是 组设备的 亮度设置
                                                        if (hostmodal_L.Count > 0)
                                                        {
                                                            foreach (var item in hostmodal_L)
                                                            {
                                                                double yuanlai = 0;
                                                                string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + item.Modal.ModalAddress;
                                                                var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                                                                if (obj != null)
                                                                {
                                                                    HostModal_Cache hhh = obj as HostModal_Cache;

                                                                    yuanlai = hhh.Brightness;
                                                                }

                                                                double data = yuanlai * (brightness / 100);
                                                                int rrr = 0;
                                                                if (item.Modal.TCLDeviceName.Equals("红"))
                                                                {
                                                                    //传过来的是0-255
                                                                    //这边用的是0-100
                                                                    int.TryParse(rgb_rgb.value.r, out rrr);
                                                                }
                                                                else if (item.Modal.TCLDeviceName.Equals("绿"))
                                                                {

                                                                    int.TryParse(rgb_rgb.value.g, out rrr);
                                                                }
                                                                else if (item.Modal.TCLDeviceName.Equals("蓝"))
                                                                {

                                                                    int.TryParse(rgb_rgb.value.b, out rrr);
                                                                }
                                                                int roundedNumber = (int)Math.Round(data);
                                                                item.Status = status;
                                                                item.Brightness = roundedNumber;
                                                            }
                                                        }
                                                    }
                                                    #endregion

                                                    break;
                                                case "IncrementBrightnessPercentageRequest"://调亮
                                                    confirmationName = "IncrementBrightnessPercentageConfirmation";
                                                    status = 1;
                                                    brightness += Convert.ToInt16(request.payload.deltaPercentage.value);
                                                    if (brightness > 100)
                                                    {
                                                        brightness = 100;
                                                    }

                                                    #region RGB组设备的控制
                                                    if (rgb_rgb != null)
                                                    {
                                                        if (hostmodal_L.Count > 0)
                                                        {
                                                            foreach (var item in hostmodal_L)
                                                            {
                                                                double yuanlai = 0;
                                                                string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + item.Modal.ModalAddress;
                                                                var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                                                                if (obj != null)
                                                                {
                                                                    HostModal_Cache hhh = obj as HostModal_Cache;

                                                                    yuanlai = hhh.Brightness;
                                                                }

                                                                double data = yuanlai * (1 + (brightness / 100));
                                                                int rrr = 0;
                                                                if (item.Modal.TCLDeviceName.Equals("红"))
                                                                {
                                                                    //传过来的是0-255
                                                                    //这边用的是0-100
                                                                    int.TryParse(rgb_rgb.value.r, out rrr);
                                                                }
                                                                else if (item.Modal.TCLDeviceName.Equals("绿"))
                                                                {
                                                                    int.TryParse(rgb_rgb.value.g, out rrr);
                                                                }
                                                                else if (item.Modal.TCLDeviceName.Equals("蓝"))
                                                                {
                                                                    int.TryParse(rgb_rgb.value.b, out rrr);
                                                                }
                                                                int roundedNumber = (int)Math.Round(data);
                                                                item.Status = status;
                                                                item.Brightness = rrr;
                                                            }
                                                        }
                                                    }
                                                    #endregion


                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    sb.Append("调亮：" + request.payload.deltaPercentage.value + "，结果：" + brightness);
                                                    break;
                                                case "DecrementBrightnessPercentageRequest"://调暗
                                                    confirmationName = "DecrementBrightnessPercentageConfirmation";
                                                    status = 1;
                                                    brightness -= Convert.ToInt16(request.payload.deltaPercentage.value);
                                                    if (brightness < 0)
                                                    {
                                                        brightness = 0;
                                                        status = 2;
                                                    }

                                                    #region RGB组设备的控制
                                                    if (rgb_rgb != null)
                                                    {
                                                        if (hostmodal_L.Count > 0)
                                                        {
                                                            foreach (var item in hostmodal_L)
                                                            {
                                                                double yuanlai = 0;
                                                                string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + item.Modal.ModalAddress;
                                                                var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                                                                if (obj != null)
                                                                {
                                                                    HostModal_Cache hhh = obj as HostModal_Cache;

                                                                    yuanlai = hhh.Brightness;
                                                                }

                                                                double data = yuanlai * (1 - (brightness / 100));
                                                                int rrr = 0;
                                                                if (item.Modal.AliasName.Equals("红") || item.Modal.Name.Contains("红"))
                                                                {
                                                                    //传过来的是0-255
                                                                    //这边用的是0-100
                                                                    int.TryParse(rgb_rgb.value.r, out rrr);
                                                                }
                                                                else if (item.Modal.Name.Contains("绿") || item.Modal.AliasName.Equals("绿"))
                                                                {

                                                                    int.TryParse(rgb_rgb.value.g, out rrr);
                                                                }
                                                                else if (item.Modal.Name.Contains("蓝") || item.Modal.AliasName.Equals("蓝"))
                                                                {

                                                                    int.TryParse(rgb_rgb.value.b, out rrr);
                                                                }
                                                                int roundedNumber = (int)Math.Round(data);
                                                                item.Status = status;
                                                                item.Brightness = rrr;
                                                            }
                                                        }
                                                    }
                                                    #endregion

                                                    payload.brightness = new Domain.IoTXiaoDuEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                    payload.previousState = previousState;
                                                    sb.Append("调暗：" + request.payload.deltaPercentage.value + "，结果：" + brightness);
                                                    break;
                                                case "SetColorTemperatureRequest"://设置色温
                                                    previousState.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    confirmationName = "SetColorTemperatureConfirmation";
                                                    status = 3;

                                                    if (request.header.@namespace.Equals("X2BOS.ConnectedHome.Control"))
                                                    {
                                                        temperature = XiaoDuToBLW(request.payload.colorTemperature.value);
                                                    }
                                                    else
                                                    {
                                                        temperature = XiaoDuToBLW(request.payload.targetTemperature.value);
                                                    }
                                                    if (temperature < 0)
                                                    {
                                                        temperature = 0;
                                                    }
                                                    else if (temperature > 100)
                                                    {
                                                        temperature = 100;
                                                    }
                                                    //阿宝修改的，TCL 非要把值设置成2700K-6500K之间
                                                    if (request.header.@namespace.Equals("X2BOS.ConnectedHome.Control"))
                                                    {
                                                        int TTT = XiaoDuToBLW(request.payload.colorTemperature.value);
                                                        int HHH = TTT - 2700;
                                                        //38是这样来的 （6500-2700）/100
                                                        double UUU = HHH / 38;
                                                        int roundedNumber = (int)Math.Round(UUU);
                                                        if (roundedNumber < 0)
                                                        {
                                                            roundedNumber = 0;
                                                        }
                                                        temperature = roundedNumber;
                                                    }
                                                    payload.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    payload.previousState = previousState;
                                                    sb.Append("设色温：" + temperature);
                                                    break;
                                                case "IncrementColorTemperatureRequest"://调高灯光色温
                                                    previousState.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    confirmationName = "IncrementColorTemperatureConfirmation";
                                                    status = 3;

                                                    if (request.header.@namespace.Equals("X2BOS.ConnectedHome.Control"))
                                                    {
                                                        int TTT = XiaoDuToBLW(request.payload.deltaValue.value);
                                                        double UUU = TTT / 38;
                                                        int roundedNumber = (int)Math.Round(UUU);
                                                        if (roundedNumber < 0)
                                                        {
                                                            roundedNumber = 0;
                                                        }
                                                        temperature -= roundedNumber;
                                                    }
                                                    else
                                                    {
                                                        temperature += Convert.ToInt16(request.payload.deltaValue.value.ToString());
                                                        if (temperature > 100)
                                                        {
                                                            temperature = 100;
                                                        }
                                                    }
                                                    payload.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    payload.previousState = previousState;
                                                    sb.Append("调高灯光色温：" + request.payload.deltaValue.value + "，结果：" + temperature);
                                                    break;
                                                case "DecrementColorTemperatureRequest"://降低灯光色温
                                                    previousState.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    confirmationName = "DecrementColorTemperatureConfirmation";
                                                    status = 3;


                                                    if (request.header.@namespace.Equals("X2BOS.ConnectedHome.Control"))
                                                    {
                                                        int TTT = XiaoDuToBLW(request.payload.deltaValue.value);
                                                        double UUU = TTT / 38;
                                                        int roundedNumber = (int)Math.Round(UUU);

                                                        if (roundedNumber < 0)
                                                        {
                                                            roundedNumber = 0;
                                                        }
                                                        temperature += roundedNumber;
                                                    }
                                                    else
                                                    {
                                                        temperature -= Convert.ToInt16(request.payload.deltaValue.value);
                                                        if (temperature < 0)
                                                        {
                                                            temperature = 0;
                                                        }
                                                    }
                                                    payload.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    payload.previousState = previousState;
                                                    sb.Append("调低灯光色温：" + request.payload.deltaValue.value + "，结果：" + temperature);
                                                    break;
                                                case "SetTemperatureRequest"://设置温度
                                                    previousState.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    confirmationName = "SetTemperatureConfirmation";
                                                    status = 1;
                                                    temperature = XiaoDuToBLW(request.payload.targetTemperature.value);
                                                    if (temperature < 16)
                                                    {
                                                        temperature = 16;
                                                    }
                                                    else if (temperature > 32)
                                                    {
                                                        temperature = 32;
                                                    }
                                                    payload.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    payload.previousState = previousState;
                                                    sb.Append("设温：" + temperature);
                                                    break;
                                                case "IncrementTemperatureRequest"://调高温度
                                                    previousState.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    confirmationName = "IncrementTemperatureConfirmation";
                                                    status = 1;
                                                    temperature += Convert.ToInt16(request.payload.deltaValue.value.ToString());
                                                    if (temperature > 32)
                                                    {
                                                        temperature = 32;
                                                    }
                                                    payload.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    payload.previousState = previousState;
                                                    sb.Append("调高温度：" + request.payload.deltaValue.value + "，结果：" + temperature);
                                                    break;
                                                case "DecrementTemperatureRequest"://调低温度
                                                    previousState.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    confirmationName = "DecrementTemperatureConfirmation";
                                                    status = 1;
                                                    temperature -= Convert.ToInt16(request.payload.deltaValue.value);
                                                    if (temperature < 16)
                                                    {
                                                        temperature = 16;
                                                    }
                                                    payload.temperature = new Domain.IoTXiaoDuEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                    payload.previousState = previousState;
                                                    sb.Append("调低温度：" + request.payload.deltaValue.value + "，结果：" + temperature);
                                                    break;
                                                case "SetFanSpeedRequest"://设置风速
                                                    previousState.fanSpeed = new Domain.IoTXiaoDuEntity.FanSpeed() { value = fanSpeed };
                                                    confirmationName = "SetFanSpeedConfirmation";
                                                    status = 1;
                                                    if (request.payload.fanSpeed.level != null && !string.IsNullOrEmpty(request.payload.fanSpeed.level))
                                                    {
                                                        switch (request.payload.fanSpeed.level.ToLower())
                                                        {
                                                            case "high":
                                                            case "max":
                                                                fanSpeed = 3;
                                                                break;
                                                            case "middle":
                                                                fanSpeed = 2;
                                                                break;
                                                            case "auto":
                                                                fanSpeed = 0;
                                                                break;
                                                            default:
                                                                fanSpeed = 1;
                                                                break;
                                                        }
                                                        sb.Append("设风速：" + request.payload.fanSpeed.level);
                                                    }
                                                    else
                                                    {
                                                        fanSpeed = Convert.ToInt16(request.payload.fanSpeed.value);
                                                        if (fanSpeed < 1)
                                                        {
                                                            fanSpeed = 1;
                                                        }
                                                        else if (fanSpeed > 3)
                                                        {
                                                            fanSpeed = 3;
                                                        }
                                                        sb.Append("设风速：" + fanSpeed);
                                                    }
                                                    payload.fanSpeed = new Domain.IoTXiaoDuEntity.FanSpeed() { value = fanSpeed };
                                                    payload.previousState = previousState;
                                                    break;
                                                case "IncrementFanSpeedRequest"://调高风速
                                                    previousState.fanSpeed = new Domain.IoTXiaoDuEntity.FanSpeed() { value = fanSpeed };
                                                    confirmationName = "IncrementFanSpeedConfirmation";
                                                    status = 1;
                                                    fanSpeed += Convert.ToInt16(request.payload.deltaValue.value);
                                                    if (fanSpeed > 3)
                                                    {
                                                        fanSpeed = 3;
                                                    }
                                                    payload.fanSpeed = new Domain.IoTXiaoDuEntity.FanSpeed() { value = fanSpeed };
                                                    payload.previousState = previousState;
                                                    sb.Append("调高风速：" + request.payload.deltaValue.value + "，结果：" + fanSpeed);
                                                    break;
                                                case "DecrementFanSpeedRequest"://调低风速
                                                    previousState.fanSpeed = new Domain.IoTXiaoDuEntity.FanSpeed() { value = fanSpeed };
                                                    confirmationName = "DecrementFanSpeedConfirmation";
                                                    status = 1;
                                                    fanSpeed -= Convert.ToInt16(request.payload.deltaValue.value);
                                                    if (fanSpeed < 1)
                                                    {
                                                        fanSpeed = 1;
                                                    }
                                                    payload.fanSpeed = new Domain.IoTXiaoDuEntity.FanSpeed() { value = fanSpeed };
                                                    payload.previousState = previousState;
                                                    sb.Append("调低风速：" + request.payload.deltaValue.value + "，结果：" + fanSpeed);
                                                    break;
                                                case "SetModeRequest"://设置模式
                                                    previousState.mode = new Domain.IoTXiaoDuEntity.Mode() { value = ModeToString(mode) };
                                                    confirmationName = "SetModeConfirmation";
                                                    status = 1;
                                                    mode = ModeToInt(request.payload.mode.value);
                                                    if (mode == -1)
                                                    {
                                                        logger.Error(string.Format("{3}(酒店：{0}，房号：{1})不支持该空调模式：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, request.payload.mode.value, platformName));
                                                        return Json(ReturnXiaoDuError(request.header, "UnsupportedTargetError"), JsonRequestBehavior.AllowGet);
                                                    }
                                                    payload.mode = new Domain.IoTXiaoDuEntity.Mode() { deviceType = request.payload.mode.deviceType, value = request.payload.mode.value };
                                                    payload.previousState = previousState;
                                                    sb.Append("模式：" + request.payload.mode.value);
                                                    break;
                                                case "PauseRequest"://暂停
                                                    confirmationName = "PauseConfirmation";
                                                    status = 6;
                                                    sb.Append("状态：暂停");
                                                    break;
                                                case "ContinueRequest"://继续
                                                    confirmationName = "ContinueConfirmation";
                                                    status = 1;
                                                    sb.Append("状态：继续");
                                                    break;
                                                case "SetTVChannelRequest"://电视跳转频道
                                                    confirmationName = "SetTVChannelConfirmation";
                                                    status = 4;
                                                    int channelNumber = 0;
                                                    if (int.TryParse(request.payload.deltaValue.value, out channelNumber))
                                                    {
                                                        valve = channelNumber;
                                                    }
                                                    else
                                                    {
                                                        var channel = RoomTypeChannelsManager.LoadAll(host.RoomType.ID).Where(r => r.Name.Contains(request.payload.deltaValue.value)).FirstOrDefault();
                                                        if (channel != null)
                                                        {
                                                            valve = channel.Code;
                                                        }
                                                        else
                                                        {
                                                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的电视频道：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, request.payload.deltaValue.value, platformName));
                                                            return Json(ReturnXiaoDuError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                                        }
                                                    }
                                                    sb.Append("调整频道至：" + valve);
                                                    break;
                                                case "IncrementTVChannelRequest"://电视下一频道
                                                    confirmationName = "IncrementTVChannelConfirmation";
                                                    status = 1;
                                                    mode = 5;
                                                    sb.Append("频道：加");
                                                    break;
                                                case "DecrementTVChannelRequest"://电视上一频道
                                                    confirmationName = "DecrementTVChannelConfirmation";
                                                    status = 1;
                                                    mode = 6;
                                                    sb.Append("频道：减");
                                                    break;
                                                case "ReturnTVChannelRequest"://返回上一个观看频道
                                                    confirmationName = "ReturnTVChannelConfirmation";
                                                    status = 1;
                                                    mode = 15;
                                                    sb.Append("电视：回看");
                                                    break;
                                                case "IncrementVolumeRequest"://增大音量
                                                    confirmationName = "IncrementVolumeConfirmation";
                                                    status = 1;
                                                    mode = 3;
                                                    sb.Append("音量：加");
                                                    break;
                                                case "DecrementVolumeRequest"://减小音量
                                                    confirmationName = "DecrementVolumeConfirmation";
                                                    status = 1;
                                                    mode = 4;
                                                    sb.Append("音量：减");
                                                    break;
                                                //case "SetVolumeRequest"://设置音量
                                                //    confirmationName = "SetVolumeConfirmation";
                                                //    break;
                                                case "SetVolumeMuteRequest"://设置静音
                                                    confirmationName = "SetVolumeMuteConfirmation";
                                                    status = 1;
                                                    mode = 1;
                                                    sb.Append("音量：静音");
                                                    break;
                                                case "SetDirectionRequest"://设置方向：扫地机，遥控器上下左右
                                                    confirmationName = "SetDirectionConfirmation";
                                                    status = 1;
                                                    string value = request.payload.direction.value.ToUpper();
                                                    switch (value)
                                                    {
                                                        case "FORWARD":
                                                            mode = 7;
                                                            break;
                                                        case "BACKWARD":
                                                            mode = 8;
                                                            break;
                                                        case "LEFT":
                                                            mode = 9;
                                                            break;
                                                        case "RIGHT":
                                                            mode = 10;
                                                            break;
                                                    }
                                                    sb.Append("移动方向：" + value);
                                                    break;
                                                default:
                                                    return Json(ReturnXiaoDuError(request.header, "UnsupportedTargetError"), JsonRequestBehavior.AllowGet);
                                            }
                                            #endregion
                                            var strq = "";
                                            if (hostmodal_L.Count == 0)
                                            {
                                                strq = hostModal.Modal.Name;
                                            }
                                            else
                                            {
                                                strq = hostmodal_L.FirstOrDefault().Modal.MultipleTCLName;
                                            }
                                            attributes.Add(new Domain.IoTXiaoDuEntity.ControlResponse.Attributes()
                                            {
                                                name = "name",
                                                //value = hostModal.Modal.Name, 
                                                value = strq,
                                                scale = "",
                                                timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false),
                                                uncertaintyInMilliseconds = "10"
                                            });
                                            attributes.Add(new Domain.IoTXiaoDuEntity.ControlResponse.Attributes() { name = "turnOnState", value = status == 1 ? "ON" : "OFF", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });


                                            if (is_monitor)
                                            {
                                                IOTMonitorData i = new IOTMonitorData();
                                                i.CreateTime = DateTime.Now;
                                                i.ControlClass = ControlClass_KongZhiSheBei;
                                                i.WhichOneDevice = new List<IotDeviceData>()
                                                {
                                                    new IotDeviceData(){DeviceName=hostModal.Modal.Name,DeviceAddress=hostModal.Modal.ModalAddress}
                                                };
                                                i.Step = 3;
                                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                i.TriggerTime = ti;
                                                i.CreateTime = DateTime.Now;
                                                i.HotelId = a;
                                                i.HotelCode = hotel_code;
                                                i.RoomNumber = b;
                                                //i.RequestId = messageid; 
                                                i.RequestId = logmsgid;
                                                i.Platform = platformName;
                                                i.CommandDescription = sb.ToString();
                                                SendMQTTData.Send(i);
                                            }

                                            //如果是调光的话 就这样控制
                                            if (hostmodal_L.Count > 0)
                                            {
                                                foreach (var item in hostmodal_L)
                                                {
                                                    HostModalManager.SetDevice(host, item, status, item.Brightness, temperature, fanSpeed, mode, valve);
                                                }
                                            }
                                            else
                                            {

                                                string KongTiaoControlName = request.header.name;
                                                bool bsa = hostModal.Modal.Type == DeviceType.AirConditioner;
                                                string KKKey = System.Guid.NewGuid().ToString("N");

                                                bool wendu1 = KongTiaoControlName.Equals("IncrementTemperatureRequest") || KongTiaoControlName.Equals("IncrementTemperatureRequest") || KongTiaoControlName.Equals("SetTemperatureRequest");
                                                bool fengsu1 = KongTiaoControlName.Equals("SetFanSpeedRequest") || KongTiaoControlName.Equals("IncrementFanSpeedRequest") || KongTiaoControlName.Equals("DecrementFanSpeedRequest");
                                                bool moshi1 = KongTiaoControlName.Equals("SetModeRequest");
                                                //特殊酒店
                                                if (AssertFault(hotel_code))
                                                {
                                                    for (int i = 0; i < 3; i++)
                                                    {
                                                        Thread.Sleep(200);
                                                        //对房间设备进行操作
                                                        //HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                                                        if (request.header.name.Equals("TurnOnRequest") && hostModal.Modal.Type == DeviceType.AirConditioner)
                                                        {
                                                            HostModalManager.SetDevice_Repeat(KKKey, host, hostModal, status, 0, 0, 0, 0, 0);
                                                        }
                                                        else if (wendu1 && bsa)
                                                        {
                                                            HostModalManager.SetDevice(host, hostModal, 0, 0, temperature, 0, 0, 0);
                                                        }
                                                        else if (fengsu1 && bsa)
                                                        {
                                                            HostModalManager.SetDevice(host, hostModal, 0, 0, 0, fanSpeed, 0, 0);
                                                        }
                                                        else if (moshi1 && bsa)
                                                        {
                                                            HostModalManager.SetDevice(host, hostModal, 0, 0, 0, 0, mode, 0);
                                                        }
                                                        else
                                                        {
                                                            HostModalManager.SetDevice_Repeat(KKKey, host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if (KongTiaoControlName.Equals("TurnOnRequest") && bsa)
                                                    {
                                                        HostModalManager.SetDevice(host, hostModal, status, 0, 0, 0, 0, 0);
                                                    }
                                                    else if (wendu1 && bsa)
                                                    {
                                                        HostModalManager.SetDevice(host, hostModal, 0, 0, temperature, 0, 0, 0);
                                                    }
                                                    else if (fengsu1 && bsa)
                                                    {
                                                        HostModalManager.SetDevice(host, hostModal, 0, 0, 0, fanSpeed, 0, 0);
                                                    }
                                                    else if (moshi1 && bsa)
                                                    {
                                                        HostModalManager.SetDevice(host, hostModal, 0, 0, 0, 0, mode, 0);
                                                    }
                                                    else
                                                    {

                                                        string tiaowen = request.header.name;
                                                        if (tiaowen.Equals("IncrementTemperatureRequest") || tiaowen.Equals("DecrementTemperatureRequest"))
                                                        {
                                                            HostModalManager.SetDevice(host, hostModal, 1, 0);
                                                            Thread.Sleep(50);
                                                        }
                                                        //对房间设备进行操作
                                                        HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                                                    }
                                                }
                                            }
                                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                                        }
                                        break;
                                    #endregion
                                }
                            }
                            payload.attributes = attributes;
                            //操作完成响应小度
                            Domain.IoTXiaoDuEntity.ControlResponse.ControlAppResponse response = new Domain.IoTXiaoDuEntity.ControlResponse.ControlAppResponse
                            {
                                header = new Domain.IoTXiaoDuEntity.Header
                                {
                                    messageId = request.header.messageId,
                                    @namespace = request.header.@namespace,
                                    name = confirmationName,
                                    payloadVersion = request.header.payloadVersion
                                },
                                payload = payload
                            };

                            if (is_monitor)
                            {
                                IOTMonitorData i = new IOTMonitorData();
                                i.Step = 4;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.CreateTime = DateTime.Now;
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.HotelCode = hotel_code;
                                i.RoomNumber = b;
                                i.RequestId = logmsgid;
                                i.Platform = platformName;
                                i.CommandDescription = "success";
                                SendMQTTData.Send(i);
                            }
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    default:
                        return Json(ReturnXiaoDuError(request.header, "UnsupportedTargetError"), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {

                IOTMonitorData i = new IOTMonitorData();
                i.Step = 3.1;
                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");

                i.CreateTime = DateTime.Now;
                i.TriggerTime = ti;
                i.HotelId = g_hotelid;
                i.HotelCode = g_hotelcode;
                i.RoomNumber = g_roomnum;
                i.RequestId = g_requestid;
                i.Platform = platformName;
                string sss = ex.Message;
                i.CommandDescription = ex.Message;
                SendMQTTData.Send(i);
                logger.Error(string.Format("处理小度或TCL电视语音设备命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 查询小度并且入库
        /// </summary>
        /// <param name="XiaoDuCUID"></param>
        /// <returns></returns>
        private Host XiaoDuQuery(string XiaoDuCUID)
        {
            Host host = null;
            string XiaoDuKongZhiKey = CacheKey.XiaoDuYuYin + "_" + XiaoDuCUID;
            var UXV = HttpContext.Cache.Get(XiaoDuKongZhiKey);
            if (UXV != null)
            {
                host = UXV as Host;
            }
            else
            {
                //host = HostManager.GetByTCLCUID(XiaoDuCUID);

                host = HostManager.GetByXiaoDuCUID(XiaoDuCUID);//根据小度音箱序列号获取对应RCU主机  
                if (host != null)
                {
                    string code = host.SysHotel.Code;
                    string roomno = host.RoomNumber;
                    string KKA = CacheKey.XiaoDuCacheUpdate + "_" + code + "_" + roomno;
                    CSRedisCacheHelper.Set_PartitionWithTime<string>(KKA, XiaoDuCUID, 120);
                    HttpContext.Cache.Insert(XiaoDuKongZhiKey, host, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration);
                }
            }
            return host;
        }

        /// <summary>
        /// TCL
        /// </summary>
        /// <param name="XiaoDuCUID"></param>
        /// <returns></returns>
        private Host TCLDataQuery(string TCLCUID)
        {
            Host host = null;
            string XiaoDuKongZhiKey = CacheKey.TCLYuYin + "_" + TCLCUID;
            var UXV = HttpContext.Cache.Get(XiaoDuKongZhiKey);
            if (UXV != null)
            {
                host = UXV as Host;
            }
            else
            {
                host = HostManager.GetByTCLCUID(TCLCUID);
                if (host != null)
                {
                    string code = host.SysHotel.Code;
                    string roomno = host.RoomNumber;
                    string KKA = CacheKey.XiaoDuCacheUpdate + "_" + code + "_" + roomno;
                    CSRedisCacheHelper.Set_PartitionWithTime<string>(KKA, TCLCUID, 120);
                    HttpContext.Cache.Insert(XiaoDuKongZhiKey, host, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration);
                }
            }

            return host;
        }

        /// <summary>
        /// 从缓存中取出数据
        /// </summary>
        /// <param name="host"></param>
        /// <param name="modalAddress"></param>
        /// <returns></returns>
        private HostModal GetDataFromCache(Host host, string modalAddress)
        {
            //HostModal hostModal = new HostModal();
            //RoomTypeModal rrr1 = new RoomTypeModal();
            //hostModal.Modal = rrr1;

            HostModal hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);//设备控制
            string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + modalAddress;
            var hostModal_T = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
            if (hostModal_T != null)
            {
                hostModal.Status = hostModal_T.Status;
                hostModal.Brightness = hostModal_T.Brightness;

                var aaa = hostModal_T.AirConditionData;
                hostModal.SettingTemp = aaa.SettingTemp;
                hostModal.FanSpeed = aaa.FanSpeed;
                hostModal.Mode = aaa.Mode;
                hostModal.Valve = aaa.Valve;
                hostModal.CurrentTemp = aaa.CurrentTemp;
            }
            //else
            //{
            //    //模式：1制冷，2制热，3送风
            //    //风速：0自动，1低，2中，3高
            //    hostModal = new HostModal();
            //    hostModal.Modal = new RoomTypeModal() { Name = "12", ModalAddress = "007000001" };
            //    hostModal.Status = 0;
            //    hostModal.Brightness = 100;

            //    hostModal.SettingTemp = 25;
            //    hostModal.FanSpeed = 3;
            //    hostModal.Mode = 3;
            //    hostModal.Valve = 2;
            //    hostModal.CurrentTemp = 25;
            //}
            return hostModal;
        }
        /// <summary>
        /// 返回错误信息
        /// </summary>
        /// <param name="header"></param>
        /// <param name="errorName"></param>
        /// <returns></returns>
        private Domain.IoTXiaoDuEntity.Error.ErrorResponse ReturnXiaoDuError(Domain.IoTXiaoDuEntity.Header header, string errorName)
        {
            Domain.IoTXiaoDuEntity.Error.ErrorResponse err = new Domain.IoTXiaoDuEntity.Error.ErrorResponse
            {
                header = new Domain.IoTXiaoDuEntity.Header
                {
                    messageId = header.messageId,
                    @namespace = header.@namespace,
                    name = errorName,
                    payloadVersion = header.payloadVersion
                },
                payload = new Domain.IoTXiaoDuEntity.Error.Payload { }
            };
            return err;
        }
        /// <summary>
        /// 空调模式转换
        /// </summary>
        /// <param name="mode"></param>
        /// <returns></returns>
        private string ModeToString(int mode)
        {
            string result = "AUTO";
            switch (mode)
            {
                case 1:
                    result = "COOL";
                    break;
                case 2:
                    result = "HEAT";
                    break;
                case 3:
                    result = "FAN";
                    break;
            }
            return result;
        }
        /// <summary>
        /// 空调模式转换
        /// </summary>
        /// <param name="mode"></param>
        /// <returns></returns>
        private int ModeToInt(string mode)
        {
            int result = 0;
            if (mode != null)
            {
                switch (mode.ToUpper())
                {
                    case "COOL":
                    case "COLD":
                        result = 1;
                        break;
                    case "HEAT":
                    case "HOT":
                        result = 2;
                        break;
                    case "FAN":
                    case "DRY":
                        result = 3;
                        break;
                    default:
                        result = -1;
                        break;
                }
            }
            return result;
        }
        /// <summary>
        /// 小度类型转换
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private int XiaoDuToBLW(string value)
        {
            switch (value.ToLower())
            {
                case "min"://最小
                    return 0;
                case "max"://最大
                    return 100;
                case "low"://低
                    return 1;
                case "middle"://中
                    return 2;
                case "high"://高
                    return 3;
                case "step":
                    return 1;
                default:
                    double result = 0;
                    if (!Double.TryParse(value, out result))
                    {
                        result = 26;
                    }
                    return Convert.ToInt32(result);
            }
        }
        private string StatusToString(int status)
        {
            return status == 1 ? "on" : "off";
        }
        #endregion

        #region TCL电视智能语音对接（老版本）
        public ActionResult GetDevicesForTV()
        {
            return GetDevicesForTCL();
        }
        public ActionResult GetDevicesForTCL()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            try
            {
                Domain.IoTTCLEntity.TCLRequest request = JsonConvert.DeserializeObject<Domain.IoTTCLEntity.TCLRequest>(reqData);//得到TCL请求
                string tclCUID = request.info.hotel + "&" + request.info.room;
                Host host = HostManager.GetByTCLCUID(tclCUID);//根据TCL的酒店ID和房号获取对应主机             
                if (host == null)
                {
                    request.code = "100";
                    request.msg = string.Format("TV设备(hotel:{0},room:{1})尚未绑定客房主机", request.info.hotel, request.info.room);
                    //logger.Error(request.msg);
                    return Json(request, JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    request.code = "100";
                    request.msg = "当前访问酒店已过期";
                    //return Json(request, JsonRequestBehavior.AllowGet);
                }
                List<Domain.IoTTCLEntity.TCLData> data = new List<Domain.IoTTCLEntity.TCLData>();
                //获取需要控制的场景
                IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                foreach (RoomTypeScene scene in sceneModals)
                {
                    data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = scene.ID.ToString(), deviceType = "scene", deviceName = scene.Name });
                }
                //获取需要控制的设备信息
                IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                foreach (HostModal hostModal in hostModals)
                {
                    switch (hostModal.Modal.Type)
                    {
                        case DeviceType.Relay:
                        case DeviceType.Dimmer:
                        case DeviceType.Traic:
                        case DeviceType.PWMDimmer:
                        case DeviceType.PWMExpand:
                        case DeviceType.PBLED:
                        case DeviceType.LVout://弱电输出
                        case DeviceType.PB20:
                        case DeviceType.PB20_LD:
                        case DeviceType.PB20_LS:
                            data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "light", deviceName = hostModal.Modal.Name });
                            break;
                        case DeviceType.AirConditioner:
                            data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "air#switch", deviceName = hostModal.Modal.Name });
                            data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "air#temp", deviceName = hostModal.Modal.Name });
                            data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "air#mode", deviceName = hostModal.Modal.Name });
                            data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "air#wind", deviceName = hostModal.Modal.Name });
                            break;
                        case DeviceType.Curtain:
                            data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "curtain", deviceName = hostModal.Modal.Name });
                            break;
                        case DeviceType.ServiceInfo:
                            data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "service", deviceName = hostModal.Modal.Name });
                            break;
                    }
                }
                request.code = "0";
                request.data = data;
                //logger.Error(string.Format("TV(酒店：{0}，房号：{1})本次获取设备数量：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, data.Count.ToString()));
                return new ContentResult
                {
                    Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(request),
                    ContentType = "application/json"
                };
            }
            catch (Exception ex)
            {
                Domain.IoTTCLEntity.TCLRequest request = new Domain.IoTTCLEntity.TCLRequest();
                request.code = "101";
                request.msg = ex.Message;
                logger.Error(string.Format("RequestData:{0},error:{1}", reqData, ex.ToString()));
                return Json(request, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult SetDevicesForTV()
        {
            return SetDevicesForTCL();
        }

        public ActionResult SetDevicesForTCL()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            try
            {
                Domain.IoTTCLEntity.TCLRequest request = JsonConvert.DeserializeObject<Domain.IoTTCLEntity.TCLRequest>(reqData);//得到TCL请求
                string tclCUID = request.info.hotel + "&" + request.info.room;
                Host host = HostManager.GetByTCLCUID(tclCUID);//根据TCL的酒店ID和房号获取对应主机             
                if (host == null)
                {
                    request.code = "100";
                    request.msg = string.Format("TV设备(hotel:{0},room:{1})尚未绑定客房主机", request.info.hotel, request.info.room);
                    //logger.Error(request.msg);
                    return Json(request, JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    request.code = "100";
                    request.msg = "当前访问酒店已过期";
                    //return Json(request, JsonRequestBehavior.AllowGet);
                }
                if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                {
                    request.code = "100";
                    request.msg = string.Format("TV设备(hotel:{0},room:{1})网络异常", request.info.hotel, request.info.room);
                    return Json(request, JsonRequestBehavior.AllowGet);
                }
                if (!CheckGetPower(host))
                {
                    request.code = "100";
                    request.msg = string.Format("TV设备(hotel:{0},room:{1})非取电状态，不可控制！", request.info.hotel, request.info.room);
                    return Json(request, JsonRequestBehavior.AllowGet);
                }
                foreach (Domain.IoTTCLEntity.TCLData data in request.data)
                {
                    if (data.deviceType == "scene")
                    {
                        var scene = RoomTypeSceneManager.Get(int.Parse(data.deviceID));
                        if (scene == null)
                        {
                            return Json("没有找到对应的场景", JsonRequestBehavior.AllowGet);
                        }
                        LightControlManager.ApplyScene(host, scene);
                        SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, "TCL TV", host.SysHotel.ID);
                    }
                    else
                    {
                        var hostModal = HostModalManager.GetByModalAddress(host.ID, data.deviceID);//设备控制
                        if (hostModal == null)
                        {
                            return Json("没有找到对应的设备", JsonRequestBehavior.AllowGet);
                        }
                        int status = 0;//hostModal.Status;
                        int brightness = 0;//hostModal.Brightness;
                        int temperature = 0;//hostModal.SettingTemp;
                        int fanSpeed = 0;//hostModal.FanSpeed;
                        int mode = 0;//hostModal.Mode;
                        int valve = 0;//hostModal.Valve;
                        switch (data.value)
                        {
                            case "on":
                                status = 1;
                                brightness = 100;
                                break;
                            case "off":
                                status = 2;
                                brightness = 0;
                                break;
                            default:
                                switch (data.deviceType)
                                {
                                    case "air#temp":
                                        //status = 1;
                                        temperature = Convert.ToInt16(data.value);
                                        if (temperature < 16)
                                        {
                                            temperature = 16;
                                        }
                                        else if (temperature > 32)
                                        {
                                            temperature = 32;
                                        }
                                        break;
                                    case "air#mode":
                                        //status = 1;
                                        mode = ModeToInt(data.value.ToUpper());
                                        break;
                                    case "air#wind":
                                        //status = 1;
                                        fanSpeed = XiaoDuToBLW(data.value);
                                        break;
                                }
                                break;
                        }
                        //对房间设备进行操作
                        HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                        string action = "打开";
                        if (status == 2)
                        {
                            action = "关闭";
                        }
                        else if (status == 6)
                        {
                            action = "暂停";
                        }
                        string detail = string.Format("{0}客房{1}{2}({3})", action, host.RoomNumber, hostModal.Modal.Name, data.deviceID);
                        SaveSystemLog(AuthorityID, "设备控制", detail, true, "TCL TV", host.SysHotel.ID);
                    }
                }
                request.code = "0";
                request.msg = "控制成功";
                return Json(request, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Domain.IoTTCLEntity.TCLRequest request = new Domain.IoTTCLEntity.TCLRequest();
                request.code = "101";
                request.msg = ex.Message;
                logger.Error(string.Format("RequestData:{0},error:{1}", reqData, ex.ToString()));
                return Json(request, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult GetDevicesStatusForTV()
        {
            return GetDevicesStatusForTCL();
        }

        public ActionResult GetDevicesStatusForTCL()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            try
            {
                Domain.IoTTCLEntity.TCLRequest request = JsonConvert.DeserializeObject<Domain.IoTTCLEntity.TCLRequest>(reqData);//得到TCL请求
                string tclCUID = request.info.hotel + "&" + request.info.room;
                Host host = HostManager.GetByTCLCUID(tclCUID);//根据TCL的酒店ID和房号获取对应主机             
                if (host == null)
                {
                    request.code = "100";
                    request.msg = string.Format("TV设备(hotel:{0},room:{1})尚未绑定客房主机", request.info.hotel, request.info.room);
                    //logger.Error(request.msg);
                    return Json(request, JsonRequestBehavior.AllowGet);
                }
                List<Domain.IoTTCLEntity.TCLData> data = new List<Domain.IoTTCLEntity.TCLData>();
                if (null == request.data || request.data.Count == 0)
                {
                    //获取需要控制的设备信息
                    IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                    foreach (HostModal hostModal in hostModals)
                    {
                        switch (hostModal.Modal.Type)
                        {
                            case DeviceType.Relay:
                            case DeviceType.Dimmer:
                            case DeviceType.Traic:
                            case DeviceType.PWMDimmer:
                            case DeviceType.PWMExpand:
                            case DeviceType.PBLED:
                            case DeviceType.LVout://弱电输出
                            case DeviceType.PB20:
                            case DeviceType.PB20_LD:
                            case DeviceType.PB20_LS:
                                data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "light", deviceName = hostModal.Modal.Name, value = StatusToString(hostModal.Status) });
                                break;
                            case DeviceType.Curtain:
                                data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "curtain", deviceName = hostModal.Modal.Name, value = StatusToString(hostModal.Status) });
                                break;
                            case DeviceType.ServiceInfo:
                                data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "service", deviceName = hostModal.Modal.Name, value = StatusToString(hostModal.Status) });
                                break;
                        }
                    }
                }
                else
                {
                    foreach (Domain.IoTTCLEntity.TCLData tclData in request.data)
                    {
                        HostModal hostModal = HostModalManager.GetByModalAddress(host.ID, tclData.deviceID);
                        if (null != hostModal)
                        {
                            switch (hostModal.Modal.Type)
                            {
                                case DeviceType.Relay:
                                case DeviceType.Dimmer:
                                case DeviceType.Traic:
                                case DeviceType.PWMDimmer:
                                case DeviceType.PWMExpand:
                                case DeviceType.PBLED:
                                case DeviceType.LVout://弱电输出
                                case DeviceType.PB20:
                                case DeviceType.PB20_LD:
                                case DeviceType.PB20_LS:
                                    data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "light", deviceName = hostModal.Modal.Name, value = StatusToString(hostModal.Status) });
                                    break;
                                case DeviceType.Curtain:
                                    data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "curtain", deviceName = hostModal.Modal.Name, value = StatusToString(hostModal.Status) });
                                    break;
                                case DeviceType.ServiceInfo:
                                    data.Add(new Domain.IoTTCLEntity.TCLData() { deviceID = hostModal.Modal.ModalAddress, deviceType = "service", deviceName = hostModal.Modal.Name, value = StatusToString(hostModal.Status) });
                                    break;
                            }
                        }
                    }
                }
                request.code = "0";
                request.data = data;
                return new ContentResult
                {
                    Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(request),
                    ContentType = "application/json"
                };
            }
            catch (Exception ex)
            {
                Domain.IoTTCLEntity.TCLRequest request = new Domain.IoTTCLEntity.TCLRequest();
                request.code = "101";
                request.msg = ex.Message;
                logger.Error(string.Format("RequestData:{0},error:{1}", reqData, ex.ToString()));
                return Json(request, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region DUI语音对接（飞响电视）
        /// <summary>
        /// DUI语音对接：主动上报ApiKey：b4b4c81c01e446b4b40f85b196c6aaec
        /// </summary>
        /// <returns></returns>
        public ActionResult Dui()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            string msg;
            try
            {
                Domain.IoTDUIEntity.Request.AppliancesRequest request = JsonConvert.DeserializeObject<Domain.IoTDUIEntity.Request.AppliancesRequest>(reqData);//得到DUI请求
                string accessToken = request.payload.accessToken;
                if (string.IsNullOrEmpty(accessToken))
                {
                    msg = "accessToken不能为空";
                    return Json(ReturnDUIError(request.header, "ACCESS_TOKEN_INVALIDATE", msg), JsonRequestBehavior.AllowGet);
                }
                string hotelCode = accessToken.Substring(0, accessToken.IndexOf("BLW"));
                SysHotel hotel = SysHotelManager.GetByCode(hotelCode);//根据酒店编码获取酒店
                if (hotel == null)
                {
                    msg = "DUI未找到对应酒店(accessToken:" + hotelCode + ")";
                    //logger.Error(msg);
                    return Json(ReturnDUIError(request.header, "ACCESS_TOKEN_INVALIDATE", msg), JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > hotel.ValidateDate)//酒店已到期
                {
                    //return Json(ReturnDUIError(request.header, "ACCESS_TOKEN_INVALIDATE", "当前访问酒店已过期"), JsonRequestBehavior.AllowGet);
                }
                string roomNumber = request.payload.group;//控制的时候DUI不传入房号
                if (string.IsNullOrEmpty(roomNumber))
                {
                    if (null == request.payload.appliance || string.IsNullOrEmpty(request.payload.appliance.applianceId))
                    {
                        msg = "DUI无法获取房号，payload.appliance.applianceId为空";
                        logger.Error(msg);
                        return Json(ReturnDUIError(request.header, "DEVICE_IS_NOT_EXIST", msg), JsonRequestBehavior.AllowGet);
                    }
                    roomNumber = request.payload.appliance.applianceId.Split('&')[2];//获取房号
                }
                Host host = HostManager.GetByRoomNumber(roomNumber, hotel.ID);
                if (host == null)
                {
                    msg = string.Format("DUI未找到对应客房主机(hotelCode:{0},roomNumber:{1})", hotelCode, roomNumber);
                    //logger.Error(msg);
                    return Json(ReturnDUIError(request.header, "DEVICE_IS_NOT_EXIST", msg), JsonRequestBehavior.AllowGet);
                }
                //判断技能类型
                switch (request.header.@namespace)
                {
                    case "DUI.SmartHome.Discovery"://发现设备
                        {
                            List<Domain.IoTDUIEntity.DiscoverResponse.DiscoveredAppliances> appliances = new List<Domain.IoTDUIEntity.DiscoverResponse.DiscoveredAppliances>();
                            List<string> applianceIds = new List<string>();
                            //获取需要控制的场景
                            IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                            foreach (RoomTypeScene scene in sceneModals)
                            {
                                string aliasNames = string.IsNullOrEmpty(scene.AliasName) ? "" : scene.AliasName;
                                appliances.Add(new Domain.IoTDUIEntity.DiscoverResponse.DiscoveredAppliances
                                {
                                    applianceId = scene.ID + "&" + "SCENE_TRIGGER" + "&" + roomNumber,
                                    group = host.RoomNumber,//房号
                                    friendlyName = scene.Name,
                                    aliasNames = new List<string>(aliasNames.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)),
                                    applianceType = "SCENE_TRIGGER",
                                    manufacturerName = "宝来威(Boonlive)",
                                    modelName = Common.Tools.GetDescription(scene.Type),
                                    zone = "",//host.RoomType.Name,//房型名称
                                    description = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + scene.Name,
                                    actions = new List<string> { "turnOn" },
                                    additionalApplianceDetails = new Dictionary<string, string>()
                                });
                                applianceIds.Add(scene.ID + "&" + "SCENE_TRIGGER");
                            }
                            //获取需要控制的设备信息
                            IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                            applianceIds = new List<string>();
                            foreach (HostModal hostModal in hostModals)
                            {
                                string applianceType;
                                List<string> actions = new List<string>();
                                switch (hostModal.Modal.Type)
                                {
                                    case DeviceType.Dimmer:
                                    case DeviceType.Traic:
                                    case DeviceType.PWMDimmer:
                                    case DeviceType.PWMExpand:
                                    case DeviceType.PBLED:
                                    case DeviceType.LVout://弱电输出
                                    case DeviceType.PB20:
                                    case DeviceType.PB20_LD:
                                    case DeviceType.PB20_LS:
                                        applianceType = "LIGHT";
                                        actions.Add("TurnOn");
                                        actions.Add("TurnOff");
                                        actions.Add("SetBrightness");
                                        actions.Add("IncreaseBrightness");
                                        actions.Add("DecreaseBrightness");
                                        break;
                                    case DeviceType.Strip://灯带：如果000回路打勾，则是调色，否则是调光
                                        applianceType = "LIGHT";
                                        actions.Add("TurnOn");
                                        actions.Add("TurnOff");
                                        //if (hostModal.Modal.ModalAddress.Substring(6) == "000")
                                        //{
                                        //    actions.Add("SetColorTemperature");
                                        //    actions.Add("IncreaseColorTemperature");
                                        //    actions.Add("DecreaseColorTemperature");
                                        //}
                                        //else
                                        //{
                                        actions.Add("SetBrightness");
                                        actions.Add("IncreaseBrightness");
                                        actions.Add("DecreaseBrightness");
                                        //}
                                        break;
                                    case DeviceType.AirConditioner:
                                        applianceType = "AIR_CONDITION";
                                        actions.Add("TurnOn");
                                        actions.Add("TurnOff");
                                        actions.Add("SetTemperature");
                                        actions.Add("IncreaseTemperature");
                                        actions.Add("DecreaseTemperature");
                                        actions.Add("SetWindSpeed");
                                        actions.Add("IncreaseWindSpeed");
                                        actions.Add("DecreaseWindSpeed");
                                        actions.Add("SetMode");
                                        break;
                                    case DeviceType.Curtain:
                                        applianceType = "CURTAIN";
                                        actions.Add("TurnOn");
                                        actions.Add("TurnOff");
                                        actions.Add("Pause");
                                        actions.Add("Continue");
                                        break;
                                    case DeviceType.TV:
                                        applianceType = "TV_SET";
                                        actions.Add("TurnOn");
                                        actions.Add("TurnOff");
                                        actions.Add("SetChannel");
                                        actions.Add("SetChannelName");
                                        actions.Add("IncreaseChannel");
                                        actions.Add("DecreaseChannel");
                                        actions.Add("returnTVChannel");
                                        actions.Add("SetVolume");
                                        actions.Add("IncreaseVolume");
                                        actions.Add("DecreaseVolume");
                                        actions.Add("SetMute");
                                        actions.Add("CancelMute");
                                        break;
                                    case DeviceType.Music:
                                        applianceType = "TV_SET";
                                        actions.Add("TurnOn");
                                        actions.Add("TurnOff");
                                        actions.Add("SetVolume");
                                        actions.Add("IncreaseVolume");
                                        actions.Add("DecreaseVolume");
                                        actions.Add("SetMute");
                                        actions.Add("CancelMute");
                                        break;
                                    default:
                                        applianceType = "SWITCH";
                                        actions.Add("TurnOn");
                                        actions.Add("TurnOff");
                                        break;
                                }
                                string aliasNames = string.IsNullOrEmpty(hostModal.Modal.AliasName) ? "" : hostModal.Modal.AliasName;
                                appliances.Add(new Domain.IoTDUIEntity.DiscoverResponse.DiscoveredAppliances
                                {
                                    applianceId = hostModal.Modal.ModalAddress + "&" + applianceType + "&" + roomNumber,
                                    group = host.RoomNumber,//房号
                                    friendlyName = hostModal.Modal.Name,
                                    aliasNames = new List<string>(aliasNames.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)),
                                    applianceType = applianceType,
                                    manufacturerName = "宝来威(Boonlive)",
                                    modelName = Common.Tools.GetDescription(hostModal.Modal.Type),
                                    zone = "",//host.RoomType.Name,//房型名称
                                    description = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + hostModal.Modal.Name,
                                    actions = actions,
                                    additionalApplianceDetails = new Dictionary<string, string>()
                                });
                                applianceIds.Add(hostModal.Modal.ModalAddress + "&" + applianceType);
                            }
                            //找到可控场景和设备，响应小度DuerOS
                            Domain.IoTDUIEntity.DiscoverResponse.AppliancesResponse response = new Domain.IoTDUIEntity.DiscoverResponse.AppliancesResponse
                            {
                                header = new Domain.IoTDUIEntity.Header
                                {
                                    messageId = request.header.messageId,
                                    @namespace = request.header.@namespace,
                                    name = "DiscoverResponse",
                                    payloadVersion = request.header.payloadVersion
                                },
                                payload = new Domain.IoTDUIEntity.DiscoverResponse.Payload
                                {
                                    appliances = appliances
                                }
                            };
                            logger.Error(string.Format("DUI(酒店：{0}，房号：{1})本次获取设备数量：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, response.payload.appliances.Count.ToString()));
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    case "DUI.SmartHome.Control"://控制消息
                        {
                            if (!CheckGetPower(host))
                            {
                                return Json(ReturnDUIError(request.header, "NOT_SUPPORT_ON_CURRENT_STATUS", "非取电状态，不可控制！"), JsonRequestBehavior.AllowGet);
                            }
                            if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                            {
                                return Json(ReturnDUIError(request.header, "IOT_DEVICE_OFFLINE", "当前客房主机不在线"), JsonRequestBehavior.AllowGet);
                            }
                            string modalAddress = request.payload.appliance.applianceId.Split('&')[0];//设备地址或场景ID
                            string applianceType = request.payload.appliance.applianceId.Split('&')[1];//设备类型
                            if (applianceType == "SCENE_TRIGGER")//场景控制
                            {
                                var scene = RoomTypeSceneManager.Get(int.Parse(modalAddress));
                                if (scene == null)
                                {
                                    logger.Error(string.Format("DUI(酒店：{0}，房号：{1})未找到对应的场景，ID：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress));
                                    return Json(ReturnDUIError(request.header, "DEVICE_IS_NOT_EXIST", "场景未找到(id:" + modalAddress + ")"), JsonRequestBehavior.AllowGet);
                                }
                                LightControlManager.ApplyScene(host, scene);
                                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, "DUI TV", host.SysHotel.ID);
                            }
                            else
                            {
                                var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);//设备控制
                                if (hostModal == null)
                                {
                                    logger.Error(string.Format("DUI(酒店：{0}，房号：{1})未找到对应的回路，Address：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress));
                                    return Json(ReturnDUIError(request.header, "DEVICE_IS_NOT_EXIST", "设备未找到(modalAddress:" + modalAddress + ")"), JsonRequestBehavior.AllowGet);
                                }
                                int status = hostModal.Status;
                                int brightness = hostModal.Brightness;
                                int temperature = hostModal.SettingTemp;
                                int fanSpeed = hostModal.FanSpeed;
                                int mode = hostModal.Mode;
                                int valve = hostModal.Valve;
                                switch (request.header.name)
                                {
                                    case "TurnOn"://打开
                                        status = 1;
                                        brightness = 100;
                                        break;
                                    case "TurnOff"://关闭
                                        status = 2;
                                        brightness = 0;
                                        break;
                                    case "SetBrightness"://设置亮度
                                        status = 1;
                                        brightness = DuiToBLW(request.payload.brightness.value);
                                        break;
                                    case "IncreaseBrightness"://调亮
                                        status = 1;
                                        brightness += DuiToBLW(request.payload.deltaBrightness.value);
                                        if (brightness > 100)
                                        {
                                            brightness = 100;
                                        }
                                        break;
                                    case "DecreaseBrightness"://调暗
                                        status = 1;
                                        brightness -= DuiToBLW(request.payload.deltaBrightness.value);
                                        if (brightness < 0)
                                        {
                                            brightness = 0;
                                            status = 2;
                                        }
                                        break;
                                    case "SetColorTemperature":
                                        break;
                                    case "IncreaseColorTemperature":
                                        break;
                                    case "DecreaseColorTemperature":
                                        break;
                                    case "SetTemperature"://设置温度
                                        status = 1;
                                        temperature = DuiToBLW(request.payload.temperature.value);
                                        if (temperature < 16)
                                        {
                                            temperature = 16;
                                        }
                                        else if (temperature > 32)
                                        {
                                            temperature = 32;
                                        }
                                        break;
                                    case "IncreaseTemperature"://调高温度
                                        status = 1;
                                        temperature += DuiToBLW(request.payload.deltaTemperature.value);
                                        if (temperature > 32)
                                        {
                                            temperature = 32;
                                        }
                                        break;
                                    case "DecreaseTemperature"://调低温度
                                        status = 1;
                                        temperature -= DuiToBLW(request.payload.deltaTemperature.value);
                                        if (temperature < 16)
                                        {
                                            temperature = 16;
                                        }
                                        break;
                                    case "SetVolume"://设置音量
                                    case "IncreaseVolume"://增大音量
                                    case "DecreaseVolume"://减小音量
                                    case "SetMute"://设置静音
                                    case "CancelMute"://取消静音
                                    case "SetChannel"://设置频道
                                    case "SetChannelName"://设置频道
                                    case "IncreaseChannel"://设置频道
                                    case "DecreaseChannel"://设置频道
                                        break;
                                    case "SetWindSpeed"://设置风速
                                        status = 1;
                                        fanSpeed = DuiToBLW(request.payload.speedLevel.value);
                                        if (fanSpeed < 1)
                                        {
                                            fanSpeed = 1;
                                        }
                                        else if (fanSpeed > 3)
                                        {
                                            fanSpeed = 3;
                                        }
                                        break;
                                    case "IncreaseWindSpeed"://调高风速
                                        status = 1;
                                        fanSpeed += DuiToBLW(request.payload.deltaSpeedLevel.value);
                                        if (fanSpeed > 3)
                                        {
                                            fanSpeed = 3;
                                        }
                                        break;
                                    case "DecreaseWindSpeed"://调低风速
                                        status = 1;
                                        fanSpeed -= DuiToBLW(request.payload.deltaSpeedLevel.value);
                                        if (fanSpeed < 1)
                                        {
                                            fanSpeed = 1;
                                        }
                                        break;
                                    case "SetMode"://设置模式
                                        status = 1;
                                        mode = ModeToInt(request.payload.mode.value);
                                        break;
                                    case "CancelMode"://取消模式
                                        break;
                                    case "Pause"://暂停
                                        status = 6;
                                        break;
                                    case "Continue"://继续
                                        status = 1;
                                        break;
                                    default:
                                        return Json(ReturnDUIError(request.header, "DEVICE_NOT_SUPPORT_FUNCTION", "设备不支持该操作"), JsonRequestBehavior.AllowGet);
                                }
                                if (hostModal.Modal.Type == DeviceType.Strip && hostModal.Modal.ModalAddress.Substring(6) == "000")//如果是000回路，则是调色，否则是调光
                                {
                                    HostModalManager.SetDevice(host, hostModal, brightness == 0 ? 2 : 1, brightness, 0, 0, 0, 0);
                                    //001回路R颜色
                                    hostModal = HostModalManager.GetByModalAddress(host.ID, hostModal.Modal.ModalAddress.Substring(0, 8) + "1");
                                    HostModalManager.SetDevice(host, hostModal, brightness == 0 ? 2 : 1, brightness, 0, 0, 0, 0);
                                    //002回路G颜色
                                    hostModal = HostModalManager.GetByModalAddress(host.ID, hostModal.Modal.ModalAddress.Substring(0, 8) + "2");
                                    HostModalManager.SetDevice(host, hostModal, brightness == 0 ? 2 : 1, brightness, 0, 0, 0, 0);
                                    //003回路B颜色
                                    hostModal = HostModalManager.GetByModalAddress(host.ID, hostModal.Modal.ModalAddress.Substring(0, 8) + "3");
                                    HostModalManager.SetDevice(host, hostModal, brightness == 0 ? 2 : 1, brightness, 0, 0, 0, 0);
                                }
                                else
                                {
                                    //对房间设备进行操作
                                    HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                                }
                                string action = "打开";
                                if (status == 2)
                                {
                                    action = "关闭";
                                }
                                else if (status == 6)
                                {
                                    action = "暂停";
                                }
                                string detail = string.Format("{0}客房{1}{2}({3})", action, host.RoomNumber, hostModal.Modal.Name, modalAddress);
                                SaveSystemLog(AuthorityID, "设备控制", detail, true, "DUI TV", host.SysHotel.ID);
                            }
                            //操作完成响应DUI
                            Domain.IoTDUIEntity.ControlResponse.ControlAppResponse response = new Domain.IoTDUIEntity.ControlResponse.ControlAppResponse
                            {
                                header = new Domain.IoTDUIEntity.Header
                                {
                                    @namespace = request.header.@namespace,
                                    name = request.header.name + "Response",
                                    messageId = request.header.messageId,
                                    payloadVersion = request.header.payloadVersion
                                },
                                payload = new Domain.IoTDUIEntity.ControlResponse.Payload { }
                            };
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    case "DUI.SmartHome.Query":
                        {
                            return Json(ReturnDUIError(request.header, "INVALIDATE_PARAMS", "namespace:" + request.header.@namespace), JsonRequestBehavior.AllowGet);
                        }
                    default:
                        return Json(ReturnDUIError(request.header, "INVALIDATE_PARAMS", "namespace:" + request.header.@namespace), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("处理DUI命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// Dui平台增量型转换
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private int DuiToBLW(string value)
        {
            switch (value.ToLower())
            {
                case "min"://最小
                    return 0;
                case "max"://最大
                    return 100;
                case "low"://低
                    return 1;
                case "mid"://中
                    return 2;
                case "high"://高
                    return 3;
                case "step":
                    return 1;
                default:
                    return Convert.ToInt16(value);
            }
        }
        /// <summary>
        /// 返回错误信息
        /// </summary>
        /// <param name="header"></param>
        /// <param name="errorName"></param>
        /// <returns></returns>
        private Domain.IoTDUIEntity.Error.ErrorResponse ReturnDUIError(Domain.IoTDUIEntity.Header header, string errorCode, string message)
        {
            Domain.IoTDUIEntity.Error.ErrorResponse err = new Domain.IoTDUIEntity.Error.ErrorResponse
            {
                header = new Domain.IoTDUIEntity.Header
                {
                    messageId = header.messageId,
                    @namespace = header.@namespace,
                    name = "ErrorResponse",
                    payloadVersion = header.payloadVersion
                },
                payload = new Domain.IoTDUIEntity.Error.Payload
                {
                    errorCode = errorCode,
                    message = message
                }
            };
            return err;
        }
        #endregion

        #region 华为大屏智能家居对接
        /// <summary>
        /// 华为设备获取技能
        /// </summary>
        /// <returns></returns>
        public ActionResult HuaWeiDiscoverDevices()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            //logger.Error(string.Format("收到华为大屏同步数据请求：{0}，来自：{1}", reqData, GetClientIP()));
            Domain.IoTHuaWeiEntity.SmartHomeContentInfoRsp rsp = new Domain.IoTHuaWeiEntity.SmartHomeContentInfoRsp();
            try
            {
                Domain.IoTHuaWeiEntity.SmartHomeContentInfoReq req = JsonConvert.DeserializeObject<Domain.IoTHuaWeiEntity.SmartHomeContentInfoReq>(reqData);//得到华为请求
                //var hosts = HostManager.LoadAll("1003").ToList();//指定酒店，同步设备技能
                var host = HostManager.GetByHuaWeiCUID(_huawei_cuid);//获取按配置的主机的技能
                List<Domain.IoTHuaWeiEntity.SmartHomeContentInfoItem> data = new List<Domain.IoTHuaWeiEntity.SmartHomeContentInfoItem>();
                if (host != null)//foreach (Host host in hosts)
                {
                    //获取需要控制的场景
                    List<Domain.IoTHuaWeiEntity.SmartHomeSceneRuleObjDef> sceneRuleList = new List<Domain.IoTHuaWeiEntity.SmartHomeSceneRuleObjDef>();
                    IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                    foreach (RoomTypeScene scene in sceneModals)
                    {
                        sceneRuleList.Add(new Domain.IoTHuaWeiEntity.SmartHomeSceneRuleObjDef
                        {
                            name = "SMARTHOME_SCENE_IFTTT",
                            value = scene.Name,
                            valueAlias = new string[] { }
                        });
                    }
                    //获取需要控制的设备
                    List<Domain.IoTHuaWeiEntity.SmartHomePayloadObjDef> payload = new List<Domain.IoTHuaWeiEntity.SmartHomePayloadObjDef>();
                    IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                    foreach (HostModal hostModal in hostModals)
                    {
                        Domain.IoTHuaWeiEntity.SmartHomePayloadObjDef playloadItem = new Domain.IoTHuaWeiEntity.SmartHomePayloadObjDef();
                        playloadItem.deviceType = hostModal.Modal.Name;//设备类型：默认回路名称
                        playloadItem.actionList = new string[] { "SMARTHOME_SWITCH_ON", "SMARTHOME_SWITCH_OFF" };//默认具有开和关意图
                        switch (hostModal.Modal.Type)
                        {
                            case DeviceType.Dimmer:
                            case DeviceType.Traic:
                            case DeviceType.PWMDimmer:
                            case DeviceType.PWMExpand:
                            case DeviceType.PBLED:
                            case DeviceType.LVout://弱电输出
                            case DeviceType.Strip://灯带调光
                            case DeviceType.PB20:
                            case DeviceType.PB20_LD:
                            case DeviceType.PB20_LS:
                                playloadItem.actionList = new string[] 
                                { 
                                    "SMARTHOME_SWITCH_ON",      //打开
                                    "SMARTHOME_SWITCH_OFF",     //关闭
                                    "SMARTHOME_TURN_BRIGHTER",  //调亮
                                    "SMARTHOME_TURN_DARKER",    //调暗
                                    "SMARTHOME_SET_BRIGHTNESS", //最亮
                                    "SMARTHOME_SET_DARKER"      //最暗
                                };
                                break;
                            case DeviceType.AirConditioner:
                                playloadItem.actionList = new string[] 
                                { 
                                    "SMARTHOME_SWITCH_ON",
                                    "SMARTHOME_SWITCH_OFF",
                                    "SMARTHOME_SET_MODE",
                                    "SMARTHOME_INC_TEMP",
                                    "SMARTHOME_DEC_TEMPERATURE",
                                    "SMARTHOME_SET_TEMP",
                                    "SMARTHOME_INC_WINDSPEED",
                                    "SMARTHOME_DEC_WINDSPEED",
                                    "SMARTHOME_SET_WINDSPEED"
                                };
                                break;
                            case DeviceType.Curtain:
                                playloadItem.actionList = new string[] { "SMARTHOME_SWITCH_ON", "SMARTHOME_SWITCH_OFF", "SMARTHOME_PAUSE" };
                                break;
                            default:
                                playloadItem.actionList = new string[] { "SMARTHOME_SWITCH_ON", "SMARTHOME_SWITCH_OFF" };
                                break;
                        }
                        List<Domain.IoTHuaWeiEntity.SmartHomeDeviceObjDef> deviceList = new List<Domain.IoTHuaWeiEntity.SmartHomeDeviceObjDef>();
                        deviceList.Add(new Domain.IoTHuaWeiEntity.SmartHomeDeviceObjDef()
                        {
                            name = "smarthome.devicename",
                            value = hostModal.Modal.Name,
                            valueAlias = new string[] { }
                        });
                        playloadItem.deviceList = deviceList;
                        payload.Add(playloadItem);
                    }
                    //组织给华为同步的数据
                    data.Add(new Domain.IoTHuaWeiEntity.SmartHomeContentInfoItem()
                    {
                        countryCode = "CN",
                        deviceType = "3",
                        language = "zh-CN",
                        vtId = _huawei_vtId,
                        payload = payload,
                        sceneRuleList = sceneRuleList
                    });
                    //logger.Error(string.Format("{3}(酒店：{0}，房号：{1})本次获取设备数量：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, (payload.Count + sceneRuleList.Count).ToString(), platformName));
                }
                rsp.data = data;
                rsp.pagination = new Domain.IoTHuaWeiEntity.PaginationRsp() { next = "0", total = data.Count };
                rsp.expectedNextTimestamp = "0";
                rsp.errorCode = "0";
                rsp.errorMessage = "OK";
                return new ContentResult
                {
                    Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(rsp),
                    ContentType = "application/json"
                };
            }
            catch (Exception ex)
            {
                rsp.errorCode = "32";
                rsp.errorMessage = ex.Message;
                logger.Error(string.Format("华为大屏同步数据请求异常，数据：{0}，异常：{1},来自：{2}", reqData, ex.ToString(), GetClientIP()));
                return Json(rsp);
            }
        }
        /// <summary>
        /// 华为设备意图请求控制
        /// </summary>
        /// <returns></returns>
        public ActionResult HuaWeiControlDevices()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            string reqDataMsg = string.Format("收到华为大屏控制设备请求：{0}，来自：{1}", reqData, GetClientIP());
            reqData = reqData.Replace("smarthome.devicetype", "smarthomeDevicetype")
                .Replace("smarthome.devicename", "smarthomeDevicename")
                .Replace("smarthome.rulename", "smarthomeRulename")
                .Replace("smarthome.room", "smarthomeRoom")
                .Replace("smarthome.charactervalue", "smarthomeCharactervalue")
                .Replace("smarthome.alldevice", "smarthomeAlldevice")
                .Replace("smarthome.target", "smarthomeTarget")
                .Replace("smarthome.action", "smarthomeAction")
                .Replace("null", "");
            Domain.IoTHuaWeiEntity.SmartHomeIntentRsp rsp = new Domain.IoTHuaWeiEntity.SmartHomeIntentRsp();
            string platformName = "华为大屏";
            try
            {
                Domain.IoTHuaWeiEntity.SmartHomeIntentReq req = JsonConvert.DeserializeObject<Domain.IoTHuaWeiEntity.SmartHomeIntentReq>(reqData);//得到华为意图请求
                rsp.version = req.version;
                rsp.reply = new Domain.IoTHuaWeiEntity.Reply() { isEndSession = true };
                if (string.IsNullOrEmpty(req.endpoint.device.deviceId))
                {
                    rsp.errorCode = "1";
                    rsp.errorMessage = platformName + "deviceId(" + req.endpoint.device.deviceId + ")无效";
                    logger.Error(rsp.errorMessage);
                    //logger.Error(reqDataMsg);
                    return Json(rsp);
                }
                Host host = HostManager.GetByHuaWeiCUID(req.endpoint.device.deviceId);//根据deviceId获取对应RCU主机             
                if (host == null)
                {
                    rsp.errorCode = "101";
                    rsp.errorMessage = platformName + "deviceId(" + req.endpoint.device.deviceId + ")尚未绑定客房主机";
                    //logger.Error(rsp.errorMessage);
                    //logger.Error(reqDataMsg);
                    return Json(rsp);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    rsp.errorCode = "101";
                    rsp.errorMessage = "当前访问酒店(" + host.SysHotel.Name + ")已过期";
                    //logger.Error(rsp.errorMessage);
                    //logger.Error(reqDataMsg);
                    return Json(rsp);
                }
                //if (!CheckGetPower(host.ID))
                //{
                //    rsp.errorCode = "101";
                //    rsp.errorMessage = "酒店(" + host.SysHotel.Name + ")客房(" + host.RoomNumber + ")：非取电状态，不可控制！";
                //    logger.Error(rsp.errorMessage);
                //    return Json(rsp);
                //}
                if (req.inquire.intent.name.StartsWith("SMARTHOME_SCENE"))//场景控制
                {
                    string modalName = "";
                    if (req.inquire.intent.slots.smarthomeRulename.values != null)
                    {
                        modalName = req.inquire.intent.slots.smarthomeRulename.values[0].real;
                    }
                    if (string.IsNullOrEmpty(modalName))
                    {
                        rsp.errorCode = "1";
                        rsp.errorMessage = "需要控制的场景名称不能为空";
                        logger.Error(rsp.errorMessage);
                        //logger.Error(reqDataMsg);
                        return Json(rsp);
                    }
                    var scene = RoomTypeSceneManager.Get(host.RoomType, modalName);
                    if (scene == null)
                    {
                        rsp.errorCode = "101";
                        rsp.errorMessage = string.Format("{3}(酒店：{0}，房号：{1})未找到对应的控制场景，名称：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalName, platformName);
                        logger.Error(rsp.errorMessage);
                        //logger.Error(reqDataMsg);
                        return Json(rsp);
                    }
                    LightControlManager.ApplyScene(host, scene);
                    SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, platformName, host.SysHotel.ID);
                }
                else
                {
                    string prefix = "", modalName = "";//设备名称：优先取type，然后取name
                    if (req.inquire.intent.slots.smarthomeAlldevice != null && req.inquire.intent.slots.smarthomeAlldevice.values != null)
                    {
                        prefix = req.inquire.intent.slots.smarthomeAlldevice.values[0].real;//所有设备
                    }
                    if (prefix == "" && req.inquire.intent.slots.smarthomeRoom != null && req.inquire.intent.slots.smarthomeRoom.values != null)
                    {
                        prefix = req.inquire.intent.slots.smarthomeRoom.values[0].real; //设备所在位置
                    }
                    if (req.inquire.intent.slots.smarthomeDevicetype.values != null)
                    {
                        modalName = req.inquire.intent.slots.smarthomeDevicetype.values[0].real;//设备类型
                    }
                    else if (req.inquire.intent.slots.smarthomeDevicename.values != null)
                    {
                        modalName = req.inquire.intent.slots.smarthomeDevicename.values[0].real;//设备名称
                    }
                    else if (req.inquire.intent.slots.smarthomeTarget.values != null)
                    {
                        modalName = req.inquire.intent.slots.smarthomeTarget.values[0].real;//服务或客需名称
                    }
                    modalName = prefix + modalName;//前缀+名称，如所有灯
                    if (string.IsNullOrEmpty(modalName))
                    {
                        rsp.errorCode = "1";
                        rsp.errorMessage = "需要控制的设备或服务名称不能为空";
                        logger.Error(rsp.errorMessage);
                        //logger.Error(reqDataMsg);
                        return Json(rsp);
                    }
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    switch (modalName)
                    {
                        case "所有灯":
                        case "总控":
                            var hostModals = HostModalManager.LoadAllLight(host.ID);
                            foreach (var hostModal1 in hostModals)
                            {
                                int status1 = hostModal1.Status;
                                int brightness1 = hostModal1.Brightness;
                                int temperature1 = hostModal1.SettingTemp;
                                int fanSpeed1 = hostModal1.FanSpeed;
                                int mode1 = hostModal1.Mode;
                                int valve1 = hostModal1.Valve;
                                switch (req.inquire.intent.name)
                                {
                                    case "SMARTHOME_SWITCH_ON":
                                        status1 = 1;
                                        brightness1 = 100;
                                        break;
                                    case "SMARTHOME_SWITCH_OFF":
                                        status1 = 2;
                                        brightness1 = 0;
                                        break;
                                    default:
                                        rsp.errorCode = "31";
                                        rsp.errorMessage = "不支持或尚未同步此意图：" + req.inquire.intent.name;
                                        logger.Error(rsp.errorMessage);
                                        //logger.Error(reqDataMsg);
                                        return Json(rsp);
                                }
                                HostModalManager.SetDevice(host, hostModal1, status1, brightness1, temperature1, fanSpeed1, mode1, valve1);//对房间设备进行操作
                            }
                            if (req.inquire.utterance != null && req.inquire.utterance.original != null)
                            {
                                sb.Append(req.inquire.utterance.original);
                            }
                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                            break;
                        default:
                            var hostModal = HostModalManager.GetByModalName(host.ID, modalName);//设备控制
                            if (hostModal == null)
                            {
                                rsp.errorCode = "101";
                                rsp.errorMessage = string.Format("{3}(酒店：{0}，房号：{1})未找到对应的控制设备或服务，名称：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalName, platformName);
                                logger.Error(rsp.errorMessage);
                                //logger.Error(reqDataMsg);
                                return Json(rsp);
                            }
                            sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：");
                            int status = hostModal.Status;
                            int brightness = hostModal.Brightness;
                            int temperature = hostModal.SettingTemp;
                            int fanSpeed = hostModal.FanSpeed;
                            int mode = hostModal.Mode;
                            int valve = hostModal.Valve;
                            switch (req.inquire.intent.name)
                            {
                                case "SMARTHOME_SWITCH_ON":
                                case "SMARTHOME_SET_BRIGHTNESS"://最亮
                                    status = 1;
                                    brightness = 100;
                                    sb.Append("打开");
                                    break;
                                case "SMARTHOME_SET_BRIGHTER"://最暗
                                    status = 1;
                                    brightness = 10;
                                    sb.Append("打开（最暗）");
                                    break;
                                case "SMARTHOME_SWITCH_OFF":
                                    status = 2;
                                    brightness = 0;
                                    sb.Append("关闭");
                                    break;
                                case "SMARTHOME_TURN_BRIGHTER":
                                    status = 1;
                                    brightness += 10;
                                    if (brightness > 100)
                                    {
                                        brightness = 100;
                                    }
                                    sb.Append("调亮");
                                    break;
                                case "SMARTHOME_TURN_DARKER":
                                    status = 1;
                                    brightness -= 10;
                                    if (brightness < 0)
                                    {
                                        brightness = 0;
                                        status = 2;
                                    }
                                    sb.Append("调暗");
                                    break;
                                case "SMARTHOME_PAUSE":
                                    status = 6;
                                    sb.Append("暂停");
                                    break;
                                case "SMARTHOME_SET_MODE":
                                    status = 1;
                                    switch (req.inquire.intent.slots.smarthomeCharactervalue.values[0].real)
                                    {
                                        case "制冷":
                                            mode = 1;
                                            break;
                                        case "制热":
                                            mode = 2;
                                            break;
                                        default://送风
                                            mode = 3;
                                            break;
                                    }
                                    sb.Append("设定模式：" + req.inquire.intent.slots.smarthomeCharactervalue.values[0].real);
                                    break;
                                case "SMARTHOME_INC_TEMP":
                                    status = 1;
                                    temperature++;
                                    if (temperature < 16)
                                    {
                                        temperature = 16;
                                    }
                                    else if (temperature > 32)
                                    {
                                        temperature = 32;
                                    }
                                    sb.Append("调高温度1°");
                                    break;
                                case "SMARTHOME_DEC_TEMPERATURE":
                                    status = 1;
                                    temperature--;
                                    if (temperature < 16)
                                    {
                                        temperature = 16;
                                    }
                                    else if (temperature > 32)
                                    {
                                        temperature = 32;
                                    }
                                    sb.Append("调低温度1°");
                                    break;
                                case "SMARTHOME_SET_TEMP":
                                    status = 1;
                                    temperature = Convert.ToInt16(req.inquire.intent.slots.smarthomeCharactervalue.values[0].real);
                                    if (temperature < 16)
                                    {
                                        temperature = 16;
                                    }
                                    else if (temperature > 32)
                                    {
                                        temperature = 32;
                                    }
                                    sb.Append("设温：" + temperature);
                                    break;
                                case "SMARTHOME_INC_WINDSPEED":
                                    status = 1;
                                    fanSpeed++;
                                    if (fanSpeed > 3)
                                    {
                                        fanSpeed = 3;
                                    }
                                    sb.Append("调高风速");
                                    break;
                                case "SMARTHOME_DEC_WINDSPEED":
                                    status = 1;
                                    fanSpeed--;
                                    if (fanSpeed > 3)
                                    {
                                        fanSpeed = 3;
                                    }
                                    sb.Append("调低风速");
                                    break;
                                case "SMARTHOME_SET_WINDSPEED":
                                    status = 1;
                                    switch (req.inquire.intent.slots.smarthomeCharactervalue.values[0].real)
                                    {
                                        case "低风":
                                            fanSpeed = 1;
                                            break;
                                        case "中风":
                                            fanSpeed = 2;
                                            break;
                                        case "高风":
                                            fanSpeed = 3;
                                            break;
                                        default://自动风
                                            fanSpeed = 0;
                                            break;
                                    }
                                    sb.Append("设定风速：" + fanSpeed);
                                    break;
                                case "SMARTHOME_SERVICE":
                                case "SMARTHOME_CUSTOMERDEMAND":
                                    string action = req.inquire.intent.slots.smarthomeAction.values[0].real;
                                    status = action == "打开" ? 1 : 2;
                                    sb.Append("控制服务(" + modalName + ")：" + action);
                                    break;
                                default:
                                    rsp.errorCode = "31";
                                    rsp.errorMessage = "不支持或尚未同步此意图：" + req.inquire.intent.name;
                                    logger.Error(rsp.errorMessage);
                                    //logger.Error(reqDataMsg);
                                    return Json(rsp);
                            }
                            if (req.inquire.utterance != null && req.inquire.utterance.original != null)
                            {
                                sb.Append("，原意：" + req.inquire.utterance.original);
                            }
                            //对房间设备进行操作
                            HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                            break;
                    }
                }
                rsp.errorCode = "0";
                rsp.errorMessage = "OK";
                return Json(rsp);
            }
            catch (Exception ex)
            {
                rsp.errorCode = "32";
                rsp.errorMessage = ex.Message;
                logger.Error("华为大屏控制设备或服务异常：" + ex.ToString());
                logger.Error(reqDataMsg);
                return Json(rsp);
            }
        }

        #endregion

        #region 飞尔智能（科大讯飞）对接
        /// <summary>
        /// 飞尔智能（科大讯飞）对接
        /// </summary>
        /// <returns></returns>
        public ActionResult FeiEr()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            try
            {
                Domain.IoTFerErEntity.Request request = JsonConvert.DeserializeObject<Domain.IoTFerErEntity.Request>(reqData);//得到飞尔请求
                //if (string.IsNullOrEmpty(request.payload.cuid))
                //{
                //    logger.Error("第三方语音设备cuid不能为空：" + reqData + "，来自：" + GetClientIP());
                //    return Json(ReturnXiaoDuError(request.header, "UnexpectedInformationReceivedError"), JsonRequestBehavior.AllowGet);
                //}
                //string platformName = "小度音箱";
                //Host host = null;
                //if (request.header.@namespace.StartsWith("X2BOS"))
                //{
                //    platformName = "TCL电视";
                //    host = HostManager.GetByTCLCUID(request.payload.cuid);
                //}
                //else
                //{
                //    host = HostManager.GetByXiaoDuCUID(request.payload.cuid);//根据小度音箱序列号获取对应RCU主机  
                //}
                //if (host == null)
                //{
                //    logger.Error(platformName + "cuid(" + request.payload.cuid + ")尚未绑定客房主机");
                //    return Json(ReturnXiaoDuError(request.header, "TargetHardwareMalfunctionError"), JsonRequestBehavior.AllowGet);//"小度音箱(" + request.payload.cuid + ")尚未绑定客房主机"
                //}
                //if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                //{
                //    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期");
                return Json("", JsonRequestBehavior.AllowGet);
                //}
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("处理飞尔智能命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 岚正播放盒语音对接
        /// <summary>
        /// 岚正播放盒语音对接
        /// </summary>
        /// <returns></returns>
        public ActionResult LZ()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            try
            {
                Domain.IoTLZEntity.DiscoverAppliancesRequest request = JsonConvert.DeserializeObject<Domain.IoTLZEntity.DiscoverAppliancesRequest>(reqData);//岚正播放盒语音对接
                string platformName = "岚正播放盒";
                if (string.IsNullOrEmpty(request.payload.cuid))
                {
                    logger.Error(platformName + "cuid不能为空：" + reqData + "，来自：" + GetClientIP());
                    return Json(ReturnLZError(request.header, "UnexpectedInformationReceivedError"), JsonRequestBehavior.AllowGet);
                }
                Host host = HostManager.GetByTCLCUID(request.payload.cuid);//根据播放盒序列号获取对应RCU主机
                if (host == null)
                {
                    logger.Error(platformName + "cuid(" + request.payload.cuid + ")尚未绑定客房主机");
                    return Json(ReturnLZError(request.header, "TargetHardwareMalfunctionError"), JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期");
                    return Json(ReturnLZError(request.header, "ExpiredAccessTokenError"), JsonRequestBehavior.AllowGet);
                }
                switch (request.header.@namespace)
                {
                    case "LZOS.Discovery"://发现设备
                        {
                            List<Domain.IoTLZEntity.DiscoveredAppliances> appliances = new List<Domain.IoTLZEntity.DiscoveredAppliances>();
                            //获取需要控制设备的分组信息
                            List<Domain.IoTLZEntity.DiscoveredGroups> groups = new List<Domain.IoTLZEntity.DiscoveredGroups>();
                            List<string> applianceIds = new List<string>();
                            //获取需要控制的场景
                            IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                            foreach (RoomTypeScene scene in sceneModals)
                            {
                                string aliasName = string.IsNullOrEmpty(scene.AliasName) ? scene.Name : scene.AliasName;//获取别名
                                appliances.Add(new Domain.IoTLZEntity.DiscoveredAppliances
                                {
                                    actions = new List<string> { "turnOn" },
                                    applianceTypes = new List<string> { "SCENE_TRIGGER" },
                                    additionalApplianceDetails = new Dictionary<string, string>() { { "SCENE", "SCENE" } },
                                    applianceId = scene.ID + "&" + "SCENE_TRIGGER",
                                    friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + scene.Name,
                                    friendlyName = scene.Name,
                                    nicknames = new List<string>(aliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)),
                                    manufacturerName = "宝来威(Boonlive)",
                                    modelName = Common.Tools.GetDescription(scene.Type),
                                    version = "V1",
                                    isReachable = true
                                });
                                applianceIds.Add(scene.ID + "&" + "SCENE_TRIGGER");
                            }
                            //场景分组
                            groups.Add(new Domain.IoTLZEntity.DiscoveredGroups
                            {
                                groupId = "1",
                                groupName = "场景",
                                applianceIds = applianceIds,
                                groupNotes = "Boonlive-" + host.SysHotel.Name + "(" + host.RoomNumber + ")" + "场景分组",
                                additionalGroupDetails = new Dictionary<string, string>()
                            });
                            //获取需要控制的设备信息
                            IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                            applianceIds = new List<string>();
                            foreach (HostModal hostModal in hostModals)
                            {
                                List<string> applianceTypes = new List<string>();
                                List<string> actions = new List<string>();
                                switch (hostModal.Modal.Type)
                                {
                                    case DeviceType.Dimmer:
                                    case DeviceType.Traic:
                                    case DeviceType.PWMDimmer:
                                    case DeviceType.PWMExpand:
                                    case DeviceType.PBLED:
                                    case DeviceType.LVout://弱电输出
                                    case DeviceType.Strip://灯带调光
                                    case DeviceType.PB20:
                                    case DeviceType.PB20_LD:
                                    case DeviceType.PB20_LS:
                                        applianceTypes.Add("LIGHT");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setBrightnessPercentage");
                                        actions.Add("incrementBrightnessPercentage");
                                        actions.Add("decrementBrightnessPercentage");
                                        break;
                                    case DeviceType.AirConditioner:
                                        applianceTypes.Add("AIR_CONDITION");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setTemperature");
                                        actions.Add("incrementTemperature");
                                        actions.Add("decrementTemperature");
                                        actions.Add("setFanSpeed");
                                        actions.Add("incrementFanSpeed");
                                        actions.Add("decrementFanSpeed");
                                        actions.Add("setMode");
                                        break;
                                    case DeviceType.Curtain:
                                        if (hostModal.Modal.Name.IndexOf("窗帘") > -1)
                                        {
                                            applianceTypes.Add("CURTAIN");//窗帘
                                        }
                                        else if (hostModal.Modal.Name.IndexOf("窗纱") > -1)
                                        {
                                            applianceTypes.Add("CURT_SIMP");//窗纱
                                        }
                                        else
                                        {
                                            applianceTypes.Add("SWITCH");//卷帘、天幕等
                                        }
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("pause");
                                        actions.Add("continue");
                                        break;
                                    case DeviceType.TV:
                                        applianceTypes.Add("TV_SET");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setTVChannel");
                                        actions.Add("decrementTVChannel");
                                        actions.Add("incrementTVChannel");
                                        actions.Add("returnTVChannel");
                                        actions.Add("setVolume");
                                        actions.Add("setVolumeMute");
                                        actions.Add("incrementVolume");
                                        actions.Add("decrementVolume");
                                        actions.Add("setDirection");
                                        break;
                                    case DeviceType.Music:
                                        applianceTypes.Add("TV_SET");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setVolume");
                                        actions.Add("incrementVolume");
                                        actions.Add("decrementVolume");
                                        actions.Add("setVolumeMute");
                                        break;
                                    default:
                                        if (hostModal.Modal.Name.IndexOf("灯") > -1 ||
                                            hostModal.Modal.EnglishName.ToLower().IndexOf("light") > -1 ||
                                            hostModal.Modal.TWName.IndexOf("燈") > -1)
                                        {
                                            applianceTypes.Add("LIGHT");
                                        }
                                        else
                                        {
                                            applianceTypes.Add("SWITCH");
                                        }
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        break;
                                }
                                appliances.Add(new Domain.IoTLZEntity.DiscoveredAppliances
                                {
                                    actions = actions,
                                    applianceTypes = applianceTypes,
                                    applianceId = hostModal.Modal.ModalAddress + "&" + applianceTypes[0],
                                    additionalApplianceDetails = new Dictionary<string, string>() { { "TYPE", Common.Tools.GetDescription(hostModal.Modal.Type) } },
                                    friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + hostModal.Modal.Name,
                                    friendlyName = hostModal.Modal.Name,
                                    nicknames = new List<string> { hostModal.Modal.Name },
                                    manufacturerName = "宝来威(Boonlive)",
                                    modelName = Common.Tools.GetDescription(hostModal.Modal.Type),
                                    version = "V1",
                                    isReachable = true
                                });
                                applianceIds.Add(hostModal.Modal.ModalAddress + "&" + applianceTypes[0]);
                            }
                            //房间分组
                            groups.Add(new Domain.IoTLZEntity.DiscoveredGroups
                            {
                                groupId = "1",
                                groupName = "房间",
                                applianceIds = applianceIds,
                                groupNotes = "Boonlive-" + host.SysHotel.Name + "(" + host.RoomNumber + ")" + "房间分组",
                                additionalGroupDetails = new Dictionary<string, string>() { }
                            });
                            //找到可控场景和设备，响应小度DuerOS
                            Domain.IoTLZEntity.DiscoverAppliancesResponse response = new Domain.IoTLZEntity.DiscoverAppliancesResponse
                            {
                                header = new Domain.IoTLZEntity.Header
                                {
                                    name = "DiscoverAppliancesResponse",
                                    @namespace = request.header.@namespace,
                                },
                                payload = new Domain.IoTLZEntity.Payload
                                {
                                    discoveredAppliances = appliances,
                                    discoveredGroups = groups
                                }
                            };
                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})本次获取设备数量：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, response.payload.discoveredAppliances.Count.ToString(), platformName));
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    case "LZOS.Control"://控制设备 
                        {
                            if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                            {
                                //logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");
                                return Json(ReturnLZError(request.header, "TargetOfflineError"), JsonRequestBehavior.AllowGet);//当技能检测到目标设备没有连接到设备云或者设备云不在线时，会给DuerOS发送TargetOfflineError消息。
                            }
                            if (!CheckGetPower(host))
                            {
                                //logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");
                                return Json(ReturnLZError(request.header, "UnsupportedOperationError"), JsonRequestBehavior.AllowGet);
                            }
                            string[] applianceIds = request.payload.appliance.applianceId.Split('&');
                            if (applianceIds.Length < 2)
                            {
                                logger.Error(platformName + "applianceId参数有误：" + request.payload.appliance.applianceId);
                                return Json(ReturnLZError(request.header, "UnexpectedInformationReceivedError"), JsonRequestBehavior.AllowGet);
                            }
                            string modalAddress = applianceIds[0];//设备地址或场景ID
                            string applianceTypes = applianceIds[1];//设备类型
                            string confirmationName = "TurnOnConfirmation";
                            Domain.IoTLZEntity.Payload payload = new Domain.IoTLZEntity.Payload();
                            List<Domain.IoTLZEntity.Attributes> attributes = new List<Domain.IoTLZEntity.Attributes>();
                            switch (applianceTypes)
                            {
                                case "SCENE_TRIGGER"://场景控制
                                case "ACTIVITY_TRIGGER":
                                    {
                                        var scene = RoomTypeSceneManager.Get(int.Parse(modalAddress));
                                        if (scene == null)
                                        {
                                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的场景，ID：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress, platformName));
                                            return Json(ReturnLZError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                        }
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "name", value = scene.Name, scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "turnOnState", value = "ON", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        LightControlManager.ApplyScene(host, scene);
                                        SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, platformName, host.SysHotel.ID);
                                    }
                                    break;
                                default:
                                    {
                                        var hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);//设备控制
                                        if (hostModal == null)
                                        {
                                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的回路，Address：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress, platformName));
                                            return Json(ReturnLZError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                        }
                                        Domain.IoTLZEntity.PreviousState previousState = new Domain.IoTLZEntity.PreviousState();
                                        previousState.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(hostModal.Brightness) };//原来的亮度
                                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                        sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：");
                                        int status = hostModal.Status;
                                        int brightness = hostModal.Brightness;
                                        int temperature = hostModal.SettingTemp;
                                        int fanSpeed = hostModal.FanSpeed;
                                        int mode = hostModal.Mode;
                                        int valve = hostModal.Valve;
                                        switch (request.header.name)
                                        {
                                            case "TurnOnRequest"://打开
                                                confirmationName = "TurnOnConfirmation";
                                                status = 1;
                                                brightness = 100;
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("状态：打开");
                                                break;
                                            case "TurnOffRequest"://关闭                   
                                                confirmationName = "TurnOffConfirmation";
                                                status = 2;
                                                brightness = 0;
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("状态：关闭");
                                                break;
                                            case "SetBrightnessPercentageRequest"://设置亮度
                                                confirmationName = "SetBrightnessPercentageConfirmation";
                                                status = 1;
                                                brightness = Convert.ToInt16(request.payload.brightness.value);
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("亮度：" + brightness);
                                                break;
                                            case "IncrementBrightnessPercentageRequest"://调亮
                                                confirmationName = "IncrementBrightnessPercentageConfirmation";
                                                status = 1;
                                                brightness += Convert.ToInt16(request.payload.deltaPercentage.value);
                                                if (brightness > 100)
                                                {
                                                    brightness = 100;
                                                }
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("调亮：" + request.payload.deltaPercentage.value);
                                                break;
                                            case "DecrementBrightnessPercentageRequest"://调暗
                                                confirmationName = "DecrementBrightnessPercentageConfirmation";
                                                status = 1;
                                                brightness -= Convert.ToInt16(request.payload.deltaPercentage.value);
                                                if (brightness < 0)
                                                {
                                                    brightness = 0;
                                                    status = 2;
                                                }
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("调暗：" + request.payload.deltaPercentage.value);
                                                break;
                                            case "SetTemperatureRequest"://设置温度
                                                previousState.temperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                confirmationName = "SetTemperatureConfirmation";
                                                status = 1;
                                                temperature = XiaoDuToBLW(request.payload.targetTemperature.value.ToString());
                                                if (temperature < 16)
                                                {
                                                    temperature = 16;
                                                }
                                                else if (temperature > 32)
                                                {
                                                    temperature = 32;
                                                }
                                                payload.targetTemperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                payload.previousState = previousState;
                                                sb.Append("设温：" + temperature);
                                                break;
                                            case "IncrementTemperatureRequest"://调高温度
                                                previousState.temperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                confirmationName = "IncrementTemperatureConfirmation";
                                                status = 1;
                                                temperature += Convert.ToInt16(request.payload.deltaValue.value);
                                                if (temperature > 32)
                                                {
                                                    temperature = 32;
                                                }
                                                payload.targetTemperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                payload.previousState = previousState;
                                                sb.Append("调高温度：" + request.payload.deltaValue.value);
                                                break;
                                            case "DecrementTemperatureRequest"://调低温度
                                                previousState.temperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                confirmationName = "DecrementTemperatureConfirmation";
                                                status = 1;
                                                temperature -= Convert.ToInt16(request.payload.deltaValue.value);
                                                if (temperature < 16)
                                                {
                                                    temperature = 16;
                                                }
                                                payload.targetTemperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                payload.previousState = previousState;
                                                sb.Append("调低温度：" + request.payload.deltaValue.value);
                                                break;
                                            case "SetFanSpeedRequest"://设置风速
                                                previousState.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                confirmationName = "SetFanSpeedConfirmation";
                                                status = 1;
                                                if (request.payload.fanSpeed.level != null & !string.IsNullOrEmpty(request.payload.fanSpeed.level))
                                                {
                                                    switch (request.payload.fanSpeed.level.ToLower())
                                                    {
                                                        case "high":
                                                        case "max":
                                                            fanSpeed = 3;
                                                            break;
                                                        case "middle":
                                                            fanSpeed = 2;
                                                            break;
                                                        case "auto":
                                                            fanSpeed = 0;
                                                            break;
                                                        default:
                                                            fanSpeed = 1;
                                                            break;
                                                    }
                                                    sb.Append("设置风速：" + request.payload.fanSpeed.level);
                                                }
                                                else
                                                {
                                                    fanSpeed = Convert.ToInt16(request.payload.fanSpeed.value);
                                                    if (fanSpeed < 1)
                                                    {
                                                        fanSpeed = 1;
                                                    }
                                                    else if (fanSpeed > 3)
                                                    {
                                                        fanSpeed = 3;
                                                    }
                                                    sb.Append("设置风速：" + fanSpeed);
                                                }
                                                payload.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                payload.previousState = previousState;
                                                break;
                                            case "IncrementFanSpeedRequest"://调高风速
                                                previousState.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                confirmationName = "IncrementFanSpeedConfirmation";
                                                status = 1;
                                                fanSpeed += Convert.ToInt16(request.payload.deltaValue.value);
                                                if (fanSpeed > 3)
                                                {
                                                    fanSpeed = 3;
                                                }
                                                payload.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                payload.previousState = previousState;
                                                sb.Append("调高风速：" + request.payload.deltaValue.value);
                                                break;
                                            case "DecrementFanSpeedRequest"://调低风速
                                                previousState.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                confirmationName = "DecrementFanSpeedConfirmation";
                                                status = 1;
                                                fanSpeed -= Convert.ToInt16(request.payload.deltaValue.value);
                                                if (fanSpeed < 1)
                                                {
                                                    fanSpeed = 1;
                                                }
                                                payload.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                payload.previousState = previousState;
                                                sb.Append("调低风速：" + request.payload.deltaValue.value);
                                                break;
                                            case "SetModeRequest"://设置模式
                                                previousState.mode = new Domain.IoTLZEntity.Mode() { value = ModeToString(mode) };
                                                confirmationName = "SetModeConfirmation";
                                                status = 1;
                                                mode = ModeToInt(request.payload.mode.value);
                                                payload.mode = new Domain.IoTLZEntity.Mode() { deviceType = request.payload.mode.deviceType, value = request.payload.mode.value };
                                                payload.previousState = previousState;
                                                sb.Append("模式：" + request.payload.mode.value);
                                                break;
                                            case "PauseRequest"://暂停
                                                confirmationName = "PauseConfirmation";
                                                status = 6;
                                                sb.Append("状态：暂停");
                                                break;
                                            case "ContinueRequest"://继续
                                                confirmationName = "ContinueConfirmation";
                                                status = 1;
                                                sb.Append("状态：继续");
                                                break;
                                            case "SetTVChannelRequest"://电视跳转频道
                                                confirmationName = "SetTVChannelConfirmation";
                                                status = 4;
                                                int channelNumber = 0;
                                                if (int.TryParse(request.payload.deltaValue.value, out channelNumber))
                                                {
                                                    valve = channelNumber;
                                                }
                                                else
                                                {
                                                    var channel = RoomTypeChannelsManager.LoadAll(host.RoomType.ID).Where(r => r.Name.Contains(request.payload.deltaValue.value)).FirstOrDefault();
                                                    if (channel != null)
                                                    {
                                                        valve = channel.Code;
                                                    }
                                                    else
                                                    {
                                                        logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的电视频道：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, request.payload.deltaValue.value, platformName));
                                                        return Json(ReturnLZError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                                    }
                                                }
                                                sb.Append("调整频道至：" + valve);
                                                break;
                                            case "IncrementTVChannelRequest"://电视下一频道
                                                confirmationName = "IncrementTVChannelConfirmation";
                                                status = 1;
                                                mode = 5;
                                                sb.Append("频道：加");
                                                break;
                                            case "DecrementTVChannelRequest"://电视上一频道
                                                confirmationName = "DecrementTVChannelConfirmation";
                                                status = 1;
                                                mode = 6;
                                                sb.Append("频道：减");
                                                break;
                                            case "ReturnTVChannelRequest"://返回上一个观看频道
                                                confirmationName = "ReturnTVChannelConfirmation";
                                                status = 1;
                                                mode = 15;
                                                sb.Append("电视：回看");
                                                break;
                                            case "IncrementVolumeRequest"://增大音量
                                                confirmationName = "IncrementVolumeConfirmation";
                                                status = 1;
                                                mode = 3;
                                                sb.Append("音量：加");
                                                break;
                                            case "DecrementVolumeRequest"://减小音量
                                                confirmationName = "DecrementVolumeConfirmation";
                                                status = 1;
                                                mode = 4;
                                                sb.Append("音量：减");
                                                break;
                                            //case "SetVolumeRequest"://设置音量
                                            //    confirmationName = "SetVolumeConfirmation";
                                            //    break;
                                            case "SetVolumeMuteRequest"://设置静音
                                                confirmationName = "SetVolumeMuteConfirmation";
                                                status = 1;
                                                mode = 1;
                                                sb.Append("音量：静音");
                                                break;
                                            default:
                                                return Json(ReturnLZError(request.header, "UnsupportedTargetError"), JsonRequestBehavior.AllowGet);
                                        }
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "name", value = hostModal.Modal.Name, scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "turnOnState", value = status == 1 ? "ON" : "OFF", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        //对房间设备进行操作
                                        HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                                        SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                                    }
                                    break;
                            }
                            payload.attributes = attributes;
                            //操作完成响应小度
                            Domain.IoTLZEntity.ControlAppliancesResponse response = new Domain.IoTLZEntity.ControlAppliancesResponse
                            {
                                header = new Domain.IoTLZEntity.Header
                                {
                                    @namespace = request.header.@namespace,
                                    name = confirmationName
                                },
                                payload = payload
                            };
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    default:
                        return Json(ReturnLZError(request.header, "UnsupportedTargetError"), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("处理岚正播放盒命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 返回错误信息
        /// </summary>
        /// <param name="header"></param>
        /// <param name="errorName"></param>
        /// <returns></returns>
        private Domain.IoTLZEntity.ErrorResponse ReturnLZError(Domain.IoTLZEntity.Header header, string errorName)
        {
            Domain.IoTLZEntity.ErrorResponse err = new Domain.IoTLZEntity.ErrorResponse
            {
                header = new Domain.IoTLZEntity.Header
                {
                    @namespace = header.@namespace,
                    name = errorName
                },
                payload = new Domain.IoTLZEntity.Payload { }
            };
            return err;
        }
        #endregion

        #region 若琪智能语音对接

        #endregion

        #region 狗尾草（小白）智能语音对接

        #endregion

        #region 小米小爱语音对接
        /*
         * clientId: C485849C
         * clientSecret: 8C9FB-6D854-CE2A0-16DAD-2AD7A
         * tokenUrl: https://boonlive-rcu.com/oauth2/token1
         * grantType: authorization_code，如果是刷新 Token 则为 refresh_token
         * webService: https://boonlive-rcu.com/iot/xiaomi
         */
        /// <summary>
        /// 小米小爱音箱对接
        /// </summary>
        /// <returns></returns>
        public ActionResult XiaoMi()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            logger.Error(reqData);
            try
            {
                Domain.IoTXiaoMiEntity.Body body = JsonConvert.DeserializeObject<Domain.IoTXiaoMiEntity.Body>(reqData);//得到小爱请求
                if (string.IsNullOrEmpty(body.data.uniqueKey))
                {
                    logger.Error("小爱设备cuid不能为空：" + reqData + "，来自：" + GetClientIP());
                    return Json(ReturnXiaoMiError(-1, "设备cuid不能为空"), JsonRequestBehavior.AllowGet);//该消息表示由于请求消息中属性信息错误，导致技能无法处理请求消息。
                }
                Host host = host = HostManager.GetByXiaoDuCUID(body.data.uniqueKey);//根据小度音箱序列号获取对应RCU主机
                if (host == null)
                {
                    logger.Error("小爱音箱cuid(" + body.data.uniqueKey + ")尚未绑定客房主机");
                    return Json(ReturnXiaoMiError(-1, "小爱cuid(" + body.data.uniqueKey + ")尚未绑定客房主机"), JsonRequestBehavior.AllowGet);//"小度音箱(" + request.payload.cuid + ")尚未绑定客房主机"
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    logger.Error("小爱音箱当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期");
                    return Json(ReturnXiaoMiError(-1, "小爱音箱当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期"), JsonRequestBehavior.AllowGet);//该消息表示请求消息中access token过期，不能使用。
                }
                switch (body.intent)
                {
                    case "":
                        break;
                }
                return Json("", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("处理小爱语音设备命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }

        private Domain.IoTXiaoMiEntity.Error ReturnXiaoMiError(int code, string desc)
        {
            return new Domain.IoTXiaoMiEntity.Error() { code = code, description = desc };
        }

        #endregion

        #region 天猫精灵语音对接
        /*
         * clientId: C485849C
         * clientSecret: 8C9FB-6D854-CE2A0-16DAD-2AD7A
         * tokenUrl: https://boonlive-rcu.com/oauth2/token1
         * grantType: authorization_code，如果是刷新 Token 则为 refresh_token
         * webService: https://boonlive-rcu.com/iot/aligenie
         * accessKey:f522013dcbfbe5ed77f33f4aa232292b
         * accessSecret:8470c5ab75bec8f39cd0ffb2eb99a8e6
         */
        /// <summary>
        /// 天猫精灵音箱对接
        /// </summary>
        /// <returns></returns>
        public ActionResult aligenie()
        {
            string IP = "";
            string PPP = Request.UserHostAddress;
            string III = Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(III))
            {
                IP = PPP;
            }
            else
            {
                IP = III;
            }

            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            //logger.Error(reqData);
            string g_requestid = "";
            int g_hotelcode = 0;
            string g_hotelid = "";
            string g_roomnum = "";
            string platformName = "天猫精灵";
            try
            {
                Domain.IoTAliGenieEntity.Request req = JsonConvert.DeserializeObject<Domain.IoTAliGenieEntity.Request>(reqData);//得到天猫精灵请求


                if (string.IsNullOrEmpty(req.baseInfo.hotelId) || string.IsNullOrEmpty(req.baseInfo.roomNo))
                {
                    logger.Error(platformName + "hotelId和roomNo不能为空：" + reqData + "，来自：" + GetClientIP());
                    return Json(ReturnAliGenieError("hotelId和roomNo不能为空", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);//该消息表示由于请求消息中属性信息错误，导致技能无法处理请求消息。
                }

                string idd = req.baseInfo.hotelId;
                string roo = req.baseInfo.roomNo;
                string RequestId = req.baseInfo.requestId;
                g_requestid = RequestId;

                Host host = null;
                string TianMaoKongZhiKey = CacheKey.TianMaoJingLing + "_" + idd + "_" + roo;
                var UXV = HttpContext.Cache.Get(TianMaoKongZhiKey);
                if (UXV != null)
                {
                    host = UXV as Host;
                }
                else
                {
                    host = HostManager.GetByTianMaoCUID(req.baseInfo.hotelId + "&" + req.baseInfo.roomNo);//根据小度音箱序列号获取对应RCU主机  
                    if (host != null)
                    {
                        string TianMaoKongZhiKeyDB = CacheKey.TianMaoJingLing + "_" + host.SysHotel.ID + "_" + host.RoomNumber;
                        HttpContext.Cache.Insert(TianMaoKongZhiKey, host, null, DateTime.Now.AddHours(24), Cache.NoSlidingExpiration);
                        HttpContext.Cache.Insert(TianMaoKongZhiKeyDB, host, null, DateTime.Now.AddHours(24), Cache.NoSlidingExpiration);
                    }
                }
                if (host == null)
                {
                    logger.Error(platformName + "(" + req.baseInfo.hotelId + "&" + req.baseInfo.roomNo + ")尚未绑定客房主机");
                    return Json(ReturnAliGenieError(platformName + "(" + req.baseInfo.hotelId + "&" + req.baseInfo.roomNo + ")尚未绑定客房主机", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期");
                    //return Json(ReturnAliGenieError("当前访问酒店已过期", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);//该消息表示请求消息中access token过期，不能使用。
                }


                long Requesttime = req.baseInfo.requestTime;
                string a = host.SysHotel.ID.ToString(); ;
                string b = host.RoomNumber;
                string c = host.SysHotel.Code;
                int co = 0;
                int.TryParse(c, out co); ;
                string Key = CacheKey.IOTKey;
                g_requestid = RequestId;
                g_hotelid = a;
                g_roomnum = b;
                g_hotelcode = co;

                bool is_monitor = true;
                //var qqq = CSRedisCacheHelper.ForeverGet<List<IOT_Monitor_Host>>(Key);
                //if (qqq != null && qqq.Count > 0)
                //{
                //    //is_monitor = qqq.Any(A => A.HotelID.Equals(a) && A.RoomNumber.Equals(b));
                //    var df = qqq.Where(A => A.HotelID.Equals(a) && A.RoomNumber.Equals(b));
                //    if (df.Count() > 0)
                //    {
                //        is_monitor = true;
                //    }
                //}

                if (is_monitor)
                {
                    IOTMonitorData i = new IOTMonitorData();
                    i.RemoteIP = IP;
                    i.Step = 0;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.CreateTime = DateTime.Now;
                    i.TriggerTime = ti;
                    i.HotelId = a;
                    i.RoomNumber = b;
                    i.HotelCode = co;
                    i.RequestId = RequestId;
                    i.Platform = platformName;
                    i.CommandDescription = reqData;
                    SendMQTTData.Send(i);
                }


                switch (req.command.commandType.ToUpper())
                {
                    case "QUERYALL"://小度平台发现设备
                        {
                            if (is_monitor)
                            {
                                IOTMonitorData i = new IOTMonitorData();
                                i.ControlClass = ControlClass_Disconvery;
                                i.Step = 1;
                                i.CreateTime = DateTime.Now;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.RoomNumber = b;
                                i.HotelCode = co;
                                i.RequestId = RequestId;
                                i.Platform = platformName;
                                i.CommandDescription = "发现设备";
                                SendMQTTData.Send(i);
                            }

                            string ChaXunKey = CacheKey.TianMaoJingLingQuerryAll + "_" + a + "_" + b;

                            Domain.IoTAliGenieEntity.Response response = null;
                            var Data = HttpContext.Cache.Get(ChaXunKey);
                            if (Data != null)
                            {
                                response = Data as Domain.IoTAliGenieEntity.Response;
                            }
                            else
                            {
                                //获取需要控制设备的分组信息
                                List<Domain.IoTAliGenieEntity.GroupsItem> groups = new List<Domain.IoTAliGenieEntity.GroupsItem>();
                                List<Domain.IoTAliGenieEntity.SceneModeItem> sceneModes = new List<Domain.IoTAliGenieEntity.SceneModeItem>();
                                List<Domain.IoTAliGenieEntity.DevicesItem> devices = new List<Domain.IoTAliGenieEntity.DevicesItem>();
                                Domain.IoTAliGenieEntity.DevicesItem devicesItem;
                                //获取需要控制的场景，通过api推送：https://openapi.aligenie.com/v1.0/ip/importHotelConfig
                                IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                                //List<Domain.IoTAliGenieEntity.RcuCustomScenes> rcuCustomScenes = new List<Domain.IoTAliGenieEntity.RcuCustomScenes>();
                                foreach (RoomTypeScene scene in sceneModals)
                                {
                                    Domain.IoTAliGenieEntity.SceneModeItem item = new Domain.IoTAliGenieEntity.SceneModeItem();
                                    //Domain.IoTAliGenieEntity.RcuCustomScenes rcuCustomScene = new Domain.IoTAliGenieEntity.RcuCustomScenes();
                                    item.SceneId = scene.ID.ToString();
                                    item.Name = scene.Name;
                                    item.Icon = "";
                                    item.Description = "";
                                    List<string> corpusList = new List<string>() { item.Name, "打开" + item.Name };
                                    if (!string.IsNullOrEmpty(scene.AliasName))
                                    {
                                        corpusList.Add(scene.AliasName);//别名不为空才添加
                                        //item.CorpusList = new List<string>(scene.AliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));//别名不为空才添加
                                    }
                                    item.CorpusList = corpusList;
                                    item.isDisplayScreen = 1;
                                    sceneModes.Add(item);// 同步技能上报
                                }
                                //获取需要控制的设备信息
                                IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                                foreach (HostModal hostModal in hostModals)
                                {
                                    devicesItem = new Domain.IoTAliGenieEntity.DevicesItem();
                                    devicesItem.number = hostModal.Modal.ModalAddress;
                                    devicesItem.deviceName = hostModal.Modal.Name;
                                    if (string.IsNullOrEmpty(hostModal.Modal.Name))
                                    {
                                        continue;
                                    }
                                    if (!string.IsNullOrEmpty(hostModal.Modal.AliasName))
                                    {
                                        devicesItem.aliasList = new List<string>(hostModal.Modal.AliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));//别名不为空才添加
                                    }
                                    switch (hostModal.Modal.Type)
                                    {
                                        case DeviceType.AirConditioner:
                                            devicesItem.name = "Aircondition";
                                            break;
                                        case DeviceType.Curtain:
                                            if (hostModal.Modal.Name.IndexOf("窗帘") > -1)
                                            {
                                                devicesItem.name = "Curtain";
                                            }
                                            else if (hostModal.Modal.Name.IndexOf("窗纱") > -1)
                                            {
                                                devicesItem.name = "LaceCurtain";
                                            }
                                            else
                                            {
                                                devicesItem.name = "Curtain";
                                            }
                                            break;
                                        case DeviceType.TV:
                                            devicesItem.name = "TV";
                                            break;
                                        default:
                                            devicesItem.name = "DimmingLight";
                                            break;
                                    }
                                    devices.Add(devicesItem);
                                }
                                //添加所有灯
                                devices.Add(new Domain.IoTAliGenieEntity.DevicesItem()
                                {
                                    number = "000000001",
                                    deviceName = "所有灯",
                                    name = "DimmingLight"
                                });
                                groups.Add(new Domain.IoTAliGenieEntity.GroupsItem
                                {
                                    groupName = "房间",
                                    groupId = "room",
                                    devices = devices
                                });
                                //找到可控场景和设备，响应天猫精灵
                                response = new Domain.IoTAliGenieEntity.Response
                                {
                                    result = new Domain.IoTAliGenieEntity.Result()
                                    {
                                        enableInfraredDeviceImport = false,
                                        enableMeshDeviceImport = false,
                                        groups = groups,
                                        sceneModes = sceneModes
                                    },
                                    responseTime = Common.TimeHelper.DateTimeToStamp(DateTime.Now),
                                    requestId = req.baseInfo.requestId,
                                    success = true,
                                    message = "success",
                                    statusCode = 200
                                };

                                Data = response;
                                HttpContext.Cache.Insert(ChaXunKey, Data, null, DateTime.Now.AddMinutes(24), Cache.NoSlidingExpiration);
                            }
                            //天猫精灵统计
                            string KKK = "TianMaoQueryAll";
                            RCUHost.RCUHostCommon.tools.LanJieData(KKK, host.SysHotel.Code);

                            if (is_monitor)
                            {
                                IOTMonitorData i = new IOTMonitorData();
                                i.Step = 4;
                                i.CreateTime = DateTime.Now;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.RoomNumber = b;
                                i.HotelCode = co;
                                i.RequestId = RequestId;
                                i.Platform = platformName;
                                i.CommandDescription = "TianMao_QueryAllSuccess";
                                SendMQTTData.Send(i);
                            }
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    case "CONTROL"://天猫控制消息
                        {
                            //天猫精灵统计
                            string KKK = "TianMaoCONTROL";
                            RCUHost.RCUHostCommon.tools.LanJieData(KKK, host.SysHotel.Code);
                            bool is_online = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
                            if (is_monitor)
                            {
                                string desc = platformName + "酒店:" + host.SysHotel.Name + host.SysHotel.Code + " 房间号：" + host.RoomNumber + " 在线状态：" + is_online.ToString();
                                IOTMonitorData i = new IOTMonitorData();
                                i.ControlClass = ControlClass_KongZhiSheBei;
                                i.Step = 1;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.CreateTime = DateTime.Now;
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.RoomNumber = b;
                                i.HotelCode = co;
                                i.RequestId = RequestId;
                                i.Platform = platformName;
                                i.CommandDescription = desc;
                                SendMQTTData.Send(i);
                            }
                            if (!is_online)
                            {
                                logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");
                                return Json(ReturnAliGenieError("当前访问rcu主机不在线", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);//当技能检测到目标设备没有连接到设备云或者设备云不在线时，会给DuerOS发送TargetOfflineError消息。
                            }
                            bool is_card_in = CheckGetPower(host);

                            if (host.SysHotel.Code == "2079")
                            {
                                is_card_in = true;
                            }
                            if (is_monitor)
                            {
                                string desc = platformName + "酒店: " + host.SysHotel.Name + host.SysHotel.Code + "房间号：" + host.RoomNumber + " 取电状态: " + is_card_in.ToString();
                                IOTMonitorData i = new IOTMonitorData();
                                i.CreateTime = DateTime.Now;
                                i.Step = 2;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.RoomNumber = b;
                                i.HotelCode = co;
                                i.RequestId = RequestId;
                                i.Platform = platformName;
                                i.CommandDescription = desc;
                                SendMQTTData.Send(i);
                            }
                            if (!is_card_in)
                            {
                                logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");
                                return Json(ReturnAliGenieError("当前访问客房尚未取电", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);
                            }
                            try
                            {
                                foreach (Domain.IoTAliGenieEntity.DevicesItem devicesItem in req.command.devices)
                                {
                                    switch (devicesItem.name)
                                    {
                                        case "Mode":
                                            {
                                                RoomTypeScene scene = null;
                                                if (devicesItem.modeType != null && devicesItem.modeType.ToLower() == "custom" && devicesItem.mode.Length < 9)
                                                {
                                                    scene = RoomTypeSceneManager.Get(host.RoomType, Convert.ToInt16(devicesItem.mode));//BLW上报的场景
                                                }
                                                else
                                                {
                                                    scene = RoomTypeSceneManager.Get(host.RoomType, devicesItem.mode);//天猫平台预定义的场景，如：sleep

                                                    //新添加的代码，以前这是 是碰运气碰对了
                                                    if (scene == null)
                                                    {
                                                        scene = RoomTypeSceneManager.Get(host.RoomType, devicesItem.modeName);//天猫平台预定义的场景，如：sleep
                                                    }
                                                }

                                                if (is_monitor)
                                                {
                                                    string desc = "模式控制";
                                                    IOTMonitorData i = new IOTMonitorData();
                                                    i.ControlClass = ControlClass_SceneKongZhi;
                                                    i.SceneName = scene.Name;
                                                    i.CreateTime = DateTime.Now;
                                                    i.Step = 3;
                                                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                    i.TriggerTime = ti;
                                                    i.HotelId = a;
                                                    i.RoomNumber = b;
                                                    i.HotelCode = co;
                                                    i.RequestId = RequestId;
                                                    i.Platform = platformName;
                                                    i.CommandDescription = desc;
                                                    SendMQTTData.Send(i);
                                                }
                                                if (scene == null)
                                                {
                                                    logger.Error(string.Format("{0}(酒店：{1}，房号：{2})未找到对应的场景，ID：{3}，modeType：{4}", platformName, host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, devicesItem.mode, devicesItem.modeType));

                                                    if (is_monitor)
                                                    {
                                                        string desc = "找不到此模式";
                                                        IOTMonitorData i = new IOTMonitorData();
                                                        i.CreateTime = DateTime.Now;
                                                        i.Step = 4;
                                                        string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                        i.TriggerTime = ti;
                                                        i.HotelId = a;
                                                        i.RoomNumber = b;
                                                        i.HotelCode = co;
                                                        i.RequestId = RequestId;
                                                        i.Platform = platformName;
                                                        i.CommandDescription = desc;
                                                        SendMQTTData.Send(i);
                                                    }
                                                    return Json(ReturnAliGenieError("未找到对应的场景", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);
                                                }
                                                else
                                                {

                                                    if (is_monitor)
                                                    {
                                                        string desc = "模式控制";
                                                        IOTMonitorData i = new IOTMonitorData();
                                                        i.ControlClass = ControlClass_SceneKongZhi;
                                                        i.SceneName = scene.Name;
                                                        i.CreateTime = DateTime.Now;
                                                        i.Step = 3;
                                                        string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                        i.TriggerTime = ti;
                                                        i.HotelId = a;
                                                        i.RoomNumber = b;
                                                        i.HotelCode = co;
                                                        i.RequestId = RequestId;
                                                        i.Platform = platformName;
                                                        i.CommandDescription = desc;
                                                        SendMQTTData.Send(i);
                                                    }
                                                }
                                                LightControlManager.ApplyScene(host, scene);

                                                if (is_monitor)
                                                {
                                                    string desc = "房间模式控制完毕";
                                                    IOTMonitorData i = new IOTMonitorData();
                                                    i.CreateTime = DateTime.Now;
                                                    i.Step = 4;
                                                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                    i.TriggerTime = ti;
                                                    i.HotelId = a;
                                                    i.RoomNumber = b;
                                                    i.HotelCode = co;
                                                    i.RequestId = RequestId;
                                                    i.Platform = platformName;
                                                    i.CommandDescription = desc;
                                                    SendMQTTData.Send(i);
                                                }
                                                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, platformName, host.SysHotel.ID);
                                            }
                                            break;
                                        default:
                                            {
                                                switch (devicesItem.number)
                                                {
                                                    case "000000001"://所有灯
                                                        {
                                                            List<IotDeviceData> lli = new List<IotDeviceData>();
                                                            var devices = new List<RCUHost.Protocols.Device>();
                                                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                                            sb.Append("控制客房(" + host.RoomNumber + ")所有灯：");
                                                            var hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.Name.Contains("灯") && r.Modal.WXActiveIndicator).ToList();
                                                            foreach (HostModal hostModal in hostModals)
                                                            {
                                                                switch (hostModal.Modal.Type)
                                                                {
                                                                    case DeviceType.Relay:
                                                                    case DeviceType.Expand:
                                                                    case DeviceType.Dimmer:
                                                                    case DeviceType.Traic:
                                                                    case DeviceType.Strip:
                                                                    case DeviceType.PWMDimmer:
                                                                    case DeviceType.PWMExpand:
                                                                    case DeviceType.PBLED:
                                                                    case DeviceType.A9IORelay:
                                                                    case DeviceType.PB20:
                                                                    case DeviceType.PB20_LD:
                                                                    case DeviceType.PB20_LS:
                                                                    case DeviceType.ColorTemp:
                                                                        int status = hostModal.Status;
                                                                        int brightness = hostModal.Brightness;
                                                                        var device = new RCUHost.Protocols.Device();
                                                                        device.Address = hostModal.Modal.ModalAddress;
                                                                        device.AddressType = RCUHost.Protocols.AddressType.DeviceAddress;
                                                                        device.Type = hostModal.Modal.Type;
                                                                        switch (devicesItem.name)
                                                                        {

                                                                            case "Light"://灯光
                                                                                switch (devicesItem.@switch)
                                                                                {
                                                                                    case 1:
                                                                                        status = 1;
                                                                                        brightness = 100;
                                                                                        //sb.Append("状态：打开");
                                                                                        break;
                                                                                    default:
                                                                                        status = 2;
                                                                                        brightness = 0;
                                                                                        //sb.Append("状态：关闭");
                                                                                        break;
                                                                                }
                                                                                break;
                                                                            case "DimmingLight"://调光
                                                                                string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID.ToString() + "_" + device.Address;
                                                                                var hostModal_T = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);

                                                                                bool JumpBrightcontrol = true;
                                                                                var is_100 = devicesItem.value.HasValue;
                                                                                if (is_100)
                                                                                {
                                                                                    if (devicesItem.value == 100)
                                                                                    {
                                                                                        JumpBrightcontrol = false;
                                                                                    }
                                                                                }

                                                                                if (co == 1085 || co == 1001 || co == 1003 || co > 2000)
                                                                                {
                                                                                    //logger.Error("查询的Key值:"+KKey);
                                                                                    if (hostModal_T != null && hostModal_T.Status == 2 && JumpBrightcontrol == true) { continue; }
                                                                                }
                                                                                if (devicesItem.value.HasValue)
                                                                                {
                                                                                    switch (devicesItem.value)
                                                                                    {
                                                                                        case 0:
                                                                                            status = 2;
                                                                                            brightness = 0;
                                                                                            //sb.Append("状态：关闭");
                                                                                            break;
                                                                                        default:
                                                                                            status = 1;
                                                                                            brightness = (int)devicesItem.value;
                                                                                            //sb.Append("状态：打开，亮度：" + brightness);
                                                                                            break;
                                                                                    }
                                                                                }

                                                                                if (devicesItem.value_up.HasValue)
                                                                                {
                                                                                    status = 1;
                                                                                    brightness += (int)devicesItem.value_up;
                                                                                    if (brightness > 100)
                                                                                    {
                                                                                        brightness = 100;
                                                                                    }
                                                                                    //sb.Append("调亮：" + devicesItem.value_up);
                                                                                }
                                                                                if (devicesItem.value_down.HasValue)
                                                                                {
                                                                                    status = 1;
                                                                                    brightness -= (int)devicesItem.value_down;
                                                                                    if (brightness < 0)
                                                                                    {
                                                                                        brightness = 0;
                                                                                        status = 2;
                                                                                    }
                                                                                    //sb.Append("调暗：" + devicesItem.value_down);
                                                                                }
                                                                                break;
                                                                        }

                                                                        device.Status = (byte)status;
                                                                        device.Brightness = (byte)brightness;
                                                                        devices.Add(device);
                                                                        sb.Append(hostModal.Modal.Name + "，");

                                                                        IotDeviceData iotdata = new IotDeviceData();
                                                                        iotdata.DeviceAddress = hostModal.Modal.ModalAddress;
                                                                        iotdata.DeviceName = hostModal.Modal.Name;
                                                                        break;
                                                                }
                                                            }
                                                            LightControlManager.AllDeviceControl(host, devices);
                                                            sb.Append("动作：" + (devicesItem.@switch == 1 ? "打开" : "关闭"));

                                                            if (is_monitor)
                                                            {
                                                                IOTMonitorData i = new IOTMonitorData();
                                                                i.ControlClass = ControlClass_KongZhiSheBei;
                                                                i.WhichOneDevice = lli;

                                                                i.CreateTime = DateTime.Now;
                                                                i.Step = 3.0;
                                                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                                i.TriggerTime = ti;
                                                                i.HotelId = a;
                                                                i.RoomNumber = b;
                                                                i.HotelCode = co;
                                                                i.RequestId = RequestId;
                                                                i.Platform = platformName;
                                                                i.CommandDescription = "房间所有灯控制。" + sb.ToString();
                                                                SendMQTTData.Send(i);
                                                            }
                                                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                                                        }
                                                        break;
                                                    default:
                                                        {
                                                            //var hostModal = HostModalManager.GetByModalAddress(host.ID, devicesItem.number);//设备控制

                                                            HostModal hostModal = new HostModal();
                                                            RoomTypeModal redalert = new RoomTypeModal();
                                                            hostModal.Modal = redalert;
                                                            string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + devicesItem.number;
                                                            var hostModal_T = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                                                            if (hostModal_T != null)
                                                            {
                                                                hostModal.HostID = hostModal_T.HostID;
                                                                hostModal.Status = hostModal_T.Status;
                                                                hostModal.Brightness = hostModal_T.Brightness;
                                                                var aaa = hostModal_T.AirConditionData;
                                                                hostModal.SettingTemp = aaa.SettingTemp;
                                                                hostModal.CurrentTemp = aaa.CurrentTemp;
                                                                hostModal.FanSpeed = aaa.FanSpeed;
                                                                hostModal.Mode = aaa.Mode;
                                                                hostModal.Valve = aaa.Valve;
                                                                hostModal.Modal.Type = hostModal_T.ModalType;
                                                                hostModal.Modal.ModalAddress = hostModal_T.Modal.ModalAddress;
                                                            }
                                                            else
                                                            {
                                                                //hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);//设备控制
                                                                hostModal = HostModalManager.GetByModalAddress(host.ID, devicesItem.number);//设备控制
                                                            }
                                                            if (hostModal == null)
                                                            {
                                                                string hhh = string.Format("{3}(酒店：{0}，房号：{1})未找到对应的回路，Address：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, devicesItem.number, platformName);
                                                                logger.Error(hhh);
                                                                if (is_monitor)
                                                                {
                                                                    IOTMonitorData i = new IOTMonitorData();
                                                                    i.CreateTime = DateTime.Now;
                                                                    i.Step = 3.1;
                                                                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                                    i.TriggerTime = ti;
                                                                    i.HotelId = a;
                                                                    i.RoomNumber = b;
                                                                    i.HotelCode = co;
                                                                    i.RequestId = RequestId;
                                                                    i.Platform = platformName;
                                                                    i.CommandDescription = hhh;
                                                                    SendMQTTData.Send(i);
                                                                }
                                                                return Json(ReturnAliGenieError("未找到对应的回路", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);
                                                            }
                                                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                                            sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：");
                                                            int status = hostModal.Status;
                                                            int brightness = hostModal.Brightness;
                                                            int temperature = hostModal.SettingTemp;
                                                            int fanSpeed = hostModal.FanSpeed;
                                                            int mode = hostModal.Mode;
                                                            int valve = hostModal.Valve;
                                                            switch (devicesItem.name)
                                                            {
                                                                case "Light"://灯光
                                                                case "Door"://门
                                                                case "ExhaustFan"://排气扇
                                                                    switch (devicesItem.@switch)
                                                                    {
                                                                        case 1:
                                                                            status = 1;
                                                                            brightness = 100;
                                                                            sb.Append("状态：打开");
                                                                            break;
                                                                        default:
                                                                            status = 2;
                                                                            brightness = 0;
                                                                            sb.Append("状态：关闭");
                                                                            break;
                                                                    }
                                                                    break;
                                                                case "DimmingLight"://调光
                                                                    if (devicesItem.value.HasValue)
                                                                    {
                                                                        switch (devicesItem.value)
                                                                        {
                                                                            case 0:
                                                                                status = 2;
                                                                                brightness = 0;
                                                                                sb.Append("状态：关闭");
                                                                                break;
                                                                            default:
                                                                                status = 1;
                                                                                brightness = (int)devicesItem.value;
                                                                                sb.Append("状态：打开，亮度：" + brightness);
                                                                                break;
                                                                        }
                                                                    }
                                                                    if (devicesItem.value_up.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        brightness += (int)devicesItem.value_up;
                                                                        if (brightness > 100)
                                                                        {
                                                                            brightness = 100;
                                                                        }
                                                                        sb.Append("调亮：" + devicesItem.value_up);
                                                                    }
                                                                    if (devicesItem.value_down.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        brightness -= (int)devicesItem.value_down;
                                                                        if (brightness < 0)
                                                                        {
                                                                            brightness = 0;
                                                                            status = 2;
                                                                        }
                                                                        sb.Append("调暗：" + devicesItem.value_down);
                                                                    }
                                                                    break;
                                                                case "Aircondition"://空调
                                                                    if (devicesItem.@switch.HasValue)
                                                                    {
                                                                        switch (devicesItem.@switch)
                                                                        {
                                                                            case 1:
                                                                                status = 1;
                                                                                sb.Append("状态：打开");
                                                                                break;
                                                                            default:
                                                                                status = 2;
                                                                                sb.Append("状态：关闭");
                                                                                break;
                                                                        }
                                                                    }
                                                                    if (devicesItem.mode != null)
                                                                    {
                                                                        status = 1;
                                                                        mode = ModeToInt(devicesItem.mode);
                                                                        sb.Append("模式：" + devicesItem.mode);
                                                                    }
                                                                    if (devicesItem.fanSpeed.HasValue)
                                                                    {
                                                                        switch (devicesItem.fanSpeed)
                                                                        {
                                                                            case 0://风速是0，关闭空调
                                                                                status = 2;
                                                                                fanSpeed = (int)devicesItem.fanSpeed;
                                                                                sb.Append("空调：关闭");
                                                                                break;
                                                                            default:
                                                                                status = 1;
                                                                                fanSpeed = (int)devicesItem.fanSpeed;
                                                                                sb.Append("设置风速：" + devicesItem.fanSpeed);
                                                                                break;
                                                                        }
                                                                    }
                                                                    if (devicesItem.fanSpeed_up.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        fanSpeed += (int)devicesItem.fanSpeed_up;
                                                                        if (fanSpeed > 3)
                                                                        {
                                                                            fanSpeed = 3;
                                                                        }
                                                                        sb.Append("调高风速：" + devicesItem.fanSpeed_up);
                                                                    }
                                                                    if (devicesItem.fanSpeed_down.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        fanSpeed -= (int)devicesItem.fanSpeed_down;
                                                                        if (fanSpeed < 1)
                                                                        {
                                                                            fanSpeed = 1;
                                                                        }
                                                                        sb.Append("调低风速：" + devicesItem.fanSpeed_down);
                                                                    }
                                                                    if (devicesItem.temperature.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        temperature = (int)devicesItem.temperature;
                                                                        if (temperature < 16)
                                                                        {
                                                                            temperature = 16;
                                                                        }
                                                                        else if (temperature > 32)
                                                                        {
                                                                            temperature = 32;
                                                                        }
                                                                        sb.Append("设温：" + temperature);
                                                                    }
                                                                    if (devicesItem.temperature_up.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        temperature += (int)devicesItem.temperature_up;
                                                                        if (temperature > 32)
                                                                        {
                                                                            temperature = 32;
                                                                        }
                                                                        sb.Append("调高温度：" + devicesItem.temperature_up);
                                                                    }
                                                                    if (devicesItem.temperature_down.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        temperature -= (int)devicesItem.temperature_down;
                                                                        if (temperature < 16)
                                                                        {
                                                                            temperature = 16;
                                                                        }
                                                                        sb.Append("调低温度：" + devicesItem.temperature_down);
                                                                    }
                                                                    break;
                                                                case "Curtain":
                                                                case "LaceCurtain":
                                                                    if (devicesItem.@switch.HasValue)
                                                                    {
                                                                        switch (devicesItem.@switch)
                                                                        {
                                                                            case 1:
                                                                                status = 1;
                                                                                brightness = 100;
                                                                                sb.Append("状态：打开");
                                                                                break;
                                                                            default:
                                                                                status = 2;
                                                                                brightness = 0;
                                                                                sb.Append("状态：关闭");
                                                                                break;
                                                                        }
                                                                    }
                                                                    if (devicesItem.value.HasValue)
                                                                    {
                                                                        switch (devicesItem.value)
                                                                        {
                                                                            case 0:
                                                                                status = 2;
                                                                                brightness = 0;
                                                                                sb.Append("状态：关闭");
                                                                                break;
                                                                            default:
                                                                                status = 1;
                                                                                brightness = (int)devicesItem.value;
                                                                                sb.Append("状态：打开，拉开：" + brightness);
                                                                                break;
                                                                        }
                                                                    }
                                                                    if (devicesItem.value_up.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        brightness += (int)devicesItem.value_up;
                                                                        if (brightness > 100)
                                                                        {
                                                                            brightness = 100;
                                                                        }
                                                                        sb.Append("调高：" + devicesItem.value_up);
                                                                    }
                                                                    if (devicesItem.value_down.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        brightness -= (int)devicesItem.value_down;
                                                                        if (brightness < 0)
                                                                        {
                                                                            brightness = 0;
                                                                            status = 2;
                                                                        }
                                                                        sb.Append("调低：" + devicesItem.value_down);
                                                                    }
                                                                    if (devicesItem.action != null)
                                                                    {
                                                                        switch (devicesItem.action)
                                                                        {
                                                                            case "pause":
                                                                                status = 6;
                                                                                sb.Append("状态：暂停");
                                                                                break;
                                                                            case "continue":
                                                                                status = 1;
                                                                                sb.Append("状态：继续");
                                                                                break;
                                                                        }
                                                                    }
                                                                    break;
                                                                case "TV":
                                                                    if (devicesItem.@switch.HasValue)
                                                                    {
                                                                        switch (devicesItem.@switch)
                                                                        {
                                                                            case 1:
                                                                                status = 1;
                                                                                brightness = 100;
                                                                                sb.Append("状态：打开");
                                                                                break;
                                                                            default:
                                                                                status = 2;
                                                                                brightness = 0;
                                                                                mode = 0;//电视开关时，内容传0
                                                                                sb.Append("状态：关闭");
                                                                                break;
                                                                        }
                                                                    }
                                                                    if (devicesItem.channelName != null)
                                                                    {
                                                                        status = 4;
                                                                        var channel = RoomTypeChannelsManager.LoadAll(host.RoomType.ID).Where(r => r.Name.Contains(devicesItem.channelName)).FirstOrDefault();
                                                                        if (channel != null)
                                                                        {
                                                                            valve = channel.Code;
                                                                        }
                                                                        else
                                                                        {
                                                                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的电视频道：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, devicesItem.channelName, platformName));
                                                                            return Json(ReturnAliGenieError("未找到对应的电视频道", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);
                                                                        }
                                                                        sb.Append("调整频道至：" + valve);
                                                                    }
                                                                    if (devicesItem.channelNumber.HasValue)
                                                                    {
                                                                        status = 4;
                                                                        valve = (int)devicesItem.channelNumber;
                                                                        sb.Append("调整频道至：" + valve);
                                                                    }
                                                                    if (devicesItem.channelNumber_up.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        mode = 5;
                                                                        sb.Append("频道：加");
                                                                    }
                                                                    if (devicesItem.channelNumber_down.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        mode = 6;
                                                                        sb.Append("频道：减");
                                                                    }
                                                                    if (devicesItem.volume.HasValue)
                                                                    {
                                                                    }
                                                                    if (devicesItem.volume_up.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        mode = 3;
                                                                        sb.Append("音量：加");
                                                                    }
                                                                    if (devicesItem.volume_down.HasValue)
                                                                    {
                                                                        status = 1;
                                                                        mode = 4;
                                                                        sb.Append("音量：减");
                                                                    }
                                                                    if (devicesItem.mute.HasValue)
                                                                    {
                                                                        if (devicesItem.mute == 1)
                                                                        {
                                                                            status = 1;
                                                                            mode = 1;
                                                                            sb.Append("音量：静音");
                                                                        }
                                                                        else
                                                                        {
                                                                            status = 1;
                                                                            mode = 0;
                                                                            sb.Append("音量：取消静音");
                                                                        }
                                                                    }
                                                                    break;
                                                                default:
                                                                    if (is_monitor)
                                                                    {
                                                                        IOTMonitorData i = new IOTMonitorData();
                                                                        i.CreateTime = DateTime.Now;
                                                                        i.Step = 3.10;
                                                                        string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                                        i.TriggerTime = ti;
                                                                        i.HotelId = a;
                                                                        i.RoomNumber = b;
                                                                        i.HotelCode = co;
                                                                        i.RequestId = RequestId;
                                                                        i.Platform = platformName;
                                                                        i.CommandDescription = "不支持此操作";
                                                                        SendMQTTData.Send(i);
                                                                    }
                                                                    return Json(ReturnAliGenieError("不支持此操作", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);
                                                            }

                                                            List<IotDeviceData> miaoll = new List<IotDeviceData>();
                                                            miaoll.Add(new IotDeviceData() { DeviceName = hostModal.Modal.TCLDeviceName, DeviceAddress = hostModal.Modal.ModalAddress });
                                                            //对房间设备进行操作
                                                            HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);

                                                            sb.Append(string.Format("status: {0}, brightness: {1} ,temp: {2}", status, brightness, temperature));
                                                            if (is_monitor)
                                                            {
                                                                IOTMonitorData i = new IOTMonitorData();
                                                                i.WhichOneDevice = miaoll;
                                                                i.ControlClass = ControlClass_KongZhiSheBei;
                                                                i.Step = 3;
                                                                i.CreateTime = DateTime.Now;
                                                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                                                i.TriggerTime = ti;
                                                                i.HotelId = a;
                                                                i.RoomNumber = b;
                                                                i.HotelCode = co;
                                                                i.RequestId = RequestId;
                                                                i.Platform = platformName;
                                                                i.CommandDescription = sb.ToString();
                                                                SendMQTTData.Send(i);
                                                            }
                                                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                                                        }
                                                        break;
                                                }
                                            }
                                            break;
                                    }
                                }

                            }
                            catch (Exception exc)
                            {
                                if (is_monitor)
                                {
                                    IOTMonitorData i = new IOTMonitorData();
                                    i.Step = 3.20;
                                    i.CreateTime = DateTime.Now;
                                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                    i.TriggerTime = ti;
                                    i.HotelId = a;
                                    i.RoomNumber = b;
                                    i.HotelCode = co;
                                    i.RequestId = RequestId;
                                    i.Platform = platformName;
                                    i.CommandDescription = "异常：" + exc.Message;
                                    SendMQTTData.Send(i);
                                }
                            }                            //操作完成响应天猫精灵
                            Domain.IoTAliGenieEntity.Response response = new Domain.IoTAliGenieEntity.Response
                            {
                                responseTime = Common.TimeHelper.DateTimeToStamp(DateTime.Now),
                                requestId = req.baseInfo.requestId,
                                success = true,
                                message = "success",
                                statusCode = 200,
                                result = new Domain.IoTAliGenieEntity.Result() { status = new List<Domain.IoTAliGenieEntity.DevicesItem>() }
                            };

                            if (is_monitor)
                            {
                                IOTMonitorData i = new IOTMonitorData();
                                i.Step = 4;
                                i.CreateTime = DateTime.Now;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = a;
                                i.RoomNumber = b;
                                i.HotelCode = co;
                                i.RequestId = RequestId;
                                i.Platform = platformName;
                                i.CommandDescription = "success";
                                SendMQTTData.Send(i);
                            }
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    default:
                        return Json(ReturnAliGenieError("不支持此操作", req.baseInfo.requestId), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                IOTMonitorData i = new IOTMonitorData();
                i.Step = 4.1;
                i.CreateTime = DateTime.Now;
                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                i.TriggerTime = ti;
                i.HotelId = g_hotelid;
                i.RoomNumber = g_roomnum;
                i.HotelCode = g_hotelcode;
                i.RequestId = g_requestid;
                i.Platform = platformName;
                i.CommandDescription = "exception: " + ex.Message;
                SendMQTTData.Send(i);
                logger.Error(string.Format("处理天猫精灵设备命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ReturnAliGenieError("处理天猫精灵设备命令异常", "0"), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 返回天猫精灵错误
        /// </summary>
        /// <param name="errorName"></param>
        /// <param name="requestId"></param>
        /// <returns></returns>
        private Domain.IoTAliGenieEntity.Response ReturnAliGenieError(string errorName, string requestId)
        {
            Domain.IoTAliGenieEntity.Response err = new Domain.IoTAliGenieEntity.Response
            {
                success = false,
                responseTime = Common.TimeHelper.DateTimeToStamp(DateTime.Now),
                message = errorName,
                requestId = requestId,
                statusCode = 500
            };
            return err;
        }

        #endregion

        #region OpenAI电视机对接(华视美达电视)
        /// <summary>
        /// OpenAI电视机对接
        ///   APPID：ca4jsq4h
        /// appsecrect：fd56ae71e3d34b9f94b3378a99170af4
        /// </summary>
        /// <returns></returns>
        public ActionResult openaitv()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            logger.Error(reqData);
            try
            {
                string platformName = "华视美达电视";
                Domain.IoTOpenAIEntity.Request req = JsonConvert.DeserializeObject<Domain.IoTOpenAIEntity.Request>(reqData);
                if (string.IsNullOrEmpty(req.hotelId) || string.IsNullOrEmpty(req.roomNumber))
                {
                    logger.Error(platformName + "hotelId和roomNumber不能为空：" + reqData + "，来自：" + GetClientIP());
                    return Json(ReturnOpenAI("401", "hotelId和roomNumber不能为空", req.requestId), JsonRequestBehavior.AllowGet);//该消息表示由于请求消息中属性信息错误，导致技能无法处理请求消息。
                }
                Host host = HostManager.GetByHuaWeiCUID(req.hotelId + "&" + req.roomNumber);//根据小度音箱序列号获取对应RCU主机  
                if (host == null)
                {
                    logger.Error(platformName + "(" + req.hotelId + "&" + req.roomNumber + ")尚未绑定客房主机");
                    return Json(ReturnOpenAI("401", "尚未绑定客房主机", req.requestId), JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期");
                    return Json(ReturnOpenAI("500", "当前访问酒店已过期", req.requestId), JsonRequestBehavior.AllowGet);//该消息表示请求消息中access token过期，不能使用。
                }
                if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");
                    return Json(ReturnOpenAI("403", "当前访问rcu主机不在线", req.requestId), JsonRequestBehavior.AllowGet);//当技能检测到目标设备没有连接到设备云或者设备云不在线时，会给DuerOS发送TargetOfflineError消息。
                }
                if (!CheckGetPower(host))
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");
                    return Json(ReturnOpenAI("403", "当前访问客房尚未取电", req.requestId), JsonRequestBehavior.AllowGet);
                }
                switch (req.skill)
                {
                    case "scene"://华视美达电视
                        {
                            RoomTypeScene scene = RoomTypeSceneManager.Get(host.RoomType, req.sceneName);
                            if (scene == null)
                            {
                                logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的场景：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, req.sceneName, platformName));
                                return Json(ReturnOpenAI("411", "未找到对应的场景", req.requestId), JsonRequestBehavior.AllowGet);
                            }
                            LightControlManager.ApplyScene(host, scene);
                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, platformName, host.SysHotel.ID);
                        }
                        break;
                    case "smartControl":
                        {
                            var hostModal = HostModalManager.GetByModalName(host.ID, req.deviceName);//设备控制
                            if (hostModal == null)
                            {
                                logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的设备，Address：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, req.deviceName, platformName));
                                return Json(ReturnOpenAI("402", "未找到对应的设备", req.requestId), JsonRequestBehavior.AllowGet);
                            }
                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：");
                            int status = hostModal.Status;
                            int brightness = hostModal.Brightness;
                            int temperature = hostModal.SettingTemp;
                            int fanSpeed = hostModal.FanSpeed;
                            int mode = hostModal.Mode;
                            int valve = hostModal.Valve;
                            switch (req.device)
                            {
                                case "light"://灯光
                                    switch (req.insType)
                                    {
                                        case "on":
                                            status = 1;
                                            brightness = 100;
                                            sb.Append("状态：打开");
                                            break;
                                        default:
                                            status = 2;
                                            brightness = 0;
                                            sb.Append("状态：关闭");
                                            break;
                                    }
                                    break;
                                case "curtain":
                                    switch (req.insType)
                                    {
                                        case "on":
                                            status = 1;
                                            brightness = Convert.ToInt16(req.value);
                                            sb.Append("状态：打开");
                                            break;
                                        default:
                                            status = 2;
                                            brightness = 0;
                                            sb.Append("状态：关闭");
                                            break;
                                    }
                                    break;
                                case "airControl"://空调
                                    switch (req.insType)
                                    {
                                        case "on":
                                            status = 1;
                                            sb.Append("空调：打开");
                                            break;
                                        case "temp":
                                            status = 1;
                                            temperature = Convert.ToInt16(req.value);
                                            if (temperature < 16)
                                            {
                                                temperature = 16;
                                            }
                                            else if (temperature > 32)
                                            {
                                                temperature = 32;
                                            }
                                            sb.Append("设温：" + temperature);
                                            break;
                                        case "mode":
                                            status = 1;
                                            mode = ModeToInt(req.value);
                                            sb.Append("模式：" + req.value);
                                            break;
                                        case "windspeed":
                                            status = 1;
                                            fanSpeed = Convert.ToInt16(req.value);
                                            sb.Append("设置风速：" + req.value);
                                            break;
                                        case "winddir":
                                            status = 1;
                                            sb.Append("设置风向：" + req.value);
                                            break;
                                        default:
                                            status = 2;
                                            sb.Append("空调：关闭");
                                            break;
                                    }
                                    break;
                                default:
                                    return Json(ReturnOpenAI("500", "不支持此操作", req.requestId), JsonRequestBehavior.AllowGet);
                            }
                            //对房间设备进行操作
                            HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                        }
                        break;
                    default:
                        return Json(ReturnOpenAI("500", "不支持此操作", req.requestId), JsonRequestBehavior.AllowGet);
                }
                return Json(ReturnOpenAI("200", "操作成功", req.requestId), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("处理OpenAI电视机命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ReturnOpenAI("500", "处理OpenAI电视机命令异常", "0"), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="code"></param>
        /// <param name="msg"></param>
        /// <param name="requestId"></param>
        /// <returns></returns>
        private Domain.IoTOpenAIEntity.Response ReturnOpenAI(string code, string msg, string requestId)
        {
            Domain.IoTOpenAIEntity.Response err = new Domain.IoTOpenAIEntity.Response
            {
                code = code,
                msg = msg,
                requestId = requestId,
                timestamp = Common.TimeHelper.DateTimeToStamp(DateTime.Now)
            };
            return err;
        }

        #endregion

        #region 长虹AI遥控器
        /// <summary>
        /// http://api?userId=13000000000&roomNum=8002&command="温度+"&mode="空调温度加"&timestamp=1686800490&sign=
        /// </summary>
        /// <returns></returns>
        public ActionResult RemoteControl()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            if (string.IsNullOrEmpty(reqData))
            {
                return Json(ReturnRemoteControlError(-1, "参数不能为空"), JsonRequestBehavior.AllowGet);
            }
            //logger.Error("收到遥控器控制命令：" + reqData);
            try
            {
                string platformName = "遥控器";
                reqData = Common.Tools.UrlParamsToJson(reqData);
                Domain.IoTRemoteControlEntity.Request req = JsonConvert.DeserializeObject<Domain.IoTRemoteControlEntity.Request>(reqData);//得到长虹AI遥控器请求

                if (string.IsNullOrEmpty(req.userId))
                {
                    return Json(ReturnRemoteControlError(-1, "设备userId不能为空"), JsonRequestBehavior.AllowGet);
                }
                if (string.IsNullOrEmpty(req.roomNum))
                {
                    return Json(ReturnRemoteControlError(-1, "设备roomNum不能为空"), JsonRequestBehavior.AllowGet);
                }
                Host host = host = HostManager.GetByRoomNumber(req.roomNum, req.userId);
                if (host == null)
                {
                    return Json(ReturnRemoteControlError(-1, "未找到对应酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")和客房(" + host.RoomNumber + ")"), JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)
                {
                    return Json(ReturnRemoteControlError(-1, "控制当前酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期"), JsonRequestBehavior.AllowGet);
                }
                if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                {
                    return Json(ReturnRemoteControlError(-1, "控制当前酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线"), JsonRequestBehavior.AllowGet);
                }
                if (!CheckGetPower(host))
                {
                    return Json(ReturnRemoteControlError(-1, "控制当前酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电"), JsonRequestBehavior.AllowGet);
                }
                if (req.mode.IndexOf("模式") > -1 && req.mode.IndexOf("空调模式") == -1)
                {
                    RoomTypeScene scene = RoomTypeSceneManager.Get(host.RoomType, req.mode);
                    if (scene == null)
                    {
                        string msg = string.Format("(酒店：{0}，房号：{1})未找到对应的场景，mode：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, req.mode);
                        return Json(ReturnRemoteControlError(-1, msg), JsonRequestBehavior.AllowGet);
                    }
                    LightControlManager.ApplyScene(host, scene);
                    SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, platformName, host.SysHotel.ID);
                }
                else
                {
                    HostModal hostModal = null;
                    if (req.mode.IndexOf("窗帘") > -1)
                    {
                        hostModal = HostModalManager.GetByModalName(host.ID, "窗帘");
                    }
                    else if (req.mode.IndexOf("空调") > -1)
                    {
                        hostModal = HostModalManager.GetByModalName(host.ID, "空调");
                    }
                    else if (req.mode.IndexOf("排风扇") > -1)
                    {
                        hostModal = HostModalManager.GetByModalName(host.ID, "排风扇");
                    }
                    if (hostModal == null)
                    {
                        string msg = string.Format("(酒店：{0}，房号：{1})未找到对应的({2})回路", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, req.mode);
                        return Json(ReturnRemoteControlError(-1, msg), JsonRequestBehavior.AllowGet);
                    }
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：");
                    int status = 0;//hostModal.Status;
                    int brightness = 0;//hostModal.Brightness;
                    int temperature = 0;//hostModal.SettingTemp;
                    int fanSpeed = 0;//hostModal.FanSpeed;
                    int mode = 0;//hostModal.Mode;
                    int valve = 0;//hostModal.Valve;
                    if (req.mode.IndexOf("打开") > -1)
                    {
                        status = 1;
                        brightness = 100;
                        sb.Append("打开");
                    }
                    else if (req.mode.IndexOf("关闭") > -1)
                    {
                        status = 2;
                        brightness = 0;
                        sb.Append("关闭");
                    }
                    else if (req.mode.IndexOf("开关") > -1)
                    {
                        status = hostModal.Status == 1 ? 2 : 1;//当前开则关，当前关则开
                        brightness = status == 1 ? 100 : 0;
                        sb.Append(status == 1 ? "打开" : "关闭");
                    }
                    else if (req.mode == "空调温度加")
                    {
                        temperature = hostModal.SettingTemp + 1;
                        if (temperature > 32)
                        {
                            temperature = 32;
                        }
                        sb.Append("空调温度加：" + temperature);
                    }
                    else if (req.mode == "空调温度减")
                    {
                        temperature = hostModal.SettingTemp - 1;
                        if (temperature < 16)
                        {
                            temperature = 16;
                        }
                        sb.Append("空调温度减：" + temperature);
                    }
                    else if (req.mode == "空调风速调节")
                    {
                        fanSpeed = hostModal.FanSpeed + 1;
                        if (fanSpeed > 3)
                        {
                            fanSpeed = 1;
                        }
                        sb.Append("空调风速调节：" + fanSpeed);
                    }
                    else if (req.mode == "空调模式调节")
                    {
                        mode = hostModal.Mode + 1;
                        if (mode > 3)
                        {
                            mode = 1;
                        }
                        sb.Append("空调模式调节：" + mode);
                    }
                    //对房间设备进行操作
                    HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                    SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                }
                return Json(ReturnRemoteControlError(0), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("处理长虹AI遥控器命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ReturnRemoteControlError(-1, ex.Message), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="code">0成功，-1失败</param>
        /// <param name="msg">失败原因</param>
        /// <returns></returns>
        private Domain.IoTRemoteControlEntity.Error ReturnRemoteControlError(int code, string msg = "succes")
        {
            if (code != 0)
            {
                logger.Error(string.Format("处理遥控器命令异常：{0}，来自：{1}", msg, GetClientIP()));
            }
            return new Domain.IoTRemoteControlEntity.Error() { code = code, msg = msg };
        }
        #endregion


        #region 创维电视对接

        /// <summary>
        /// 酒店列表
        /// </summary>
        /// <returns></returns>
        [HttpGet()]
        public ActionResult ChuangWei_HotelInfo()
        {
            ReturnInfo r = new ReturnInfo();
            r.code = 200;
            string msg = "查询成功";
            int code = 200;
            r.msg = msg;

            IList<object> list = new List<object>();
            var Q = Request.Headers["Authorization"];
            if (Q != null)
            {
                JWTData JJJ = null;
                string Token = Q.ToString();
                if (!string.IsNullOrEmpty(Token))
                {
                    var TuT = SignKeyCommon.TokenValidate(Token, out JJJ, out code, out msg);
                    if (TuT)
                    {
                        var hotels = SysHotelManager.LoadAll().Where(A => !A.IsDeleted).ToList();
                        foreach (SysHotel hotel in hotels)
                        {
                            if (hotel.IsUseSkyworthTV)
                            {
                                list.Add(new
                                {
                                    id = hotel.ID,
                                    name = hotel.Name
                                });
                            }
                        }
                    }
                    else
                    {
                        r.code = code;
                        r.msg = msg;
                    }
                }

                r.data = list;
            }
            else
            {
                r.code = 10030;
                r.msg = msg;
            }
            return Json(r, JsonRequestBehavior.AllowGet);
        }

        [HttpGet()]
        public ActionResult ChuangWei_RoomInfo(string hotelId)
        {
            ReturnInfo r = new ReturnInfo();
            r.code = 200;

            string msg = "";
            int code = 200;
            IList<object> list = new List<object>();
            string Token = "";
            var AuthData = Request.Headers["Authorization"];
            if (AuthData != null)
            {
                JWTData JJJ = null;
                Token = AuthData.ToString();
                var TuT = SignKeyCommon.TokenValidate(Token, out JJJ, out code, out msg);
                if (TuT)
                {
                    int hid = 0;
                    int.TryParse(hotelId, out hid);
                    var hosts = HostManager.LoadAll(hid).OrderBy(A => A.RoomNumber);
                    foreach (Host hotel in hosts)
                    {
                        list.Add(new
                        {
                            id = hotel.ID,
                            name = hotel.RoomNumber
                        });
                    }
                    msg = "查询成功";
                }
                else
                {
                    r.code = code;
                    r.msg = msg;
                }
                r.data = list;
            }
            else
            {
                r.code = 10030;
                r.msg = msg;
            }
            return Json(r, JsonRequestBehavior.AllowGet);
        }

        [HttpGet()]
        public ActionResult ChuangWei_DeviceInfo(int HotelId, int RoomId, string TimeStamp)
        {
            ReturnInfo r1 = new ReturnInfo();
            r1.code = 200;
            string msg = "请求成功";
            r1.msg = msg;

            IList<DD> list = new List<DD>();

            IList<HostModal> hostModalsAllData = HostModalManager.LoadByHostID(RoomId).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
            //IList<HostModal> hostModalsAllData = HostModalManager.LoadByHostID(RoomId).Where(r => r.Modal.WXActiveIndicator).ToList();
            IList<HostModal> hostModals = hostModalsAllData.Where(r => r.Modal.MultipleGroupID == 0).ToList();
            IList<HostModal> hostModalsGroup = hostModalsAllData.Where(r => r.Modal.MultipleGroupID != 0).ToList();
            foreach (HostModal modal in hostModals)
            {
                switch (modal.Modal.Type)
                {
                    case DeviceType.Relay://主机继电器
                    case DeviceType.Dimmer://LED调光
                    case DeviceType.PWMDimmer://PWM调光
                    case DeviceType.PWMExpand://PWM扩展
                    case DeviceType.PBLED:
                    case DeviceType.Traic://可控硅调光
                    case DeviceType.Strip://灯带调光
                    case DeviceType.A9IORelay:
                    case DeviceType.LVout://弱电输出
                    case DeviceType.Expand://扩展继电器
                    case DeviceType.PB20:
                    case DeviceType.PB20_LD:
                    case DeviceType.PB20_LS:
                    case DeviceType.ColorTemp:
                        DD light = new DD
                        {
                            deviceId = "LIGHT_" + modal.HostID + "_" + modal.Modal.ModalAddress,
                            deviceType = "LIGHT",
                            deviceName = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                        };
                        list.Add(light);
                        break;
                    default:
                        break;
                }




                #region 窗帘
                switch (modal.Modal.Type)
                {
                    case DeviceType.Curtain:
                        DD cu = new DD
                        {
                            deviceId = "CURTAIN_" + modal.HostID + "_" + modal.Modal.ModalAddress,
                            deviceType = "CURTAIN",
                            deviceName = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                        };
                        list.Add(cu);
                        break;
                }
                #endregion

                #region 空调
                switch (modal.Modal.Type)
                {
                    case DeviceType.AirConditioner:
                        DD air = new DD
                        {
                            deviceId = "AIR_" + modal.HostID + "_" + modal.Modal.ModalAddress,
                            deviceType = "AIR",
                            deviceName = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                        };
                        list.Add(air);
                        break;
                }
                #endregion

            }
            #region TCL设备 其实组设备也可以使用
            //获取 组设备
            List<HostModal> TTT = new List<HostModal>();
            var Q = hostModalsGroup.Where(A => A.Modal.MultipleGroupID != 0);
            if (Q.Count() > 0)
            {
                var P = Q.GroupBy(A => A.Modal.MultipleGroupID);

                foreach (var item in P)
                {
                    //获取每一组的数据
                    int ID = item.Key;
                    var ll = item.Select(A => A.Modal.ModalAddress).ToArray();
                    //这个是组名字，每一个数据的组名字都一样的
                    var N1 = item.FirstOrDefault();

                    //每一组的数据
                    HostModal hh = new HostModal();
                    hh.HostID = ID;
                    hh.Modal = new RoomTypeModal();
                    hh.Modal.Name = N1.Modal.MultipleTCLName; ;
                    hh.Modal.Type = N1.Modal.Type;
                    hh.Modal.ModalAddress = string.Join("#", ll);
                    TTT.Add(hh);
                }
            }
            foreach (var item in TTT)
            {
                DD light = new DD
                {
                    deviceId = "LIGHT_" + item.HostID + "_" + item.Modal.ModalAddress,
                    deviceType = "LIGHT",
                    deviceName = ReturnNameByLanguage(item.Modal.Name, item.Modal.EnglishName, item.Modal.TWName),
                };
                list.Add(light);
            }
            #endregion


            #region 情景
            var hhh = hostModals.FirstOrDefault();
            if (hhh != null)
            {
                var typeid = hhh.Modal.RoomType.ID;
                //获取需要控制的场景
                IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == typeid && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                foreach (RoomTypeScene scene in sceneModals)
                {
                    string aliasName = string.IsNullOrEmpty(scene.AliasName) ? scene.Name : scene.AliasName;//获取别名
                    DD sss = new DD
                    {
                        deviceId = "SCENE_" + scene.ID + "_" + scene.GroupAddress,
                        deviceType = "SCENE",
                        deviceName = aliasName
                    };
                    list.Add(sss);
                }
            }
            #endregion

            r1.data = list;

            return Json(r1, JsonRequestBehavior.AllowGet);
        }

        [HttpPost()]
        public ActionResult GetAllDevice(int hostid)
        {
            List<DD> ll = new List<DD>();
            //获取需要控制的设备信息
            IList<HostModal> hostModals = HostModalManager.LoadByHostID(hostid).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
            foreach (HostModal modal in hostModals)
            {
                switch (modal.Modal.Type)
                {
                    case DeviceType.Relay://主机继电器
                    case DeviceType.Dimmer://LED调光
                    case DeviceType.PWMDimmer://PWM调光
                    case DeviceType.PWMExpand://PWM扩展
                    case DeviceType.PBLED:
                    case DeviceType.Traic://可控硅调光
                    case DeviceType.Strip://灯带调光
                    case DeviceType.A9IORelay:
                    case DeviceType.LVout://弱电输出
                    case DeviceType.Expand://扩展继电器
                    case DeviceType.PB20:
                    case DeviceType.PB20_LD:
                    case DeviceType.PB20_LS:
                    case DeviceType.ColorTemp:
                        DD light = new DD
                        {
                            deviceId = "LIGHT_" + modal.HostID + "_" + modal.Modal.ModalAddress,
                            deviceType = "LIGHT",
                            deviceName = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName),
                        };
                        ll.Add(light);
                        break;
                    default:
                        break;
                }
            }
            return Json(ll, JsonRequestBehavior.AllowGet);
        }

        public static string[] controll_all_open = new string[] { "开灯", "打开所有灯", "打开灯", "开灯光", "打开所有灯光", "打开灯光", "打开全开模式", "全开模式" };
        public static string[] controll_all_close = new string[] { "关灯", "关闭所有灯", "关闭灯", "关灯光", "关闭所有灯光", "关闭灯光", "打开全关模式", "全关模式" };

        [HttpPost()]
        public ActionResult ChuangWei_DeviceCommandControl()
        {
            //返回控制结果
            ReturnInfo result = new ReturnInfo();
            result.code = 1;
            result.msg = "执行成功";
            try
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                logger.Error("chuangwei 控制指令为： " + jsonData);
                var UUU = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);

                string Token = "";
                int code = 0;
                string msg = "";
                var AuthData = Request.Headers["Authorization"];
                if (AuthData != null)
                {
                    JWTData JJJ = null;
                    Token = AuthData.ToString();
                    var TuT = SignKeyCommon.TokenValidate(Token, out JJJ, out code, out msg);
                    if (!TuT)
                    {
                        code = 0;
                        result.code = code;
                        result.msg = "Token验证不通过";
                        return Json(result, JsonRequestBehavior.AllowGet);
                    }
                }

                string HotelId = UUU["hotelId"];

                //这里 创维传过来的实际上是房间号
                //真想打死他们啊，在这里 耗费了很久的时间
                string RoomNumber = UUU["roomId"];
                string VoiceCmd = UUU["voiceCmd"];
                string TimeStamp = UUU["timeStamp"];
                //string HotelId = "";
                //string RoomId = "";
                //string VoiceCmd = "";
                //string TimeStamp = "";

                int hid = 0;
                int.TryParse(HotelId, out hid);

                string platformName = "创维电视";
                var request = Newtonsoft.Json.JsonConvert.DeserializeObject<ChuangWeiCommandData>(VoiceCmd);

                var a11 = request.nlp_cmd.data;

                var a22 = JsonConvert.DeserializeObject<List<MessageData>>(a11);
                //这里的 roomid 实际上是 房间号
                //创维文档上写的和实际上不符 
                //是个大坑 
                Host host = HostManager.GetByRoomNumber(RoomNumber, hid);

                if (host == null)
                {
                    result.code = 0;
                    result.msg = "不存在此房间";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                string a = host.SysHotel.ID.ToString();
                string room_number = host.RoomNumber;
                string hotel_code_str = host.SysHotel.Code;

                int hotel_code = 0;
                int.TryParse(hotel_code_str, out hotel_code);

                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {

                    logger.Error("已经过期");
                    result.code = 0;
                    result.msg = "当前酒店已经过期";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

                #region 监控
                string Key = CacheKey.IOTKey;
                bool is_monitor = false;
                var qqq = CSRedisCacheHelper.ForeverGet<List<IOT_Monitor_Host>>(Key);
                if (qqq != null && qqq.Count > 0)
                {
                    var df = qqq.Where(A => A.HotelID.Equals(HotelId) && A.RoomNumber.Equals(host.RoomNumber));
                    if (df.Count() > 0)
                    {
                        is_monitor = true;
                    }
                }
                bool is_online = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
                if (is_monitor)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号:(" + host.RoomNumber + ") is_online: " + is_online.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.Step = 1;
                    i.CreateTime = DateTime.Now;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = HotelId;
                    i.HotelCode = hotel_code;
                    i.RoomNumber = room_number;
                    i.RequestId = "";
                    i.Platform = platformName;
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                #endregion

                if (!is_online)
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");

                    result.code = 0;
                    result.msg = "当前房间主机不在线，无法控制";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }




                bool is_take_card = CheckGetPower(host);

                if (is_monitor)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号：(" + host.RoomNumber + ") 取电: " + is_take_card.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.Step = 2;
                    i.CreateTime = DateTime.Now;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = HotelId;
                    i.HotelCode = hotel_code;
                    i.RoomNumber = room_number;
                    i.RequestId = "";
                    i.Platform = platformName;
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                if (!is_take_card)
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");

                    result.code = 0;
                    result.msg = "当前房间没有取电，不能在这种情况下控制";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

                string query = request.query;

                Device data_return = new Device();

                #region 全开或者全关
                bool b1 = controll_all_open.Contains(query);
                bool b2 = controll_all_close.Contains(query);

                if (b1 || b2)
                {
                    int status = 0;
                    int brightness = 100;

                    var devices1 = new List<RCUHost.Protocols.Device>();
                    var hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.Name.Contains("灯") && r.Modal.WXActiveIndicator).ToList();
                    foreach (HostModal hostModal in hostModals)
                    {
                        switch (hostModal.Modal.Type)
                        {
                            case DeviceType.Relay:
                            case DeviceType.Expand:
                            case DeviceType.Dimmer:
                            case DeviceType.Traic:
                            case DeviceType.Strip:
                            case DeviceType.PWMDimmer:
                            case DeviceType.PWMExpand:
                            case DeviceType.PBLED:
                            case DeviceType.A9IORelay:
                            case DeviceType.PB20:
                            case DeviceType.PB20_LD:
                            case DeviceType.PB20_LS:
                            case DeviceType.ColorTemp:
                                int status1 = hostModal.Status;
                                int brightness1 = hostModal.Brightness;
                                var device = new RCUHost.Protocols.Device();
                                device.Address = hostModal.Modal.ModalAddress;
                                device.AddressType = RCUHost.Protocols.AddressType.DeviceAddress;
                                device.Type = hostModal.Modal.Type;

                                //全开
                                if (b1)
                                {
                                    status = 1;
                                    brightness = 100;
                                }
                                //全关
                                else if (b2)
                                {
                                    status = 2;
                                    brightness = 0;
                                }
                                device.Status = (byte)status;
                                device.Brightness = (byte)brightness;
                                devices1.Add(device);
                                break;
                        }
                    }
                    LightControlManager.AllDeviceControl(host, devices1);
                }
                #endregion

                else
                {
                    foreach (var G_item in a22)
                    {
                        header hh = G_item.header;
                        payload pp = G_item.payload;


                        // id SCENE_15639_0.27.0
                        string deviceIdn = pp.appliance.additionalApplianceDetails.deviceId;
                        string[] mmo = deviceIdn.Split('_');

                        string deviceid = mmo[1];
                        string modalAddress = mmo[2];


                        var Deviceinfo = pp.appliance.additionalApplianceDetails;
                        var TTTy = Deviceinfo.deviceType;
                        var M_DeviceId = Deviceinfo.deviceId;
                        var M_DeviceName = Deviceinfo.deviceName;

                        //消息id
                        string messageid = hh.messageId;


                        if (TTTy.Equals("SCENE"))
                        {
                            #region 情景控制
                            if (hh.name.Equals("TurnOnRequest"))
                            {
                                //var scene = RoomTypeSceneManager.Get(int.Parse(modalAddress));
                                var scene = RoomTypeSceneManager.Get(int.Parse(deviceid));
                                if (scene == null)
                                {
                                    logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的场景，ID：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress, platformName));
                                    return Json("", JsonRequestBehavior.AllowGet);
                                }
                                LightControlManager.ApplyScene(host, scene);

                                if (is_monitor)
                                {
                                    IOTMonitorData i = new IOTMonitorData();
                                    i.Step = 3.1;
                                    i.CreateTime = DateTime.Now;
                                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                    i.TriggerTime = ti;
                                    i.HotelId = HotelId;
                                    i.HotelCode = hotel_code;
                                    i.RoomNumber = room_number;
                                    i.RequestId = "";
                                    i.Platform = platformName;
                                    string sss = string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID);
                                    i.CommandDescription = sss.ToString();
                                    SendMQTTData.Send(i);
                                }
                            }
                            #endregion
                        }
                        else
                        {

                            int status = 0;
                            int brightness = 100;
                            int temperature = 25;
                            int fanSpeed = 1;
                            int mode = 1;
                            int air_value = 0;

                            HostModal item = GetDataFromCache(host, modalAddress);
                            if (item != null)
                            {
                                status = item.Status;
                                mode = item.Mode;
                                temperature = item.SettingTemp;
                                fanSpeed = item.FanSpeed;
                                brightness = item.Brightness;
                                air_value = item.Valve;
                            }

                            if (item != null)
                            {
                                data_return.deviceName = item.Modal.Name;
                                #region 设备控制
                                if (TTTy.Equals("LIGHT"))
                                {
                                    data_return.deviceId = "LIGHT_" + item.HostID + "_" + item.Modal.ModalAddress;
                                    data_return.deviceType = "LIGHT";
                                    if (hh.name.Equals("TurnOnRequest"))
                                    {
                                        status = 1;
                                        brightness = 100;
                                    }
                                    else if (hh.name.Equals("TurnOffRequest"))
                                    {
                                        status = 2;
                                        brightness = 0;
                                    }
                                    else if (hh.name.Equals("SetBrightnessPercentageRequest"))
                                    {
                                        status = 1;
                                        brightness = Convert.ToInt16(pp.brightness.value);
                                    }


                                    else if (hh.name.Equals("IncrementBrightnessPercentageRequest"))//调亮
                                    {
                                        status = 1;
                                        brightness = item.Brightness;
                                        brightness += Convert.ToInt16(pp.brightness.value);
                                        if (brightness > 100)
                                        {
                                            brightness = 100;
                                        }
                                    }
                                    else if (hh.name.Equals("DecrementBrightnessPercentageRequest"))//调暗
                                    {
                                        status = 1;
                                        brightness = item.Brightness;
                                        brightness -= Convert.ToInt16(pp.brightness.value);
                                        if (brightness < 0)
                                        {
                                            brightness = 0;
                                            status = 2;
                                        }
                                    }
                                    else if (hh.name.Equals("SetColorTemperatureRequest"))//设置色温
                                    {
                                        status = 3;
                                        temperature = XiaoDuToBLW(pp.targetTemperature.value);

                                        if (temperature < 0)
                                        {
                                            temperature = 0;
                                        }
                                        else if (temperature > 100)
                                        {
                                            temperature = 100;
                                        }
                                    }
                                    else if (hh.name.Equals("IncrementColorTemperatureRequest")) //调高灯光色温
                                    {
                                        status = 1;
                                        temperature = item.CurrentTemp;
                                        //brightness = item.Brightness;
                                        //temperature = 0;

                                        double GV = 0;
                                        double.TryParse(pp.deltaPercentage.value.ToString(), out GV);
                                        int gh = Convert.ToInt32(GV);

                                        //brightness += Convert.ToInt16(gh);
                                        //if (brightness > 100)
                                        //{
                                        //    brightness = 100;
                                        //}

                                        temperature += Convert.ToInt16(gh);
                                        if (temperature > 100)
                                        {
                                            temperature = 100;
                                        }
                                    }
                                    else if (hh.name.Equals("DecrementColorTemperatureRequest"))//降低灯光色温
                                    {
                                        status = 1;
                                        //temperature = 0;
                                        temperature = item.CurrentTemp;

                                        //brightness = item.Brightness;

                                        double GV = 0;
                                        double.TryParse(pp.deltaPercentage.value.ToString(), out GV);
                                        int gh = Convert.ToInt32(GV);

                                        //brightness -= Convert.ToInt16(gh);
                                        //if (brightness < 0)
                                        //{
                                        //    brightness = 0;
                                        //    status = 2;
                                        //}
                                        temperature -= Convert.ToInt16(gh);
                                        if (temperature < 0)
                                        {
                                            temperature = 0;
                                        }
                                    }
                                    //冷色调
                                    else if (hh.name.Equals("colorTemperatureInKelvin"))
                                    {

                                    }
                                }
                                else if (TTTy.Equals("AIR")) //这里和文档上不一样
                                {
                                    if (hh.name.Equals("TurnOnRequest"))
                                    {
                                        status = 1;
                                        brightness = 100;
                                    }
                                    else if (hh.name.Equals("TurnOffRequest"))
                                    {
                                        status = 2;
                                        brightness = 0;
                                    }
                                    else if (hh.name.Equals("SetTemperatureRequest"))
                                    {
                                        status = 1;
                                        temperature = XiaoDuToBLW(pp.targetTemperature.value);
                                        if (temperature < 16)
                                        {
                                            temperature = 16;
                                        }
                                        else if (temperature > 32)
                                        {
                                            temperature = 32;
                                        }
                                    }
                                    else if (hh.name.Equals("IncrementTemperatureRequest"))
                                    {
                                        status = 1;
                                        temperature = item.SettingTemp;
                                        temperature += Convert.ToInt16(pp.deltaValue.value.ToString());
                                        if (temperature > 32)
                                        {
                                            temperature = 32;
                                        }
                                    }
                                    else if (hh.name.Equals("DecrementTemperatureRequest"))
                                    {
                                        status = 1;
                                        temperature = item.SettingTemp;
                                        temperature -= Convert.ToInt16(pp.deltaValue.value);
                                        if (temperature < 16)
                                        {
                                            temperature = 16;
                                        }
                                    }
                                    else if (hh.name.Equals("SetFanSpeedRequest"))
                                    {
                                        status = 1;
                                        if (pp.fanSpeed.level != null && !string.IsNullOrEmpty(pp.fanSpeed.level))
                                        {
                                            switch (pp.fanSpeed.level.ToLower())
                                            {
                                                case "high":
                                                case "max":
                                                case "高":
                                                    fanSpeed = 3;
                                                    break;
                                                case "middle":
                                                case "中":
                                                    fanSpeed = 2;
                                                    break;
                                                case "auto":
                                                case "自动":
                                                    fanSpeed = 0;
                                                    break;
                                                default:
                                                    fanSpeed = 1;
                                                    break;
                                            }
                                        }
                                        else
                                        {
                                            fanSpeed = Convert.ToInt16(pp.fanSpeed.value);
                                            if (fanSpeed < 1)
                                            {
                                                fanSpeed = 1;
                                            }
                                            else if (fanSpeed > 3)
                                            {
                                                fanSpeed = 3;
                                            }
                                        }
                                    }

                                    else if (hh.name.Equals("IncrementFanSpeedRequest"))
                                    {
                                        status = 1;
                                        fanSpeed = item.FanSpeed;
                                        fanSpeed += Convert.ToInt16(pp.deltaValue.value);
                                        if (fanSpeed > 3)
                                        {
                                            fanSpeed = 3;
                                        }
                                    }
                                    else if (hh.name.Equals("DecrementFanSpeedRequest"))
                                    {
                                        status = 1;
                                        fanSpeed = item.FanSpeed;
                                        fanSpeed -= Convert.ToInt16(pp.deltaValue.value);
                                        if (fanSpeed < 1)
                                        {
                                            fanSpeed = 1;
                                        }
                                    }
                                    else if (hh.name.Equals("SetModeRequest"))
                                    {
                                        status = 1;
                                        mode = ModeToInt(pp.mode.value);
                                        if (mode == -1)
                                        {
                                            //logger.Error(string.Format("{3}(酒店：{0}，房号：{1})不支持该空调模式：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, request.payload.mode.value, platformName));
                                        }
                                    }
                                }
                                else if (TTTy.Equals("CURTAIN"))
                                {
                                    if (hh.name.Equals("TurnOnRequest"))
                                    {
                                        status = 1;
                                        brightness = 100;
                                    }
                                    else if (hh.name.Equals("TurnOffRequest"))
                                    {
                                        status = 2;
                                        brightness = 0;
                                    }
                                    else if (hh.name.Equals("PauseRequest"))
                                    {
                                        status = 6;
                                    }
                                }
                                else
                                {

                                }
                                logger.Error("创维控制指令为:  status: " + status + " brightness: " + item.Brightness);
                                HostModalManager.SetDevice(host, item, status, brightness, temperature, fanSpeed, mode, air_value);
                                #endregion
                            }
                        }
                    }
                }
                result.data = data_return;
            }
            catch (Exception ex)
            {
                result.code = 0;
                result.msg = ex.Message;
                string s = JsonConvert.SerializeObject(result);
                logger.Error("创维控制失败： " + s);
            }

            string sjk = JsonConvert.SerializeObject(result);
            logger.Error("控制结果为: " + sjk);
            return Json(result, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 创建增加的 一键投诉
        /// https://客控IOT后台BaseUrl/sky/api/customer/complaint/
        /// </summary>
        /// <param name="hotelId"></param>
        /// <param name="roomId"></param>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult ChuangWei_TouSu(string hotelId, string roomId, string timeStamp)
        {

            ReturnInfo result = new ReturnInfo();
            result.code = 1;
            result.msg = "执行成功";
            try
            {
                logger.Error("收到创维电视的一键投诉功能 hotelid: " + hotelId + " RoomNum:" + roomId);
                //byte[] byts = new byte[Request.InputStream.Length];
                //Request.InputStream.Read(byts, 0, byts.Length);
                //string jsonData = System.Text.Encoding.UTF8.GetString(byts);
                //logger.Error("chuangwei 控制指令为： " + jsonData);
                //var UUU = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);

                string Token = "";
                int code = 0;
                string msg = "";
                var AuthData = Request.Headers["Authorization"];
                if (AuthData != null)
                {
                    JWTData JJJ = null;
                    Token = AuthData.ToString();
                    var TuT = SignKeyCommon.TokenValidate(Token, out JJJ, out code, out msg);
                    if (!TuT)
                    {
                        code = 0;
                        result.code = code;
                        result.msg = "Token验证不通过";
                        return Json(result, JsonRequestBehavior.AllowGet);
                    }
                }

                //string HotelId = UUU["hotelId"];
                string HotelId = hotelId;

                //这里 创维传过来的实际上是房间号
                //真想打死他们啊，在这里 耗费了很久的时间
                //string RoomNumber = UUU["roomId"];
                string RoomNumber = roomId;
                //string VoiceCmd = UUU["voiceCmd"];
                //string TimeStamp = UUU["timeStamp"];
                string TimeStamp = timeStamp;
                //string HotelId = "";
                //string RoomId = "";
                //string VoiceCmd = "";
                //string TimeStamp = "";

                int hid = 0;
                int.TryParse(HotelId, out hid);

                string platformName = "创维电视";
                //var request = Newtonsoft.Json.JsonConvert.DeserializeObject<ChuangWeiCommandData>(VoiceCmd);

                //var a11 = request.nlp_cmd.data;

                //var a22 = JsonConvert.DeserializeObject<List<MessageData>>(a11);
                //这里的 roomid 实际上是 房间号
                //创维文档上写的和实际上不符 
                //是个大坑 
                Host host = HostManager.GetByRoomNumber(RoomNumber, hid);

                if (host == null)
                {
                    result.code = 0;
                    result.msg = "不存在此房间";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                string a = host.SysHotel.ID.ToString();
                string room_number = host.RoomNumber;
                string hotel_code_str = host.SysHotel.Code;

                int hotel_code = 0;
                int.TryParse(hotel_code_str, out hotel_code);

                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {

                    logger.Error("已经过期");
                    result.code = 0;
                    result.msg = "当前酒店已经过期";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

                #region 监控
                string Key = CacheKey.IOTKey;
                bool is_monitor = false;
                var qqq = CSRedisCacheHelper.ForeverGet<List<IOT_Monitor_Host>>(Key);
                if (qqq != null && qqq.Count > 0)
                {
                    var df = qqq.Where(A => A.HotelID.Equals(HotelId) && A.RoomNumber.Equals(host.RoomNumber));
                    if (df.Count() > 0)
                    {
                        is_monitor = true;
                    }
                }
                bool is_online = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
                if (is_monitor)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号:(" + host.RoomNumber + ") is_online: " + is_online.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.CreateTime = DateTime.Now;
                    i.Step = 1;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = HotelId;
                    i.HotelCode = hotel_code;
                    i.RoomNumber = room_number;
                    i.RequestId = "";
                    i.Platform = platformName;
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                #endregion

                if (!is_online)
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");

                    result.code = 0;
                    result.msg = "当前房间主机不在线，无法控制";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }




                bool is_take_card = CheckGetPower(host);

                if (is_monitor)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号：(" + host.RoomNumber + ") 取电: " + is_take_card.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.CreateTime = DateTime.Now;
                    i.Step = 2;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = HotelId;
                    i.HotelCode = hotel_code;
                    i.RoomNumber = room_number;
                    i.RequestId = "";
                    i.Platform = platformName;
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                if (!is_take_card)
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");

                    result.code = 0;
                    result.msg = "当前房间没有取电，不能在这种情况下控制";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

                //给麦工 宝镜系统推送数据
                string TouSu_URL = host.SysHotel.DeviceStatusPushURL;
                //当设备或服务状态发生变化时，推送给指定的第三方接口
                if ((!string.IsNullOrEmpty(TouSu_URL)))
                {
                    Tuple<string, string, string> tup = new Tuple<string, string, string>(hotel_code_str, RoomNumber, TouSu_URL);
                    Task.Factory.StartNew((tupobj) =>
                    {
                        Tuple<string, string, string> ttt = tupobj as Tuple<string, string, string>;
                        XuanZhuResponse resp = new XuanZhuResponse();
                        resp.code = ttt.Item1;
                        resp.roomNumber = ttt.Item2;
                        resp.address = "004000004";
                        resp.name = "投诉";
                        resp.status = 1;
                        string nnn = Newtonsoft.Json.JsonConvert.SerializeObject(resp);
                        logger.Error("投诉信息给宝镜推送: " + nnn);
                        //XuanZhuOperation.ReportService(ttt.Item3, resp);

                        MyHttp.SendHttpData(ttt.Item3, resp);
                    }, tup);
                }


                int status = 1;
                int brightness = 100;
                //询问过工程部的人，一键投诉的地址是004000004 这是固定的
                HostModal item = GetDataFromCache(host, "004000004");
                HostModalManager.SetDevice(host, item, status, brightness);

                result.code = 200;
                string mmm = host.SysHotel.TouSuResponseData;
                if (!string.IsNullOrEmpty(mmm))
                {
                    result.msg = mmm;
                }
                else
                {
                    result.msg = "您的投诉信息，我们已经收到，会尽快为您处理";
                }

                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("创维电视一键投诉功能异常：" + ex.Message);
                result.code = 500;
                result.msg = "error:" + ex.Message;
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion


        #region 嗨喂语音对接
        /// <summary>
        /// 嗨喂语音对接
        /// </summary>
        /// <returns></returns>
        public ActionResult HaiW()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            try
            {
                logger.Error("HiWei:" + reqData);
                bool isMonitor = true;

                Domain.IoTHiWeiEntity.DiscoverAppliancesRequest request = JsonConvert.DeserializeObject<Domain.IoTHiWeiEntity.DiscoverAppliancesRequest>(reqData);//岚正播放盒语音对接
                string platformName = "嗨喂";
                if (string.IsNullOrEmpty(request.payload.cuid))
                {
                    logger.Error(platformName + "cuid不能为空：" + reqData + "，来自：" + GetClientIP());
                    return Json(ReturnHiWeiError(request.header, "UnexpectedInformationReceivedError"), JsonRequestBehavior.AllowGet);
                }
                Host host = HostManager.GetByHiWeiCUID(request.payload.cuid);//根据播放盒序列号获取对应RCU主机
                if (host == null)
                {
                    logger.Error(platformName + "cuid(" + request.payload.cuid + ")尚未绑定客房主机");
                    return Json(ReturnHiWeiError(request.header, "TargetHardwareMalfunctionError"), JsonRequestBehavior.AllowGet);
                }
                if (DateTime.Now > host.SysHotel.ValidateDate)//酒店已到期
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")已过期");
                    return Json(ReturnHiWeiError(request.header, "ExpiredAccessTokenError"), JsonRequestBehavior.AllowGet);
                }

                string messageid = request.payload.cuid;
                messageid = Guid.NewGuid().ToString("N") + messageid;
                string hotelid = host.SysHotel.ID.ToString();
                int hotelcode = 0;
                int.TryParse(host.SysHotel.Code, out hotelcode);

                string roomno = host.RoomNumber;
                if (isMonitor)
                {
                    IOTMonitorData i = new IOTMonitorData();
                    i.Step = 0;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.CreateTime = DateTime.Now;
                    i.TriggerTime = ti;
                    i.HotelId = hotelid;
                    i.HotelCode = hotelcode;
                    i.RoomNumber = roomno;
                    i.RequestId = messageid;
                    i.Platform = platformName;
                    i.CommandDescription = reqData;
                    SendMQTTData.Send(i);
                }



                bool is_online = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);

                if (isMonitor)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号:(" + host.RoomNumber + ") is_online: " + is_online.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.CreateTime = DateTime.Now;
                    i.Step = 1;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = hotelid;
                    i.HotelCode = hotelcode;
                    i.RoomNumber = roomno;
                    i.RequestId = messageid;
                    i.Platform = platformName;
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                if (!is_online)
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");
                    return Json(ReturnHiWeiError(request.header, "TargetOfflineError"), JsonRequestBehavior.AllowGet);//当技能检测到目标设备没有连接到设备云或者设备云不在线时，会给DuerOS发送TargetOfflineError消息。
                }


                bool is_take_card = CheckGetPower(host);

                if (isMonitor)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号：(" + host.RoomNumber + ") 取电: " + is_take_card.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.CreateTime = DateTime.Now;
                    i.Step = 2;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = hotelid;
                    i.HotelCode = hotelcode;
                    i.RoomNumber = roomno;
                    i.RequestId = messageid;
                    i.Platform = platformName;
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                if (!is_take_card)
                {
                    logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");
                    return Json(ReturnHiWeiError(request.header, "UnsupportedOperationError"), JsonRequestBehavior.AllowGet);
                }
                switch (request.header.@namespace)
                {
                    #region 发现调协
                    case "LZOS.Discovery"://发现设备
                        {

                            //小度精灵统计
                            string KKK = platformName + "Discovery";
                            RCUHost.RCUHostCommon.tools.LanJieData(KKK, host.SysHotel.Code);
                            List<Domain.IoTHiWeiEntity.DiscoveredAppliances> appliances = new List<Domain.IoTHiWeiEntity.DiscoveredAppliances>();

                            //获取需要控制设备的分组信息
                            List<Domain.IoTHiWeiEntity.DiscoveredGroups> groups = new List<Domain.IoTHiWeiEntity.DiscoveredGroups>();
                            List<string> applianceIds = new List<string>();
                            //获取需要控制的场景
                            IList<RoomTypeScene> sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
                            foreach (RoomTypeScene scene in sceneModals)
                            {
                                string aliasName = string.IsNullOrEmpty(scene.AliasName) ? scene.Name : scene.AliasName;//获取别名
                                appliances.Add(new Domain.IoTHiWeiEntity.DiscoveredAppliances
                                {
                                    actions = new List<string> { "turnOn" },
                                    applianceTypes = new List<string> { "SCENE_TRIGGER" },
                                    additionalApplianceDetails = new Dictionary<string, string>() { { "SCENE", "SCENE" } },
                                    applianceId = scene.ID + "&" + "SCENE_TRIGGER",
                                    friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + scene.Name,
                                    friendlyName = scene.Name,
                                    nicknames = new List<string>(aliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)),
                                    manufacturerName = "宝来威(Boonlive)",
                                    modelName = Common.Tools.GetDescription(scene.Type),
                                    version = "V1",
                                    isReachable = true
                                });
                                applianceIds.Add(scene.ID + "&" + "SCENE_TRIGGER");
                            }
                            //场景分组
                            groups.Add(new Domain.IoTHiWeiEntity.DiscoveredGroups
                            {
                                groupId = "1",
                                groupName = "场景",
                                applianceIds = applianceIds,
                                groupNotes = "Boonlive-" + host.SysHotel.Name + "(" + host.RoomNumber + ")" + "场景分组",
                                additionalGroupDetails = new Dictionary<string, string>()
                            });
                            //获取需要控制的设备信息
                            IList<HostModal> hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
                            applianceIds = new List<string>();
                            foreach (HostModal hostModal in hostModals)
                            {
                                List<string> applianceTypes = new List<string>();
                                List<string> actions = new List<string>();
                                switch (hostModal.Modal.Type)
                                {
                                    case DeviceType.Dimmer:
                                    case DeviceType.Traic:
                                    case DeviceType.PWMDimmer:
                                    case DeviceType.PWMExpand:
                                    case DeviceType.PBLED:
                                    case DeviceType.LVout://弱电输出
                                    case DeviceType.Strip://灯带调光
                                    case DeviceType.PB20:
                                    case DeviceType.PB20_LD:
                                    case DeviceType.PB20_LS:
                                        applianceTypes.Add("LIGHT");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setBrightnessPercentage");
                                        actions.Add("incrementBrightnessPercentage");
                                        actions.Add("decrementBrightnessPercentage");
                                        break;
                                    case DeviceType.AirConditioner:
                                        applianceTypes.Add("AIR_CONDITION");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setTemperature");
                                        actions.Add("incrementTemperature");
                                        actions.Add("decrementTemperature");
                                        actions.Add("setFanSpeed");
                                        actions.Add("incrementFanSpeed");
                                        actions.Add("decrementFanSpeed");
                                        actions.Add("setMode");
                                        break;
                                    case DeviceType.Curtain:
                                        if (hostModal.Modal.Name.IndexOf("窗帘") > -1)
                                        {
                                            applianceTypes.Add("CURTAIN");//窗帘
                                        }
                                        else if (hostModal.Modal.Name.IndexOf("窗纱") > -1)
                                        {
                                            applianceTypes.Add("CURT_SIMP");//窗纱
                                        }
                                        else
                                        {
                                            applianceTypes.Add("SWITCH");//卷帘、天幕等
                                        }
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("pause");
                                        actions.Add("continue");
                                        break;
                                    case DeviceType.TV:
                                        applianceTypes.Add("TV_SET");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setTVChannel");
                                        actions.Add("decrementTVChannel");
                                        actions.Add("incrementTVChannel");
                                        actions.Add("returnTVChannel");
                                        actions.Add("setVolume");
                                        actions.Add("setVolumeMute");
                                        actions.Add("incrementVolume");
                                        actions.Add("decrementVolume");
                                        actions.Add("setDirection");
                                        break;
                                    case DeviceType.Music:
                                        applianceTypes.Add("TV_SET");
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        actions.Add("setVolume");
                                        actions.Add("incrementVolume");
                                        actions.Add("decrementVolume");
                                        actions.Add("setVolumeMute");
                                        break;
                                    default:
                                        if (hostModal.Modal.Name.IndexOf("灯") > -1 ||
                                            hostModal.Modal.EnglishName.ToLower().IndexOf("light") > -1 ||
                                            hostModal.Modal.TWName.IndexOf("燈") > -1)
                                        {
                                            applianceTypes.Add("LIGHT");
                                        }
                                        else
                                        {
                                            applianceTypes.Add("SWITCH");
                                        }
                                        actions.Add("turnOn");
                                        actions.Add("turnOff");
                                        break;
                                }
                                appliances.Add(new Domain.IoTHiWeiEntity.DiscoveredAppliances
                                {
                                    actions = actions,
                                    applianceTypes = applianceTypes,
                                    applianceId = hostModal.Modal.ModalAddress + "&" + applianceTypes[0],
                                    additionalApplianceDetails = new Dictionary<string, string>() { { "TYPE", Common.Tools.GetDescription(hostModal.Modal.Type) } },
                                    friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + hostModal.Modal.Name,
                                    friendlyName = hostModal.Modal.Name,
                                    nicknames = new List<string> { hostModal.Modal.Name },
                                    manufacturerName = "宝来威(Boonlive)",
                                    modelName = Common.Tools.GetDescription(hostModal.Modal.Type),
                                    version = "V1",
                                    isReachable = true
                                });
                                applianceIds.Add(hostModal.Modal.ModalAddress + "&" + applianceTypes[0]);
                            }
                            //房间分组
                            groups.Add(new Domain.IoTHiWeiEntity.DiscoveredGroups
                            {
                                groupId = "1",
                                groupName = "房间",
                                applianceIds = applianceIds,
                                groupNotes = "Boonlive-" + host.SysHotel.Name + "(" + host.RoomNumber + ")" + "房间分组",
                                additionalGroupDetails = new Dictionary<string, string>() { }
                            });
                            //找到可控场景和设备，响应小度DuerOS
                            Domain.IoTHiWeiEntity.DiscoverAppliancesResponse response = new Domain.IoTHiWeiEntity.DiscoverAppliancesResponse
                            {
                                header = new Domain.IoTHiWeiEntity.Header
                                {
                                    name = "DiscoverAppliancesResponse",
                                    @namespace = request.header.@namespace,
                                },
                                payload = new Domain.IoTHiWeiEntity.Payload
                                {
                                    discoveredAppliances = appliances,
                                    discoveredGroups = groups
                                }
                            };
                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})本次获取设备数量：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, response.payload.discoveredAppliances.Count.ToString(), platformName));

                            if (isMonitor)
                            {
                                string sss = "发现设备返回";
                                IOTMonitorData i = new IOTMonitorData();
                                i.CreateTime = DateTime.Now;
                                i.Step = 3;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = hotelid;
                                i.HotelCode = hotelcode;
                                i.RoomNumber = roomno;
                                i.RequestId = messageid;
                                i.Platform = platformName;
                                i.CommandDescription = sss;
                                SendMQTTData.Send(i);
                            }
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    #endregion
                    case "LZOS.Control"://控制设备 
                        {

                            //小度精灵统计
                            string KKK = platformName + "Control";
                            RCUHost.RCUHostCommon.tools.LanJieData(KKK, host.SysHotel.Code);
                            bool nnv = !Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);
                            if (nnv)
                            {
                                //logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");
                                return Json(ReturnHiWeiError(request.header, "TargetOfflineError"), JsonRequestBehavior.AllowGet);//当技能检测到目标设备没有连接到设备云或者设备云不在线时，会给DuerOS发送TargetOfflineError消息。
                            }
                            bool nnv1 = !CheckGetPower(host);
                            if (nnv1)
                            {
                                //logger.Error(platformName + "当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");
                                return Json(ReturnHiWeiError(request.header, "UnsupportedOperationError"), JsonRequestBehavior.AllowGet);
                            }
                            string[] applianceIds = request.payload.appliance.applianceId.Split('&');
                            if (applianceIds.Length < 2)
                            {
                                logger.Error(platformName + "applianceId参数有误：" + request.payload.appliance.applianceId);
                                return Json(ReturnHiWeiError(request.header, "UnexpectedInformationReceivedError"), JsonRequestBehavior.AllowGet);
                            }
                            string modalAddress = applianceIds[0];//设备地址或场景ID
                            string applianceTypes = applianceIds[1];//设备类型
                            string confirmationName = "TurnOnConfirmation";
                            Domain.IoTLZEntity.Payload payload = new Domain.IoTLZEntity.Payload();
                            List<Domain.IoTLZEntity.Attributes> attributes = new List<Domain.IoTLZEntity.Attributes>();
                            switch (applianceTypes)
                            {
                                case "SCENE_TRIGGER"://场景控制
                                case "ACTIVITY_TRIGGER":
                                    {
                                        var scene = RoomTypeSceneManager.Get(int.Parse(modalAddress));
                                        if (scene == null)
                                        {
                                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的场景，ID：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress, platformName));
                                            return Json(ReturnHiWeiError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                        }
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "name", value = scene.Name, scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "turnOnState", value = "ON", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        LightControlManager.ApplyScene(host, scene);
                                        SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("SceneControl"), string.Format("打开客房({0})场景：{1}，ID：{2}", host.RoomNumber, scene.Name, scene.ID), true, platformName, host.SysHotel.ID);
                                    }
                                    break;
                                default:
                                    {

                                        if (isMonitor)
                                        {
                                            string sss = "控制设备开始";
                                            IOTMonitorData i = new IOTMonitorData();
                                            i.CreateTime = DateTime.Now;
                                            i.Step = 3.1;
                                            string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                            i.TriggerTime = ti;
                                            i.HotelId = hotelid;
                                            i.HotelCode = hotelcode;
                                            i.RoomNumber = roomno;
                                            i.RequestId = messageid;
                                            i.Platform = platformName;
                                            i.CommandDescription = sss;
                                            SendMQTTData.Send(i);
                                        }
                                        string MKey = "XiaoDuAddress_" + host.ID + "_" + modalAddress;
                                        var ddd = HttpContext.Cache.Get(MKey);
                                        HostModal hostModal = null;
                                        if (ddd != null)
                                        {
                                            hostModal = ddd as HostModal;
                                        }
                                        else
                                        {
                                            hostModal = HostModalManager.GetByModalAddress(host.ID, modalAddress);//设备控制
                                            HttpContext.Cache.Insert(MKey, hostModal, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
                                        }
                                        if (hostModal == null)
                                        {
                                            logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的回路，Address：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, modalAddress, platformName));
                                            return Json(ReturnHiWeiError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                        }
                                        Domain.IoTLZEntity.PreviousState previousState = new Domain.IoTLZEntity.PreviousState();
                                        previousState.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(hostModal.Brightness) };//原来的亮度
                                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                        sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：");
                                        int status = hostModal.Status;
                                        int brightness = hostModal.Brightness;
                                        int temperature = hostModal.SettingTemp;
                                        int fanSpeed = hostModal.FanSpeed;
                                        int mode = hostModal.Mode;
                                        int valve = hostModal.Valve;
                                        switch (request.header.name)
                                        {
                                            case "TurnOnRequest"://打开
                                                confirmationName = "TurnOnConfirmation";
                                                status = 1;
                                                brightness = 100;
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("状态：打开");
                                                break;
                                            case "TurnOffRequest"://关闭                   
                                                confirmationName = "TurnOffConfirmation";
                                                status = 2;
                                                brightness = 0;
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("状态：关闭");
                                                break;
                                            case "SetBrightnessPercentageRequest"://设置亮度
                                                confirmationName = "SetBrightnessPercentageConfirmation";
                                                status = 1;
                                                brightness = Convert.ToInt16(request.payload.brightness.value);
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("亮度：" + brightness);
                                                break;
                                            case "IncrementBrightnessPercentageRequest"://调亮
                                                confirmationName = "IncrementBrightnessPercentageConfirmation";
                                                status = 1;
                                                brightness += Convert.ToInt16(request.payload.deltaPercentage.value);
                                                if (brightness > 100)
                                                {
                                                    brightness = 100;
                                                }
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("调亮：" + request.payload.deltaPercentage.value);
                                                break;
                                            case "DecrementBrightnessPercentageRequest"://调暗
                                                confirmationName = "DecrementBrightnessPercentageConfirmation";
                                                status = 1;
                                                brightness -= Convert.ToInt16(request.payload.deltaPercentage.value);
                                                if (brightness < 0)
                                                {
                                                    brightness = 0;
                                                    status = 2;
                                                }
                                                payload.brightness = new Domain.IoTLZEntity.Brightness() { value = Convert.ToDouble(brightness) };
                                                payload.previousState = previousState;
                                                sb.Append("调暗：" + request.payload.deltaPercentage.value);
                                                break;
                                            case "SetTemperatureRequest"://设置温度
                                                previousState.temperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                confirmationName = "SetTemperatureConfirmation";
                                                status = 1;
                                                temperature = XiaoDuToBLW(request.payload.targetTemperature.value.ToString());
                                                if (temperature < 16)
                                                {
                                                    temperature = 16;
                                                }
                                                else if (temperature > 32)
                                                {
                                                    temperature = 32;
                                                }
                                                payload.targetTemperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                payload.previousState = previousState;
                                                sb.Append("设温：" + temperature);
                                                break;
                                            case "IncrementTemperatureRequest"://调高温度
                                                previousState.temperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                confirmationName = "IncrementTemperatureConfirmation";
                                                status = 1;
                                                temperature += Convert.ToInt16(request.payload.deltaValue.value);
                                                if (temperature > 32)
                                                {
                                                    temperature = 32;
                                                }
                                                payload.targetTemperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                payload.previousState = previousState;
                                                sb.Append("调高温度：" + request.payload.deltaValue.value);
                                                break;
                                            case "DecrementTemperatureRequest"://调低温度
                                                previousState.temperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                confirmationName = "DecrementTemperatureConfirmation";
                                                status = 1;
                                                temperature -= Convert.ToInt16(request.payload.deltaValue.value);
                                                if (temperature < 16)
                                                {
                                                    temperature = 16;
                                                }
                                                payload.targetTemperature = new Domain.IoTLZEntity.Temperature() { value = Convert.ToDouble(temperature) };
                                                payload.previousState = previousState;
                                                sb.Append("调低温度：" + request.payload.deltaValue.value);
                                                break;
                                            case "SetFanSpeedRequest"://设置风速
                                                previousState.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                confirmationName = "SetFanSpeedConfirmation";
                                                status = 1;
                                                if (request.payload.fanSpeed.level != null & !string.IsNullOrEmpty(request.payload.fanSpeed.level))
                                                {
                                                    switch (request.payload.fanSpeed.level.ToLower())
                                                    {
                                                        case "high":
                                                        case "max":
                                                            fanSpeed = 3;
                                                            break;
                                                        case "middle":
                                                            fanSpeed = 2;
                                                            break;
                                                        case "auto":
                                                            fanSpeed = 0;
                                                            break;
                                                        default:
                                                            fanSpeed = 1;
                                                            break;
                                                    }
                                                    sb.Append("设置风速：" + request.payload.fanSpeed.level);
                                                }
                                                else
                                                {
                                                    fanSpeed = Convert.ToInt16(request.payload.fanSpeed.value);
                                                    if (fanSpeed < 1)
                                                    {
                                                        fanSpeed = 1;
                                                    }
                                                    else if (fanSpeed > 3)
                                                    {
                                                        fanSpeed = 3;
                                                    }
                                                    sb.Append("设置风速：" + fanSpeed);
                                                }
                                                payload.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                payload.previousState = previousState;
                                                break;
                                            case "IncrementFanSpeedRequest"://调高风速
                                                previousState.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                confirmationName = "IncrementFanSpeedConfirmation";
                                                status = 1;
                                                fanSpeed += Convert.ToInt16(request.payload.deltaValue.value);
                                                if (fanSpeed > 3)
                                                {
                                                    fanSpeed = 3;
                                                }
                                                payload.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                payload.previousState = previousState;
                                                sb.Append("调高风速：" + request.payload.deltaValue.value);
                                                break;
                                            case "DecrementFanSpeedRequest"://调低风速
                                                previousState.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                confirmationName = "DecrementFanSpeedConfirmation";
                                                status = 1;
                                                fanSpeed -= Convert.ToInt16(request.payload.deltaValue.value);
                                                if (fanSpeed < 1)
                                                {
                                                    fanSpeed = 1;
                                                }
                                                payload.fanSpeed = new Domain.IoTLZEntity.FanSpeed() { value = fanSpeed };
                                                payload.previousState = previousState;
                                                sb.Append("调低风速：" + request.payload.deltaValue.value);
                                                break;
                                            case "SetModeRequest"://设置模式
                                                previousState.mode = new Domain.IoTLZEntity.Mode() { value = ModeToString(mode) };
                                                confirmationName = "SetModeConfirmation";
                                                status = 1;
                                                mode = ModeToInt(request.payload.mode.value);
                                                payload.mode = new Domain.IoTLZEntity.Mode() { deviceType = request.payload.mode.deviceType, value = request.payload.mode.value };
                                                payload.previousState = previousState;
                                                sb.Append("模式：" + request.payload.mode.value);
                                                break;
                                            case "PauseRequest"://暂停
                                                confirmationName = "PauseConfirmation";
                                                status = 6;
                                                sb.Append("状态：暂停");
                                                break;
                                            case "ContinueRequest"://继续
                                                confirmationName = "ContinueConfirmation";
                                                status = 1;
                                                sb.Append("状态：继续");
                                                break;
                                            case "SetTVChannelRequest"://电视跳转频道
                                                confirmationName = "SetTVChannelConfirmation";
                                                status = 4;
                                                int channelNumber = 0;
                                                if (int.TryParse(request.payload.deltaValue.value, out channelNumber))
                                                {
                                                    valve = channelNumber;
                                                }
                                                else
                                                {
                                                    var channel = RoomTypeChannelsManager.LoadAll(host.RoomType.ID).Where(r => r.Name.Contains(request.payload.deltaValue.value)).FirstOrDefault();
                                                    if (channel != null)
                                                    {
                                                        valve = channel.Code;
                                                    }
                                                    else
                                                    {
                                                        logger.Error(string.Format("{3}(酒店：{0}，房号：{1})未找到对应的电视频道：{2}", host.SysHotel.Code + host.SysHotel.Name, host.RoomNumber, request.payload.deltaValue.value, platformName));
                                                        return Json(ReturnHiWeiError(request.header, "UnableToGetValueError"), JsonRequestBehavior.AllowGet);
                                                    }
                                                }
                                                sb.Append("调整频道至：" + valve);
                                                break;
                                            case "IncrementTVChannelRequest"://电视下一频道
                                                confirmationName = "IncrementTVChannelConfirmation";
                                                status = 1;
                                                mode = 5;
                                                sb.Append("频道：加");
                                                break;
                                            case "DecrementTVChannelRequest"://电视上一频道
                                                confirmationName = "DecrementTVChannelConfirmation";
                                                status = 1;
                                                mode = 6;
                                                sb.Append("频道：减");
                                                break;
                                            case "ReturnTVChannelRequest"://返回上一个观看频道
                                                confirmationName = "ReturnTVChannelConfirmation";
                                                status = 1;
                                                mode = 15;
                                                sb.Append("电视：回看");
                                                break;
                                            case "IncrementVolumeRequest"://增大音量
                                                confirmationName = "IncrementVolumeConfirmation";
                                                status = 1;
                                                mode = 3;
                                                sb.Append("音量：加");
                                                break;
                                            case "DecrementVolumeRequest"://减小音量
                                                confirmationName = "DecrementVolumeConfirmation";
                                                status = 1;
                                                mode = 4;
                                                sb.Append("音量：减");
                                                break;
                                            //case "SetVolumeRequest"://设置音量
                                            //    confirmationName = "SetVolumeConfirmation";
                                            //    break;
                                            case "SetVolumeMuteRequest"://设置静音
                                                confirmationName = "SetVolumeMuteConfirmation";
                                                status = 1;
                                                mode = 1;
                                                sb.Append("音量：静音");
                                                break;
                                            default:
                                                return Json(ReturnHiWeiError(request.header, "UnsupportedTargetError"), JsonRequestBehavior.AllowGet);
                                        }
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "name", value = hostModal.Modal.Name, scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        attributes.Add(new Domain.IoTLZEntity.Attributes() { name = "turnOnState", value = status == 1 ? "ON" : "OFF", scale = "", timestampOfSample = Common.TimeHelper.GetCurrentTimestamp(false), uncertaintyInMilliseconds = "10" });
                                        //对房间设备进行操作
                                        HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);


                                        if (isMonitor)
                                        {
                                            IOTMonitorData i = new IOTMonitorData();
                                            i.Step = 0;
                                            string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                            i.CreateTime = DateTime.Now;
                                            i.TriggerTime = ti;
                                            i.HotelId = hotelid;
                                            i.HotelCode = hotelcode;
                                            i.RoomNumber = roomno;
                                            i.RequestId = messageid;
                                            i.Platform = platformName;
                                            i.CommandDescription = reqData;
                                            SendMQTTData.Send(i);
                                        }
                                        SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("DeviceControl"), sb.ToString(), true, platformName, host.SysHotel.ID);
                                    }
                                    break;
                            }
                            payload.attributes = attributes;

                            if (isMonitor)
                            {
                                string sss = "控制设备结束";
                                IOTMonitorData i = new IOTMonitorData();
                                i.CreateTime = DateTime.Now;
                                i.Step = 5;
                                string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                                i.TriggerTime = ti;
                                i.HotelId = hotelid;
                                i.HotelCode = hotelcode;
                                i.RoomNumber = roomno;
                                i.RequestId = messageid;
                                i.Platform = platformName;
                                i.CommandDescription = sss;
                                SendMQTTData.Send(i);
                            }
                            //操作完成响应小度
                            Domain.IoTLZEntity.ControlAppliancesResponse response = new Domain.IoTLZEntity.ControlAppliancesResponse
                            {
                                header = new Domain.IoTLZEntity.Header
                                {
                                    @namespace = request.header.@namespace,
                                    name = confirmationName
                                },
                                payload = payload
                            };
                            return new ContentResult
                            {
                                Content = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(response),
                                ContentType = "application/json"
                            };
                        }
                    default:
                        return Json(ReturnHiWeiError(request.header, "UnsupportedTargetError"), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("处理嗨喂播放盒命令异常，数据：{0}，异常：{1}", reqData, ex.ToString()));
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 返回错误信息
        /// </summary>
        /// <param name="header"></param>
        /// <param name="errorName"></param>
        /// <returns></returns>
        private Domain.IoTLZEntity.ErrorResponse ReturnHiWeiError(Domain.IoTHiWeiEntity.Header header, string errorName)
        {
            Domain.IoTLZEntity.ErrorResponse err = new Domain.IoTLZEntity.ErrorResponse
            {
                header = new Domain.IoTLZEntity.Header
                {
                    @namespace = header.@namespace,
                    name = errorName
                },
                payload = new Domain.IoTLZEntity.Payload { }
            };
            return err;
        }
        #endregion


        //public static string HiWeiKey = "HiWei_";
        //public static string HiWeiAppId = ConfigurationManager.AppSettings["HiWeiAppId"].ToString();
        //public static string HiWeiAppSecret = ConfigurationManager.AppSettings["HiWeiAppSecret"].ToString();

        //[HttpGet()]
        //public ActionResult HiWeiOAuthRequest(string response_type, string client_id, string client_secret, string redirect_uri)
        //{
        //    try
        //    {
        //        Random r = new Random();
        //        int code = r.Next(1, 10000);
        //        string id = HiWeiAppId;
        //        string secret = HiWeiAppSecret;
        //        string Key = HiWeiKey + code;
        //        if (response_type.Equals("code") && client_id.Equals(id) && client_secret.Equals(secret))
        //        {
        //            var t1 = Guid.NewGuid().ToString();
        //            var t2 = Guid.NewGuid().ToString();

        //            var t3 = Guid.NewGuid().ToString();
        //            var t4 = Guid.NewGuid().ToString();
        //            var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(t1 + "###" + t2));
        //            var reftoken = Convert.ToBase64String(Encoding.UTF8.GetBytes(t3 + "###" + t4));

        //            HiWeiToken g = new HiWeiToken();
        //            g.access_token = token;
        //            g.refresh_token = reftoken;
        //            g.expires_in = new TimeSpan(20, 0, 0).TotalSeconds;

        //            CSRedisCacheHelper.Set_PartitionWithTime<HiWeiToken>(Key, g, 3);

        //            var client1 = new RestClient(redirect_uri);
        //            var request1 = new RestRequest("", Method.POST);

        //            request1.AddParameter("code", code);
        //            var QQQ = client1.Execute(request1);
        //            HttpStatusCode HHH = QQQ.StatusCode;
        //        }
        //        else
        //        {
        //            return Json(new { Result = false, Msg = "Fault" }, JsonRequestBehavior.AllowGet);//该消息表示请求消息中access token过期，不能使用。
        //        }
        //        return Json(new { Result = true, Msg = "Success" }, JsonRequestBehavior.AllowGet);//该消息表示请求消息中access token过期，不能使用。
        //    }
        //    catch (Exception)
        //    {
        //        return Json(new { Result = false, Msg = "Fault" }, JsonRequestBehavior.AllowGet);//该消息表示请求消息中access token过期，不能使用。
        //    }
        //}

        //[HttpPost()]
        //public ActionResult gettoken()
        //{
        //    try
        //    {
        //        string code = Request.Form["code"].ToString();
        //        string Key = HiWeiKey + code;
        //        var hi = CSRedisCacheHelper.Get_Partition<HiWeiToken>(Key);

        //        if (hi != null)
        //        {
        //            return Json(hi, JsonRequestBehavior.AllowGet);
        //        }
        //        else
        //        {

        //            return Json(new { Result = false, Msg = "没有授权" }, JsonRequestBehavior.AllowGet);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return Json(ex.Message, JsonRequestBehavior.AllowGet);
        //    }
        //}


        /// <summary>
        /// ETV-艺龙酒店(绥化北林店)728893
        /// 授权接口
        /// </summary>
        /// <returns></returns>
        [HttpPost()]
        public ActionResult ETV_Auth()
        {
            Request.InputStream.Position = 0;
            byte[] reqBody = new byte[Request.InputStream.Length];
            Request.InputStream.Read(reqBody, 0, reqBody.Length);
            string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
            var ttt = JsonConvert.DeserializeObject<TV_AuthData>(reqData);

            //clientId：        a6f3270f77b545a087daa1caed816b3b
            //clientSecret：8854e0b8261b49d6989b5b2f39bd157a
            if (ttt.clientId.Equals("a6f3270f77b545a087daa1caed816b3b") && ttt.clientSecret.Equals("8854e0b8261b49d6989b5b2f39bd157a"))
            {
                var token = Guid.NewGuid().ToString("N");
                string kkk = "ETVKey";
                CSRedisCacheHelper.Set_PartitionWithTime(kkk, token, 7 * 24 * 60, 5);

                TV_ResponseData c = new TV_ResponseData();
                c.code = 200;
                c.msg = null;
                c.data = new TTT_Data()
                {
                    token = token,
                    expiresIn = 7 * 24 * 60 * 60
                };
                //{
                //    "code": 200,
                //    "msg": null,
                //    "data": {
                //        "token": "74b87337454200d4d33f80c4663dc5e5",
                //        "expiresIn": 154589
                //    }
                //}

                return Json(c, JsonRequestBehavior.AllowGet);
            }
            else
            {

                TV_ResponseData c = new TV_ResponseData();
                c.code = 500;
                c.msg = "鉴权数据错误";
                c.data = null;
                return Json(c, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 两天时间要对接完，时间紧迫，数据先写死
        /// </summary>
        public static Dictionary<string, string> ETVDic = new Dictionary<string, string>()
        {
            //艺龙酒店（绥化北林万达广场店）
            {"1668326697184","1213"}
        };
        public class GGG
        {
            public string DeviceName { get; set; }
            public string Address { get; set; }
        }

        [HttpPost()]
        public ActionResult ETV_Controller()
        {
            try
            {
                string IP = "";
                string PPP = Request.UserHostAddress;
                string III = Request.ServerVariables["REMOTE_ADDR"];
                if (string.IsNullOrEmpty(III))
                {
                    IP = PPP;
                }
                else
                {
                    IP = III;
                }
                var token = Request.Headers["Authorization"];
                string kkk = "ETVKey";
                var t_take = CSRedisCacheHelper.Get_Partition<string>(kkk, 5);
                //t_take = "abc";
                if (t_take == null || !t_take.Equals(token))
                {
                    return Json(new { code = 500, msg = "token已经过期" }, JsonRequestBehavior.AllowGet);
                }
                Request.InputStream.Position = 0;
                byte[] reqBody = new byte[Request.InputStream.Length];
                Request.InputStream.Read(reqBody, 0, reqBody.Length);
                string reqData = System.Text.Encoding.UTF8.GetString(reqBody);

                var ttt = JsonConvert.DeserializeObject<ETV_ControllerData>(reqData);

                string hotelid_WANBU = ttt.hotelId;

                //var hotelid = ETVDic[hotelid_WANBU];
                string hotelid = "";
                int hotelid_int = 0;
                //int.TryParse(hotelid, out hotelid_int);

                SysHotel hotel_sys = null;
                string KKKHotel = "HotelInfoETV_" + hotelid_WANBU;
                var hotel_ooo = HttpContext.Cache.Get(KKKHotel);
                if (hotel_ooo != null)
                {
                    hotel_sys = hotel_ooo as SysHotel;
                }
                else
                {
                    hotel_sys = SysHotelManager.GetByETV_HotelId(hotelid_WANBU);
                    HttpContext.Cache.Insert(KKKHotel, hotel_sys, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0));
                }
                if (hotel_sys != null)
                {
                    hotelid_int = hotel_sys.ID;
                    hotelid = hotel_sys.ID.ToString();
                }
                else
                {
                    return Json(new { code = 500, msg = "找不到此酒店" }, JsonRequestBehavior.AllowGet);//"小度音箱(" + request.payload.cuid + ")尚未绑定客房主机"
                }

                string msgid = Guid.NewGuid().ToString("N");
                string roomNo = ttt.roomNo;
                string traceId = ttt.traceId;
                string domain = ttt.domain;
                string intent = ttt.intent;
                List<ETV_CanShu> slots = ttt.slots;


                bool is_monitor = true;
                if (is_monitor)
                {
                    IOTMonitorData i = new IOTMonitorData();
                    i.RemoteIP = IP;
                    i.Step = 0;
                    string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.CreateTime = DateTime.Now;
                    i.TriggerTime = ti;
                    i.HotelId = hotelid;
                    i.HotelCode = int.Parse(hotel_sys.Code);
                    i.RoomNumber = roomNo;
                    i.RequestId = msgid;
                    i.Platform = "ETV";
                    i.CommandDescription = reqData;
                    SendMQTTData.Send(i);
                }
                Host host = null;
                string ETVKongZhiKey = CacheKey.ETV_YuYin + "_" + hotelid + "_" + roomNo;
                var UXV = HttpContext.Cache.Get(ETVKongZhiKey);
                if (UXV != null)
                {
                    host = UXV as Host;
                }
                else
                {
                    // host = HostManager.GetByXiaoDuCUID(XiaoDuCUID);//根据小度音箱序列号获取对应RCU主机  
                    host = HostManager.GetByRoomNumber(roomNo, hotelid_int);
                    if (host != null)
                    {
                        string code = host.SysHotel.Code;
                        string roomno = host.RoomNumber;
                        HttpContext.Cache.Insert(ETVKongZhiKey, host, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration);
                    }
                }

                if (host == null)
                {
                    return Json(new { code = 500, msg = "找不到此房间" }, JsonRequestBehavior.AllowGet);//"小度音箱(" + request.payload.cuid + ")尚未绑定客房主机"
                }

                int hotelcode = 0;
                int.TryParse(host.SysHotel.Code, out hotelcode);

                bool is_online = Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC);

                if (true)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号:(" + host.RoomNumber + ") is_online: " + is_online.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.ControlClass = ControlClass_KongZhiSheBei;
                    i.Step = 1;
                    i.CreateTime = DateTime.Now;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = hotelid;
                    i.HotelCode = int.Parse(host.SysHotel.Code);
                    i.RoomNumber = roomNo;
                    i.RequestId = msgid;
                    i.Platform = "ETV";
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                if (!is_online)
                {
                    logger.Error("ETV当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")不在线");
                    return Json(new { code = 500, msg = "当前客户已经离线" }, JsonRequestBehavior.AllowGet);
                }


                bool is_take_card = CheckGetPower(host);

                if (true)
                {
                    string sss = "酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")房间号：(" + host.RoomNumber + ") 取电: " + is_take_card.ToString();
                    IOTMonitorData i = new IOTMonitorData();
                    i.Step = 2;
                    i.CreateTime = DateTime.Now;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.TriggerTime = ti;
                    i.HotelId = hotelid;
                    i.HotelCode = hotelcode;
                    i.RoomNumber = roomNo;
                    i.RequestId = msgid;
                    i.Platform = "ETV";
                    i.CommandDescription = sss;
                    SendMQTTData.Send(i);
                }
                if (!is_take_card)
                {
                    logger.Error("ETV当前访问酒店(" + host.SysHotel.Name + host.SysHotel.Code + ")客房rcu(" + host.RoomNumber + ")尚未取电");
                    return Json(new { code = 500, msg = "只有取电后才能控制" }, JsonRequestBehavior.AllowGet);
                }

                IList<HostModal> hostModals = null;

                string Hkey = "ETVIOT_" + host.ID;
                var dataH = HttpContext.Cache.Get(Hkey);
                if (dataH != null)
                {
                    hostModals = dataH as IList<HostModal>;
                }
                else
                {
                    hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).ToList();
                    if (hostModals != null && hostModals.Count > 0)
                    {
                        HttpContext.Cache.Insert(Hkey, hostModals, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
                    }
                }

                List<GGG> lla = new List<GGG>();
                // hostmodal只需要 address 和type
                // device.Address = hostModal.Modal.ModalAddress;
                // device.Type = hostModal.Modal.Type
                if (intent.Equals("IOT.Light") || intent.Equals("IOT.Switch") || intent.Equals("IOT.Curtain"))
                {
                    foreach (var item in slots)
                    {
                        var action = item.action;
                        var name = item.applianceName;
                        var area = item.area;
                        List<HostModal> q1 = new List<HostModal>();
                        if (name.Equals("灯"))
                        {
                            q1 = hostModals.Where(A => A.Modal.Name.Contains("灯")).ToList();
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(area))
                            {
                                name = area + name;
                            }
                            q1 = hostModals.Where(A => A.Modal.Name.Equals(name) || A.Modal.AliasName.Equals(name)).ToList();
                        }
                        if (q1 != null && q1.Count > 0)
                        {
                            foreach (var item_inter in q1)
                            {
                                int status = 0;
                                int brightness = 0;
                                if (action.Equals("TurnOnRequest"))
                                {
                                    status = 1;
                                    brightness = 100;
                                }
                                else if (action.Equals("TurnOffRequest"))
                                {
                                    status = 2;
                                    brightness = 0;
                                }
                                Thread.Sleep(50);
                                GGG vva = new GGG() { DeviceName = item_inter.Modal.Name, Address = item_inter.Modal.ModalAddress };

                                lla.Add(vva);
                                HostModalManager.SetDevice(host, item_inter, status, brightness);
                            }
                        }
                    }
                }
                if (intent.Equals("IOT.AirCondition"))
                {
                    foreach (var item in slots)
                    {
                        var action = item.action;
                        var name = item.applianceName;
                        var area = item.area;
                        var value = item.value;
                        if (!string.IsNullOrEmpty(area))
                        {
                            name = area + name;
                        }

                        var q1 = hostModals.Where(A => A.Modal.Type == DeviceType.AirConditioner && (A.Modal.Name.Equals(name) || A.Modal.AliasName.Equals(name)));
                        foreach (var item_inter in q1)
                        {
                            int status = 0;
                            int temperature = 25;
                            int fanSpeed = 0;
                            int mode = 0;
                            int dianci_famen = 0;
                            int brightness = 0;
                            if (action.Equals("TurnOnRequest"))
                            {
                                status = 1;
                            }
                            if (action.Equals("TurnOffRequest"))
                            {
                                status = 2;
                            }
                            if (action.Equals("setTemperature"))
                            {
                                int v = 25;
                                int.TryParse(value, out v);
                                temperature = v;
                            }
                            if (action.Equals("setFanSpeed"))
                            {
                                //value=high（高），middle（中），low（低），auto（自动）
                                //空调风速：自动0,低1,中2,高3
                                if (value.Equals("high"))
                                {
                                    fanSpeed = 3;
                                }
                                else if (value.Equals("middle"))
                                {
                                    fanSpeed = 2;
                                }
                                else if (value.Equals("low"))
                                {
                                    fanSpeed = 1;
                                }
                                else if (value.Equals("auto"))
                                {
                                    fanSpeed = 0;
                                }
                            }
                            if (action.Equals("setMode"))
                            {
                                //value=cool（制冷），heat（制热），fan=（通风），auto（自动）
                                //自动0，制冷1，制热2，送风3
                                if (value.Equals("cool"))
                                {
                                    mode = 1;
                                }
                                else if (value.Equals("heat"))
                                {
                                    mode = 2;
                                }
                                else if (value.Equals("fan"))
                                {
                                    mode = 3;
                                }
                                else if (value.Equals("auto"))
                                {
                                    mode = 0;
                                }
                            }
                            HostModalManager.SetDevice(host, item_inter, status, brightness, temperature, fanSpeed, mode);
                        }
                        if (q1 != null)
                        {
                        }
                    }
                }
                if (intent.Equals("IOT.SceneTrigger"))
                {

                    foreach (var item in slots)
                    {
                        var action = item.action;
                        var name = item.applianceName;
                        var area = item.area;
                        int hid = int.Parse(hotelid);
                        if (!string.IsNullOrEmpty(area))
                        {
                            name = area + name;
                        }
                        var scene = RoomTypeSceneManager.LoadAll().Where(A => A.HotelID == hid && A.Name.Equals(name)).FirstOrDefault();
                        if (scene != null)
                        {
                            if (action.Equals("TurnOnRequest"))
                            {
                                LightControlManager.ApplyScene(host, scene);
                            }
                            if (action.Equals("TurnOffRequest"))
                            {
                                LightControlManager.ApplyScene(host, scene);
                            }
                        }
                    }
                }
                if (is_monitor)
                {
                    IOTMonitorData i = new IOTMonitorData();
                    i.Step = 4;
                    string ti = CPUData.GetNowPrecise().ToString("yyyy-MM-dd HH:mm:ss.ffffff");
                    i.CreateTime = DateTime.Now;
                    i.TriggerTime = ti;
                    i.HotelId = hotelid;
                    i.HotelCode = hotelcode;
                    i.RoomNumber = roomNo;
                    i.RequestId = msgid;
                    i.Platform = "ETV";

                    i.CommandDescription = "success: 控制设备" + JsonConvert.SerializeObject(lla);
                    SendMQTTData.Send(i);
                }
                return Json(new { code = 200, msg = "控制成功" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
    }
    public class ETV_ControllerData
    {
        public string hotelId { get; set; }
        public string roomNo { get; set; }
        public string traceId { get; set; }
        public string domain { get; set; }
        public string intent { get; set; }
        public List<ETV_CanShu> slots { get; set; }
    }
    public class ETV_CanShu
    {
        public string applianceType { get; set; }
        public string action { get; set; }
        public string applianceName { get; set; }
        public string value { get; set; }
        public string area { get; set; }
    }
    public class TV_ResponseData
    {
        public int code { get; set; }
        public object msg { get; set; }
        public TTT_Data data { get; set; }
    }
    public class TTT_Data
    {
        public string token { get; set; }
        /// <summary>
        /// 时间为秒
        /// </summary>
        public long expiresIn { get; set; }
    }
    public class TV_AuthData
    {
        public string clientId { get; set; }
        public string clientSecret { get; set; }
    }
    public class HiWeiToken
    {
        public string access_token { get; set; }
        public string refresh_token { get; set; }
        public double expires_in { get; set; }
    }
    public class DD
    {
        public string deviceId { get; set; }

        public string deviceType { get; set; }

        public string deviceName { get; set; }
    }
    public class Device
    {
        public string deviceType { get; set; }
        public string type { get; set; }
        public string deviceId { get; set; }
        public string deviceName { get; set; }
    }
    public class Appliance
    {
        public string applianceId { get; set; }
        public Device additionalApplianceDetails { get; set; }
    }
    public class header
    {
        public string messageId { get; set; }
        public string @namespace { get; set; }
        public string name { get; set; }
        public string payloadVersion { get; set; }
    }
    public class payload
    {
        public string accessToken { get; set; }
        public Appliance appliance { get; set; }
        public LiangDu brightness { get; set; }
        public WenDu targetTemperature { get; set; }
        public WenDu deltaValue { get; set; }
        public FengSu fanSpeed { get; set; }
        public MoShi mode { get; set; }
        public SeWen deltaPercentage { get; set; }
    }
    public class SeWen
    {
        public string value { get; set; }
    }

    public class MoShi
    {
        public string value { get; set; }
    }
    public class FengSu
    {
        public string level { get; set; }
        public int value { get; set; }
    }
    public class WenDu
    {
        public string value { get; set; }
    }
    public class LiangDu
    {
        public double value { get; set; }
    }
    public class MessageData
    {
        public header header { get; set; }
        public payload payload { get; set; }
    }
    public class chuangweidata
    {
        //public List<MessageData> data { get; set; }
        public string data { get; set; }
    }
    public class ChuangWeiCommandData
    {
        public string nlp_namespace { get; set; }
        public string nlp_name { get; set; }
        public string query { get; set; }
        public chuangweidata nlp_cmd { get; set; }
        public string cuid { get; set; }
        public PackageData resourcePackage { get; set; }
    }
    public class PackageData
    {
        public string skillTitle { get; set; }
        public string domain { get; set; }
        public int aiState { get; set; }
        public string voiceprint { get; set; }
        public string skillSource { get; set; }
        public string tips { get; set; }
    }

    public class ChuangWeiControlData
    {
        public string hotelId { get; set; }
        public string roomId { get; set; }
        public string timeStamp { get; set; }
        public string voiceCmd { get; set; }
    }
}
