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();
}
///
/// 如果存在取电服务记录,且不是打开状态,则返回false,不可控制设备(除了空调),不存在取电服务,可以控制
///
///
///
private bool CheckGetPower(Host host)
{
bool Result = BBB(host);
try
{
string KKK1 = CacheKey.TakeCardOnLine + "_" + host.HostNumber;
CommonEntity.DataTongJi.MTakeCardData Chaka = CSRedisCacheHelper.Get_Partition(KKK1, 5);
if (Chaka != null)
{
string KeyFilter1 = "NEWDiff";
string KeyFilter2 = "OLDDiff";
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);
}
Result = Result || Chaka.Status == 0x01;
if (Result == true)
{
return true;
}
}
}
catch (Exception ex)
{
logger.Error("取电数据不同" + ex.Message);
}
return Result;
}
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(KKey);
if (hostModal == null)
{
return false;
}
if (hostModal != null && hostModal.Status != 1)
{
return false;
}
return true;
}
public static List ButString = new List() { 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);
}
///
/// 小度对接
///
///
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(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>(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 appliances = new List();
//获取需要控制设备的分组信息
List groups = new List();
List applianceIds = new List();
//获取需要控制的场景
IList 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 { "turnOn" },
applianceTypes = new List { "SCENE_TRIGGER" },
additionalApplianceDetails = new Dictionary() { { "TYPE", "SCENE_TRIGGER" } },
applianceId = scene.ID.ToString(),
friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + scene.Name,
friendlyName = scene.Name,
nicknames = new List(aliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)), //new List { 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()
});
applianceIds = new List();
//获取需要控制的设备信息
IList hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
#region TCL设备 其实组设备也可以使用
//获取 组设备
List TTT = new List();
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 applianceTypes = new List();
List actions = new List();
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.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() { { "TYPE", applianceTypes[0] } },
applianceId = hostModal.Modal.ModalAddress,
friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + hostModal.Modal.Name,
friendlyName = hostModal.Modal.Name,
nicknames = new List(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() { "turnOn", "turnOff", "setBrightnessPercentage", "incrementBrightnessPercentage", "decrementBrightnessPercentage" },
applianceTypes = new List() { "LIGHT" },
additionalApplianceDetails = new Dictionary() { { "TYPE", "LIGHT" } },
applianceId = "000000001",
friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->所有灯",
friendlyName = "所有灯",
//nicknames = new List { "所有灯", "打开灯", "关闭灯", "开灯", "关灯", "灯" },
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() { }
});
//找到可控场景和设备,响应小度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 attributes = new List();
if (modalAddress.StartsWith("00000000"))//所有灯控制
{
#region 所有灯控制
var devices = new List();
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 devicelist = new List();
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;
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"://设置亮度
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"://调亮
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 (hostModal.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_L = new List();
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(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(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(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()
{
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
{
//对房间设备进行操作
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);
}
}
///
/// 查询小度并且入库
///
///
///
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(KKA, XiaoDuCUID, 120);
HttpContext.Cache.Insert(XiaoDuKongZhiKey, host, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration);
}
}
return host;
}
///
/// TCL
///
///
///
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(KKA, TCLCUID, 120);
HttpContext.Cache.Insert(XiaoDuKongZhiKey, host, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration);
}
}
return host;
}
///
/// 从缓存中取出数据
///
///
///
///
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(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;
}
///
/// 返回错误信息
///
///
///
///
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;
}
///
/// 空调模式转换
///
///
///
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;
}
///
/// 空调模式转换
///
///
///
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;
}
///
/// 小度类型转换
///
///
///
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(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 data = new List();
//获取需要控制的场景
IList 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 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(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(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 data = new List();
if (null == request.data || request.data.Count == 0)
{
//获取需要控制的设备信息
IList 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语音对接(飞响电视)
///
/// DUI语音对接:主动上报ApiKey:b4b4c81c01e446b4b40f85b196c6aaec
///
///
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(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 appliances = new List();
List applianceIds = new List();
//获取需要控制的场景
IList 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(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 { "turnOn" },
additionalApplianceDetails = new Dictionary()
});
applianceIds.Add(scene.ID + "&" + "SCENE_TRIGGER");
}
//获取需要控制的设备信息
IList hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
applianceIds = new List();
foreach (HostModal hostModal in hostModals)
{
string applianceType;
List actions = new List();
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(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()
});
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);
}
}
///
/// Dui平台增量型转换
///
///
///
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);
}
}
///
/// 返回错误信息
///
///
///
///
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 华为大屏智能家居对接
///
/// 华为设备获取技能
///
///
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(reqData);//得到华为请求
//var hosts = HostManager.LoadAll("1003").ToList();//指定酒店,同步设备技能
var host = HostManager.GetByHuaWeiCUID(_huawei_cuid);//获取按配置的主机的技能
List data = new List();
if (host != null)//foreach (Host host in hosts)
{
//获取需要控制的场景
List sceneRuleList = new List();
IList 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 payload = new List();
IList 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 deviceList = new List();
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);
}
}
///
/// 华为设备意图请求控制
///
///
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(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 飞尔智能(科大讯飞)对接
///
/// 飞尔智能(科大讯飞)对接
///
///
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(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 岚正播放盒语音对接
///
/// 岚正播放盒语音对接
///
///
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(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 appliances = new List();
//获取需要控制设备的分组信息
List groups = new List();
List applianceIds = new List();
//获取需要控制的场景
IList 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 { "turnOn" },
applianceTypes = new List { "SCENE_TRIGGER" },
additionalApplianceDetails = new Dictionary() { { "SCENE", "SCENE" } },
applianceId = scene.ID + "&" + "SCENE_TRIGGER",
friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + scene.Name,
friendlyName = scene.Name,
nicknames = new List(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()
});
//获取需要控制的设备信息
IList hostModals = HostModalManager.LoadByHostID(host.ID).Where(r => r.Modal.WXActiveIndicator).OrderBy(r => r.Modal.Type).ToList();
applianceIds = new List();
foreach (HostModal hostModal in hostModals)
{
List applianceTypes = new List();
List actions = new List();
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() { { "TYPE", Common.Tools.GetDescription(hostModal.Modal.Type) } },
friendlyDescription = "Boonlive->" + host.SysHotel.Name + "->" + host.RoomNumber + "->" + hostModal.Modal.Name,
friendlyName = hostModal.Modal.Name,
nicknames = new List { 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() { }
});
//找到可控场景和设备,响应小度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 attributes = new List();
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);
}
}
///
/// 返回错误信息
///
///
///
///
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
*/
///
/// 小米小爱音箱对接
///
///
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(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
*/
///
/// 天猫精灵音箱对接
///
///
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(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>(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 groups = new List();
List sceneModes = new List();
List devices = new List();
Domain.IoTAliGenieEntity.DevicesItem devicesItem;
//获取需要控制的场景,通过api推送:https://openapi.aligenie.com/v1.0/ip/importHotelConfig
IList sceneModals = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == host.RoomType.ID && r.ActiveIndicator).OrderBy(r => r.Sort).ToList();
//List rcuCustomScenes = new List();
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 corpusList = new List() { item.Name, "打开" + item.Name };
if (!string.IsNullOrEmpty(scene.AliasName))
{
corpusList.Add(scene.AliasName);//别名不为空才添加
//item.CorpusList = new List(scene.AliasName.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));//别名不为空才添加
}
item.CorpusList = corpusList;
item.isDisplayScreen = 1;
sceneModes.Add(item);// 同步技能上报
}
//获取需要控制的设备信息
IList 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.AliasName))
{
devicesItem.aliasList = new List(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 lli = new List();
var devices = new List();
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"://调光
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(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 miaoll = new List();
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() }
};
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);
}
}
///
/// 返回天猫精灵错误
///
///
///
///
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电视机对接(华视美达电视)
///
/// OpenAI电视机对接
/// APPID:ca4jsq4h
/// appsecrect:fd56ae71e3d34b9f94b3378a99170af4
///
///
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(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);
}
}
///
/// 返回
///
///
///
///
///
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遥控器
///
/// http://api?userId=13000000000&roomNum=8002&command="温度+"&mode="空调温度加"×tamp=1686800490&sign=
///
///
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(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);
}
}
///
///
///
/// 0成功,-1失败
/// 失败原因
///
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 创维电视对接
///
/// 酒店列表
///
///
[HttpGet()]
public ActionResult ChuangWei_HotelInfo()
{
ReturnInfo r = new ReturnInfo();
r.code = 200;
string msg = "查询成功";
int code = 200;
r.msg = msg;
IList