using System;
using System.Collections.Generic;
using System.Text;
using HDL_ON.Entity;
using HDL_ON.UI;
using Shared;
namespace HDL_ON.DriverLayer
{
///
/// 通讯方式
///
public enum CommunicationMode
{
none,
///
/// 本地udp
///
local_BusUdp,
///
/// 本地tcp客户端
///
tcp_local_client,
}
public class Control
{
static Control _control;
public static Control Ins
{
get
{
if (_control == null)
{
_control = new Control();
}
return _control;
}
}
///
/// 记录接收到的消息,方便zb的工程师调试他们的设备
///
public List MsgInfoList = new List();
int _msg_id = 1;
///
/// 通讯ID
///
public int msg_id
{
get
{
return _msg_id++;
}
}
/////
///// 获取13位时间戳
/////
/////
//public string Get_TimeStamp()
//{
// long t = DateTime.Now.Ticks / 10000;
// return t.ToString();
//}
///
/// 是否搜索本地网关成功
///
public bool IsSearchLocalGatewaySuccessful = false;
///
/// 是否本地加密,目前只对A网关有用
///
public bool IsLocalEncrypt;
///
/// 判断是否本地加密并且加密key不为空
///
public bool IsLocalEncryptAndGetAesKey {
get {
return IsLocalEncrypt && (!string.IsNullOrEmpty(DB_ResidenceData.Instance.CurrentRegion.localSecret));
}
}
bool _GatewayOnline_Local = false;
///
/// 网关在线-局域网
///
public bool GatewayOnline_Local
{
get
{
return _GatewayOnline_Local;
}
set
{
if (_GatewayOnline_Local != value)
{
_GatewayOnline_Local = value;
if (value)
{
//修改主页连接状态
HomePage.LoadEvent_CheckLinkStatus();
MainPage.Log($"网关局域网在线,刷新设备状态");
new System.Threading.Thread(() =>
{
System.Threading.Thread.Sleep(1000);
FunctionList.List.ReadAllFunctionStatus();
})
{ IsBackground = true, Priority = System.Threading.ThreadPriority.AboveNormal }.Start();
}
else
{
//修改主页连接状态
HomePage.LoadEvent_CheckLinkStatus();
}
}
}
}
bool _GatewayOnline_Cloud = false;
///
/// 网关在线-云端
///
public bool GatewayOnline_Cloud
{
get
{
return _GatewayOnline_Cloud;
}
set
{
if (_GatewayOnline_Cloud != value)
{
_GatewayOnline_Cloud = value;
if(GatewayOnline_Local)
{
return;
}
if (value)
{
if (DB_ResidenceData.Instance.HomeGateway == null)
{
return;
}
if (!DB_ResidenceData.Instance.HomeGateway.gatewayStatus)//远程情况下,网关未链接服务器不能修改主页网关状态
{
new System.Threading.Thread(() =>
{
System.Threading.Thread.Sleep(3000);
var pm = new DAL.Server.HttpServerRequest();
pm.GetGatewayInfo();
})
{ IsBackground = true }.Start();
return;
}
//修改主页连接状态
HomePage.LoadEvent_CheckLinkStatus();
MainPage.Log($"网关云端在线,刷新设备状态");
new System.Threading.Thread(() =>
{
System.Threading.Thread.Sleep(1000);
FunctionList.List.ReadAllFunctionStatus();
})
{ IsBackground = true, Priority = System.Threading.ThreadPriority.AboveNormal }.Start();
}
else
{
//修改主页连接状态
HomePage.LoadEvent_CheckLinkStatus();
}
}
}
}
///
/// 网关通讯ID
///
public string GatewayId = "";
///
/// 是否为远程连接
///
//public bool IsRemote = false;
///
/// 通讯地址IP
///
public string reportIp = "255.255.255.255";
///
/// tcp服务端
///
public Control_TcpServer myTcpServer = null;
///
/// tcp客服端
///
public Control_TcpClient myTcpClient = null;
///
/// 本地udp
///
public Control_Udp myUdp1 = null;
///
/// 通讯方式
///
public CommunicationMode communicationMode;
///
/// 打开tcp服务端
///
public void OpenTcpServer()
{
myTcpServer = new Control_TcpServer();
myTcpServer.OpenServer();
}
///
/// 打开Udp
///
public void OpenUdp(int port)
{
UdpSocket._BusSocket.Start(port);
}
///
/// 关闭udp
///
public void CloseUdp()
{
UdpSocket._BusSocket.Stop();
}
///
/// 打开tcp客服端
///
public void OpenTcpClent()
{
if (myTcpClient == null)
{
myTcpClient = new Control_TcpClient(reportIp);
myTcpClient.Connect();
}
}
///
/// 搜索本地网关列表
///
public void SearchLoaclGateway()
{
//2021-01-15 : 住宅没有绑定网关的时候不用搜索,并且不能链接mqtt
if(DB_ResidenceData.Instance.HomeGateway == null || string.IsNullOrEmpty(DB_ResidenceData.Instance.HomeGateway.gatewayId))
{
return;
}
Ins.GatewayOnline_Local = false;
var ggg = DB_ResidenceData.Instance.GatewayType == 0 ? "一端口" : "A网关";
var ggg1 = MainPage.InternetStatus == 1 ? "4G" : "wifi";
MainPage.Log($"搜索网关列表,网关类型:{ggg};网络类型:{ggg1}");
if (MainPage.InternetStatus == 0)
{
Ins.GatewayOnline_Cloud = false;
return;
}
else if (MainPage.InternetStatus == 1)
{
DAL.Mqtt.MqttClient.InitState();
}
else if (MainPage.InternetStatus == 2)
{
OpenUdp(DB_ResidenceData.Instance.GatewayType == 0 ? 6000 : 8585);
//重置搜索网关标志
IsSearchLocalGatewaySuccessful = false;
new System.Threading.Thread(() =>
{
for (int i = 0; i < 5; i++)
{
if (IsSearchLocalGatewaySuccessful)
{
Ins.GatewayOnline_Local = true;
break;
}
if (DB_ResidenceData.Instance.GatewayType == 0)
{
new Control_Udp().ControlBytesSend(Command.ReadGateway, 255, 255, new byte[] { (byte)new Random().Next(255), (byte)new Random().Next(255) });
}
else if (DB_ResidenceData.Instance.GatewayType == 1)
{
new Control_Udp().SearchLocalGateway();
new Control_Udp().SearchLocalGateway(true);
}
System.Threading.Thread.Sleep(500);
}
DAL.Mqtt.MqttClient.InitState();
})
{ IsBackground = true }.Start();
}
}
///
/// 场景控制入口
///
public void ControlScene(Scene scene)
{
//体验模式
if(MainPage.NoLoginMode)
{
foreach(var sceneFunction in scene.functions)
{
var revString = "";
var upDataObj = new AlinkFunctionStatusObj();
upDataObj.id = "999";
upDataObj.objects = new List();
var asd = new AlinkStatusData() { deviceId = sceneFunction.localFunction.deviceId, sid = sceneFunction.sid };
var status1 = new List();
foreach (var dic in sceneFunction.status)
{
status1.Add(new AttributesStatus() { key = dic.key, value = dic.value });
}
asd.status = status1;
upDataObj.objects.Add(asd);
revString = Newtonsoft.Json.JsonConvert.SerializeObject(upDataObj);
UpdataFunctionStatus(revString, null, true);
}
return;
}
//远程或者控制link网关场景
if (!Ins.GatewayOnline_Local || DB_ResidenceData.Instance.GatewayType == 1)
{
new System.Threading.Thread(() =>
{
ControlAProtocolScene(scene);
})
{ IsBackground = true }.Start();
}
else
{
if (DB_ResidenceData.Instance.GatewayType == 0)
{
new Control_Udp().ControlBusScenes(scene);
}
}
}
///
/// 安防控制
///
public void ControlArm()
{
DAL.Server.HttpServerRequest httpServer = new DAL.Server.HttpServerRequest();
//var pack = httpServer.GetSecurityAlarmLogList
}
///
/// 发送命令
/// 自动判断是否为A协议设备,
/// 不是A协议,自动转化bus命令数据
///
///
///
/// 是否直接使用远程发送
///
public void SendWriteCommand(Function function, Dictionary commandDictionary, bool useRemote = false,int resend = 3)
{
function.controlCounter++;
function.refreshTime = DateTime.Now;
//如果是控制调光的开时,亮度值不能为0
if (commandDictionary.Count > 2)
{
if (commandDictionary.ContainsKey(FunctionAttributeKey.OnOff) && commandDictionary.ContainsKey(FunctionAttributeKey.Brightness))
{
if (commandDictionary[FunctionAttributeKey.OnOff] == "on")
{
if (commandDictionary[FunctionAttributeKey.Brightness] == "0")
{
commandDictionary[FunctionAttributeKey.Brightness] = "100";
}
}
if (commandDictionary[FunctionAttributeKey.OnOff] == "off")
{
if (commandDictionary[FunctionAttributeKey.Brightness] != "0")
{
commandDictionary[FunctionAttributeKey.Brightness] = "0";
}
}
}
}
///dome控制
if (MainPage.NoLoginMode)
{
var revString = "";
var upDataObj = new AlinkFunctionStatusObj();
upDataObj.id = "999";
upDataObj.objects = new List();
var asd = new AlinkStatusData() { deviceId = function.deviceId, sid = function.sid };
var status1 = new List();
foreach (var dic in commandDictionary)
{
status1.Add(new AttributesStatus() { key = dic.Key, value = dic.Value });
}
asd.status = status1;
upDataObj.objects.Add(asd);
revString = Newtonsoft.Json.JsonConvert.SerializeObject(upDataObj);
UpdataFunctionStatus(revString, null, true);
return;
}
//MainPage.Log($"发送数据:{Newtonsoft.Json.JsonConvert.SerializeObject(commandDictionary)}");
///第三方涂鸦设备统一使用远程控制
switch (function.spk)
{
case SPK.ElectricTuyaAirCleaner:
case SPK.ElectricTuyaAirCleaner2:
case SPK.ElectricTuyaFan:
case SPK.ElectricTuyaFan2:
case SPK.ElectricTuyaWaterValve:
case SPK.ElectricTuyaWeepRobot:
case SPK.ElectricTuyaWeepRobot2:
useRemote = true;
break;
}
//远程通讯 --涂鸦设备必须需要远程
if (useRemote == true)
{
DAL.Server.HttpServerRequest httpServer = new DAL.Server.HttpServerRequest();
//ALink控制、Bus控制使用同一个接口控制,由云端负责解析
var apiControlData = function.GetApiControlData(commandDictionary);
var actionObjs = new List();
actionObjs.Add(apiControlData);
var pack = httpServer.ControlDevice(actionObjs);
}
else
{
//本地通讯
if (Ins.GatewayOnline_Local)
{
//Bus控制
if (DB_ResidenceData.Instance.GatewayType == 0)
{
try
{
new Control_Udp().WriteBusData(function, commandDictionary);
}
catch (Exception ex)
{
MainPage.Log($"发送数据异常: {ex.Message}");
}
}
//ALink控制
else
{
var functionControlDataObj = function.GetGatewayAlinkControlData(commandDictionary);
var functionControlDataJson = Newtonsoft.Json.JsonConvert.SerializeObject(functionControlDataObj);
var sendBytes = Ins.ConvertSendBodyData(CommunicationTopic.ct.ControlFunctionTopic, functionControlDataJson);
new Control_Udp().SendLocalHdlLinkData(sendBytes, functionControlDataObj.id,resend);
MainPage.Log($"本地通讯 发送HDL-Link数据:{functionControlDataJson}");
}
}
//远程通讯
else
{
//Bug修复:一端口远程控制调光设备的调光属性时,无法控制到0,反复横跳。
//因为On + 远程控制发送给云端使用的是link协议数据,杨涛中转给高胜处理时候逻辑上有冲突,导致无法单独控制亮度值,需要同时发送开关值与亮度值。
if (DB_ResidenceData.Instance.GatewayType == 0)
{
if (commandDictionary.Count == 1)
{
if (commandDictionary.ContainsKey(FunctionAttributeKey.Brightness))
{
commandDictionary.Add(FunctionAttributeKey.OnOff, commandDictionary[FunctionAttributeKey.Brightness] == "0" ? "off" : "on");
}
}
if(function.spk == SPK.LightCCT)
{
if (!commandDictionary.ContainsKey(FunctionAttributeKey.CCT))
{
commandDictionary.Add(FunctionAttributeKey.CCT, function.GetAttrState(FunctionAttributeKey.CCT));
}
}
}
DAL.Server.HttpServerRequest httpServer = new DAL.Server.HttpServerRequest();
//ALink控制、Bus控制使用同一个接口控制,由云端负责解析
var apiControlData = function.GetApiControlData(commandDictionary);
var actionObjs = new List();
actionObjs.Add(apiControlData);
var pack = httpServer.ControlDevice(actionObjs);
MainPage.Log($"远程控制反馈:{pack.message}");
}
}
}
///
/// 全开全关功能
///
public void SwtichFunctions(bool open,List functions)
{
//dome模式控制
if(MainPage.NoLoginMode)
{
new System.Threading.Thread(() =>
{
foreach (var temp in functions)
{
Dictionary d1 = new Dictionary();
d1.Add(FunctionAttributeKey.OnOff, open ? "on" : "off");
SendWriteCommand(temp, d1);
System.Threading.Thread.Sleep(100);
}
})
{ IsBackground = true }.Start();
return;
}
var count = 0;
List actionObjs = new List();
Dictionary d = new Dictionary();
d.Add(FunctionAttributeKey.OnOff, open ? "on" : "off");
var pm = new DAL.Server.HttpServerRequest();
//一端口全开全关需要延时发送
if (DB_ResidenceData.Instance.GatewayType == 0)
{
new System.Threading.Thread(() =>
{
foreach (var temp in functions)
{
var apiControlData = temp.GetApiControlData(d);
var result = pm.ControlDevice(new List() { apiControlData });
System.Threading.Thread.Sleep(100);
}
})
{ IsBackground = true }.Start();
}
else
{
foreach (var temp in functions)
{
var apiControlData = temp.GetApiControlData(d);
actionObjs.Add(apiControlData);
count++;
if (count > 9)
{
var result = pm.ControlDevice(actionObjs);
actionObjs = new List();
count = 0;
System.Threading.Thread.Sleep(100);
}
}
var pack = pm.ControlDevice(actionObjs);
}
}
public void SendApiReadCommand(List functionIds)
{
var pm = new DAL.Server.HttpServerRequest();
var pack = pm.RefreshDeviceStatus(functionIds);
}
///
/// 读取功能详细数据
///
///
public void ReadFunctionsInfo(List functionIds)
{
var pm = new DAL.Server.HttpServerRequest();
var pack = pm.GetDeviceInfoList(functionIds);
if(pack!= null&& pack.Data!=null)
{
//待测试2021-03-04
var ddd = Newtonsoft.Json.JsonConvert.DeserializeObject>(pack.Data.ToString());
if(ddd!= null)
{
foreach(var function in ddd)
{
var temp = FunctionList.List.GetDeviceFunctionList().Find((obj) => obj.deviceId == function.deviceId);
if(temp!= null)
{
if (SPK.Get3tySpk(SPK.BrandType.Tuya).Contains(temp.spk))
{
Stan.HdlDeviceStatuPushLogic.Current.UpdateDeviceStatu(temp.sid, function.status);
}
}
}
}
}
}
///
/// 发送读取命令
/// 自动判断是否为A协议设备
///
public void SendReadCommand(Function function ,bool forceRemote = false)
{
function.refreshTime = DateTime.Now;
if (forceRemote)
{
var pm = new DAL.Server.HttpServerRequest();
var pack = pm.RefreshDeviceStatus(new List() { function.deviceId });
}
else
{
if (Ins.GatewayOnline_Local)
{
if (DB_ResidenceData.Instance.GatewayType == 0)
{
try
{
new Control_Udp().ReadBusData(function);
}
catch (Exception ex)
{
MainPage.Log($"发送数据异常: {ex.Message}");
}
}
else
{
var readKey = new Dictionary();
readKey.Add("sid", function.sid);
var readDataObj = new AlinkReadFunctionStatusObj()
{
id = Ins.msg_id.ToString(),
objects = new List>()
{
readKey
},
time_stamp = Utlis.GetTimestamp()
};
var functionControlDataJson = Newtonsoft.Json.JsonConvert.SerializeObject(readDataObj);
var sendBytes = Ins.ConvertSendBodyData(CommunicationTopic.ct.ReadStatus, functionControlDataJson);
MainPage.Log($"本地通讯 发送HDL-Link数据:{functionControlDataJson}");
new Control_Udp().SendLocalHdlLinkData(sendBytes, readDataObj.id);
}
}
else
{
var pm = new DAL.Server.HttpServerRequest();
var pack = pm.RefreshDeviceStatus(new List() { function.deviceId });
}
}
}
///
/// 安防控制
///
public void ControlSecurity(SecurityAlarm securityAlarm,string state)
{
if (!Ins.GatewayOnline_Local)//网关本地不在线
{
var pm = new DAL.Server.HttpServerRequest();
var result = pm.SetSecurityStatus(new List() { new SecurityState() {
gatewayId = DB_ResidenceData.Instance.HomeGateway.gatewayId,
sid = securityAlarm.sid, status = state, userSecurityId = securityAlarm.userSecurityId
} });
MainPage.Log($"安防控制结果:{result.Code}");
}
else
{
Dictionary keys = new Dictionary();
keys.Add("sid", securityAlarm.sid);
keys.Add("status", state);
keys.Add("alarm", securityAlarm.alarm.ToString());
var aLinkData = new AlinkReadFunctionStatusObj()
{
id = Ins.msg_id.ToString(),
objects = new List>()
{
keys
},
time_stamp = Utlis.GetTimestamp()
};
var aLinkJson = Newtonsoft.Json.JsonConvert.SerializeObject(aLinkData);
var sendBytes = Ins.ConvertSendBodyData(CommunicationTopic.ct.ControlSeurity, aLinkJson);
new Control_Udp().SendLocalHdlLinkData(sendBytes, aLinkData.id);
}
}
///
/// a协议控制场景
///
///
static void ControlAProtocolScene(Scene scene)
{
if (!Ins.GatewayOnline_Local)//网关本地不在线
{
var pm = new DAL.Server.HttpServerRequest();
var result = pm.ExecuteScene(scene.userSceneId);
}
else
{
Dictionary keys = new Dictionary();
keys.Add("sid", scene.sid);
var aLinkData = new AlinkReadFunctionStatusObj()
{
id = Ins.msg_id.ToString(),
objects = new List>()
{
keys
},
time_stamp = Utlis.GetTimestamp()
};
var aLinkJson = Newtonsoft.Json.JsonConvert.SerializeObject(aLinkData);
var sendBytes = Ins.ConvertSendBodyData(CommunicationTopic.ct.ControlScene, aLinkJson);
new Control_Udp().SendLocalHdlLinkData(sendBytes, aLinkData.id,0);
}
}
///
/// 网关进入配网模式
///
public void AuthGateway()
{
var objects1 = new { spk = "", time = "180" };
//{"objects":[{"spk":"","time":"180"}],"id":"8","time_stamp":"1635241216669"}
var sendId = Ins.msg_id.ToString();
var sendObj = new { objects = objects1, id = sendId, time_stamp = Utlis.GetTimestamp() };
var aLinkJson = Newtonsoft.Json.JsonConvert.SerializeObject(sendObj);
var sendBytes = Ins.ConvertSendBodyData(CommunicationTopic.ct.AuthGateway, aLinkJson);
new Control_Udp().SendLocalHdlLinkData(sendBytes, Ins.msg_id.ToString());
}
///
/// 转换发送数据
///
/// 主题
/// body内容数据
/// 是否要对body加密
///
public byte[] ConvertSendBodyData(string topic, string bodyDataString, bool isEncryption = true)
{
//string topicString = "Topic:" + topic + "\r\n";
//byte[] bodyBytes = Encoding.ASCII.GetBytes(bodyDataString);
//string lengthString = "Length:" + bodyBytes.Length.ToString() + "\r\n" + "\r\n";
//string sendDataString = topicString + lengthString + bodyDataString;
//byte[] sendDataBytes = Encoding.ASCII.GetBytes(sendDataString);
//MainPage.Log($"转换HDL-Link数据\r\n{sendDataString}\r\n");
//***************************************************************
//2021-09-23 增加本地通信加密处理
//1.拼接头
string topicString = "Topic:" + topic + "\r\n";
//2.Body字符串转为byte数组
byte[] bodyBytes = Encoding.UTF8.GetBytes(bodyDataString);
//判断是否需加密Body数据
if (isEncryption && IsLocalEncryptAndGetAesKey)
{
bodyBytes = Securitys.EncryptionService.AesEncryptPayload(bodyBytes, DB_ResidenceData.Instance.CurrentRegion.localSecret);
//bodyDataString = Encoding.UTF8.GetString(bodyBytes);
//MainPage.Log($"转换HDL-Link数据 加密key:" + DB_ResidenceData.Instance.CurrentRegion.localSecret);
}
//3.拼接body的Length长度数据
string lengthString = "Length:" + bodyBytes.Length.ToString() + "\r\n" + "\r\n";
string topicAndLengthString = topicString + lengthString;
byte[] topicAndLengthBytes = Encoding.UTF8.GetBytes(topicAndLengthString);
//4.拼接合并 Topic 和 body的byte数组数据
byte[] sendDataBytes = new byte[topicAndLengthBytes.Length + bodyBytes.Length];
topicAndLengthBytes.CopyTo(sendDataBytes, 0);
bodyBytes.CopyTo(sendDataBytes, topicAndLengthBytes.Length);
//var sendDataString = Encoding.UTF8.GetString(sendDataBytes);
//MainPage.Log($"转换HDL-Link数据\r\n{sendDataString}\r\n");
//***************************************************************
return sendDataBytes;
}
///
/// 转换接收到的数据
///
///
public void ConvertReceiveData(byte[] receiveBytes,string ip)
{
var reString = Encoding.UTF8.GetString(receiveBytes);
AnalysisReceiveData(reString, receiveBytes,ip);
}
///
/// 转换接收到的数据
///
/// 转String后的数据
///
///
public LocalCommunicationData AnalysisReceiveData(string receiveString, byte[] originalReceiveBytes , string sIp = null)
{
LocalCommunicationData receiveObj = new LocalCommunicationData();
MainPage.Log($"局域网信息: \r\n{receiveString}");
var res = receiveString.Split("\r\n\r\n");
if (res.Length == 2)
{
var topics = res[0].Split("\r\n");
//MainPage.Log(res[1]);
foreach (var ts in topics)
{
var key = ts.Split(":");
switch (key[0])
{
case "Topic":
receiveObj.Topic = key[1];
break;
case "Length":
receiveObj.Length = Convert.ToInt32(key[1]);
break;
}
}
//MainPage.Log($"局域网信息: {receiveObj.Topic} : 内容: {res[1]}");
//验证有效数据长度
//if (res[1].Length != receiveObj.Length)
//{
// MainPage.Log($"收到数据包长度不够");
// return receiveObj;
//}
receiveObj.BodyDataString = res[1];
//2021-09-23 过滤不需要解密的主题 目前搜索网关主题不加密
if (receiveObj.Topic != CommunicationTopic.SearchLoaclGatewayReply)
{
//判断当前网关是否开启了本地加密
if (IsLocalEncryptAndGetAesKey)
{
MainPage.Log($"局域网信息 开始解密");
if (originalReceiveBytes != null)
{
//拿到原始Bytes数据去解密
byte[] topicBytes = Encoding.UTF8.GetBytes(res[0]);
byte[] bodyBytes = new byte[receiveObj.Length];
Array.Copy(originalReceiveBytes, topicBytes.Length + 4, bodyBytes, 0, receiveObj.Length);
byte[] receiveBytes = Securitys.EncryptionService.AesDecryptPayload(bodyBytes, DB_ResidenceData.Instance.CurrentRegion.localSecret);
var revString = Encoding.UTF8.GetString(receiveBytes);
receiveObj.BodyDataString = revString;
MainPage.Log($"局域网信息: 解密后:" + receiveObj.BodyDataString);
//if(receiveObj.Topic.EndsWith("/thing/property/up"))
//{
// MsgInfoList.Add(revString + "\r\n");
//}
}
else
{
//目前不拿原始Bytes数据 解密不了
//byte[] receiveBytes = Encoding.UTF8.GetBytes(res[1]);
//MainPage.Log($"局域网信息 receiveBytes {receiveBytes.Length}");
//receiveBytes = Securitys.EncryptionService.AesDecryptPayload(receiveBytes, DB_ResidenceData.Instance.CurrentRegion.localSecret);
//MainPage.Log($"局域网信息 解密后:receiveBytes {receiveBytes.Length}");
//var revString = Encoding.UTF8.GetString(receiveBytes);
//receiveObj.BodyDataString = revString;
//MainPage.Log($"局域网信息: 解密后:" + receiveObj.BodyDataString);
}
}
}
if (receiveObj.Topic == CommunicationTopic.SearchLoaclGatewayReply || receiveObj.Topic == CommunicationTopic.GatewayBroadcast)
{
var bodyJObj = Newtonsoft.Json.JsonConvert.DeserializeObject(res[1]);
if (bodyJObj == null)
{
return receiveObj;
}
var device = Newtonsoft.Json.JsonConvert.DeserializeObject(bodyJObj.objects.ToString());
if (device.device_mac.ToUpper() == DB_ResidenceData.Instance.HomeGateway.mac.ToUpper())
{
MainPage.Log("本地搜索网关成功");
Ins.IsSearchLocalGatewaySuccessful = true;
Ins.GatewayOnline_Local = true;
if (!string.IsNullOrEmpty(device.gatewayId))
{
Ins.GatewayId = device.gatewayId;
}
else
{
Ins.GatewayId = device.device_mac;
}
if (!string.IsNullOrEmpty(sIp))
{
device.ip_address = sIp;
}
reportIp = device.ip_address;//主播地址也能控制设备//"239.0.168.188";//
//2021-09-23 新增获取当前网关是否本地加密
Ins.IsLocalEncrypt = device.isLocalEncrypt;
//MainPage.Log("网关本地加密状态:" + device.local_encrypt.ToString());
}
}
else if (receiveObj.Topic == CommunicationTopic.ct.ReadStatus + "_reply" ||
receiveObj.Topic == CommunicationTopic.ct.ControlFunctionTopic + "_reply" ||
receiveObj.Topic == CommunicationTopic.ct.GatewayUpStatus ||
receiveObj.Topic.Contains( CommunicationTopic.ct.GatewayUpSortTopic))
{
//TODO 暂时不传正确的数据上去,如果后面要优化前面这些代码
UpdataFunctionStatus(receiveObj.BodyDataString, null);
}
else if (receiveObj.Topic == CommunicationTopic.ct.ControlSeurity +"_reply"
|| receiveObj.Topic == CommunicationTopic.ct.ReadSecurityStatus + "_reply"
|| receiveObj.Topic == CommunicationTopic.ct.SecurityStatusUp)
{
try
{
MainPage.Log($"局域网安防信息: {receiveObj.Topic} : 内容: {res[1]}");
var tt = "";
lock (tt) {
var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(receiveObj.BodyDataString);
if (temp != null)
{
Control_Udp.ReceiveRepeatManager(temp.id, null);
foreach (var updataSecurity in temp.objects)
{
var updataLocalSecurity = FunctionList.List.securities.Find((obj) => obj.sid == updataSecurity.sid);
if (updataLocalSecurity != null)
{
updataLocalSecurity.status = updataSecurity.status;
updataLocalSecurity.alarm = updataSecurity.alarm;
ArmCenterPage.LoadEvent_RefreshSecurityStatus(updataLocalSecurity);
}
}
HomePage.LoadEvent_RefreshSecurityStatus();
}
}
}
catch (Exception ex){
MainPage.Log($"安防局域网异常:{ex.Message}");
}
}
else
{
//一些特殊的主题处理(为了执行速度,尽可能的别加耗时的操作)
Stan.HdlCloudReceiveLogic.Current.CloudOverallMsgReceiveEx(receiveObj.Topic, receiveObj.BodyDataString);
}
}
return receiveObj;
}
///
/// 更新设备状态
/// A协议数据
///
///
public void UpdataFunctionStatus(string revString, byte[] usefulBytes,bool isCloudData = false)
{
var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(revString);
if (temp != null)
{
Control_Udp.ReceiveRepeatManager(temp.id, usefulBytes);
var allLocalFuntion = FunctionList.List.GetDeviceFunctionList();
foreach (var updateTemp in temp.objects)
{
try
{
if (Ins.GatewayOnline_Local && isCloudData)//本地链接,除了涂鸦设备数据之外的云端数据不处理
{
if (FunctionList.List.OtherBrandFunction.Count != 0)
{
if (FunctionList.List.OtherBrandFunction.Find((obj) => obj.sid == updateTemp.sid) == null)
{
//MainPage.Log($"A协议更新状态:本地链接,除了涂鸦设备数据之外的云端数据不处理...");
return;
}
}
}
var localFunction = allLocalFuntion.Find((obj) => obj.sid == updateTemp.sid);
if (localFunction == null)
{
continue;
}
if (Ins.GatewayOnline_Local && isCloudData)//本地链接,除了涂鸦设备数据之外的云端数据不处理
{
if (!SPK.Get3tySpk(SPK.BrandType.All3tyBrand).Contains(localFunction.spk))
{
//MainPage.Log($"A协议更新状态:本地链接,除了涂鸦设备数据之外的云端数据不处理........");
return;
}
}
//MainPage.Log($"A协议更新状态:{revString}");
foreach (var attr in updateTemp.status)
{
localFunction.time_stamp = temp.time_stamp;
localFunction.SetAttrState(attr.key, attr.value);
}
//更新界面状态
switch (localFunction.spk)
{
case SPK.AirSwitch:
AirSwitchPage.UpdataState(localFunction);
if(localFunction.GetAttribute(FunctionAttributeKey.Power)!=null)//如果是带电量的空开也要更新能源界面
{
EnergyMainPage.UpdataStatus(localFunction);
}
break;
case SPK.ElectricEnergy:
EnergyMainPage.UpdataStatus(localFunction);
break;
case SPK.LightSwitch:
RelayPage.UpdataState(localFunction);
break;
case SPK.LightDimming:
localFunction.lastState = Language.StringByID(StringId.Brightness) + " : " +
localFunction.GetAttrState(FunctionAttributeKey.Brightness) + "%";
DimmerPage.UpdataStates(localFunction);
break;
case SPK.ElectricFan:
case SPK.HvacFan:
localFunction.lastState = Language.StringByID(StringId.Level) + " : " +
localFunction.GetAttrState(FunctionAttributeKey.OpenLevel);
FanPage.UpdataState(localFunction);
break;
case SPK.LightRGB:
localFunction.lastState = Language.StringByID(StringId.Brightness) + " : " + localFunction.GetAttrState(FunctionAttributeKey.Brightness) + "%";
RGBPage.UpdataStates(localFunction);
break;
case SPK.LightRGBW:
break;
case SPK.LightCCT:
localFunction.lastState = Language.StringByID(StringId.Brightness) + " : " + localFunction.GetAttrState(FunctionAttributeKey.Brightness) + "%";
ColorTureLampPage.UpdataStatus(localFunction);
break;
case SPK.CurtainSwitch:
localFunction.lastState = localFunction.trait_on_off.curValue.ToString() == "on" ? Language.StringByID(StringId.Open) : Language.StringByID(StringId.Close);
CurtainModulePage.UpdataState(localFunction);
break;
case SPK.CurtainTrietex:
localFunction.lastState = Language.StringByID(StringId.Open) + localFunction.GetAttrState(FunctionAttributeKey.Percent) + "%";
MotorCurtainPage.UpdataState(localFunction);
break;
case SPK.CurtainRoller:
localFunction.lastState = Language.StringByID(StringId.Open) + localFunction.GetAttrState(FunctionAttributeKey.Percent) + "%";
RollingShutterPage.UpdataState(localFunction);
break;
case SPK.CurtainShades:
break;
case SPK.AcStandard:
case SPK.HvacAC:
case SPK.AcIr:
Stan.HdlDeviceStatuPushLogic.Current.UpdateDeviceStatu(updateTemp.sid, updateTemp.status);
if (localFunction != null)
{
localFunction.lastState = "";
switch (localFunction.GetAttrState(FunctionAttributeKey.Mode))
{
case "cool":
localFunction.lastState = Language.StringByID(StringId.Cool);
break;
case "heat":
localFunction.lastState = Language.StringByID(StringId.Heat);
break;
case "dry":
localFunction.lastState = Language.StringByID(StringId.Dry);
break;
case "auto":
localFunction.lastState = Language.StringByID(StringId.Auto);
break;
case "fan":
localFunction.lastState = Language.StringByID(StringId.AirSupply);
break;
}
switch (localFunction.GetAttrState(FunctionAttributeKey.FanSpeed))
{
case "high":
localFunction.lastState += " " + Language.StringByID(StringId.HighWindSpeed);
break;
case "medium":
localFunction.lastState += " " + Language.StringByID(StringId.MiddleWindSpeed);
break;
case "low":
localFunction.lastState += " " + Language.StringByID(StringId.LowWindSpeed);
break;
case "auto":
localFunction.lastState += " " + Language.StringByID(StringId.Auto);
break;
}
localFunction.lastState += " " + localFunction.GetAttrState(FunctionAttributeKey.SetTemp) + new AC().GetTempUnitString(localFunction);
}
break;
case SPK.HvacFloorHeat:
case SPK.FloorHeatStandard:
localFunction.lastState = "";
switch (localFunction.GetAttrState(FunctionAttributeKey.Mode))
{
case "normal":
localFunction.lastState = Language.StringByID(StringId.Normal);
break;
case "day":
localFunction.lastState = Language.StringByID(StringId.Day);
break;
case "night":
localFunction.lastState = Language.StringByID(StringId.Night);
break;
case "timer":
localFunction.lastState = Language.StringByID(StringId.Auto);
break;
case "away":
localFunction.lastState = Language.StringByID(StringId.Away);
break;
}
localFunction.lastState += " " + localFunction.GetAttrState(FunctionAttributeKey.SetTemp) + new FloorHeating().GetTempUnitString(localFunction);
FloorHeatingPage.UpdataStates(localFunction);
break;
case SPK.SensorPm25:
case SPK.SensorCO2:
case SPK.SensorTVOC:
case SPK.SensorTemperature:
case SPK.SensorHumidity:
case SPK.SensorHcho:
if(localFunction.spk == SPK.SensorTemperature)
{
HomePage.LoadEvent_RefreshEnvirIndoorTemp();
}
else if (localFunction.spk == SPK.SensorHumidity)
{
HomePage.LoadEvent_RefreshEnvirIndoorHumi();
}
EnvironmentalPage.LoadEvent_UpdataStatus(localFunction);
//A_EnvironmentalDataCenter.LoadEvent_UpdataStatus(localFunction);
break;
case SPK.SensorEnvironment:
case SPK.SensorEnvironment2:
case SPK.SensorEnvironment3:
if (localFunction.GetAttributes().Contains(FunctionAttributeKey.Temperature))
{
HomePage.LoadEvent_RefreshEnvirIndoorTemp();
}
if (localFunction.GetAttributes().Contains(FunctionAttributeKey.Humidity))
{
HomePage.LoadEvent_RefreshEnvirIndoorHumi();
}
EnvironmentalPage.LoadEvent_UpdataStatus(localFunction);
//A_EnvironmentalDataCenter.LoadEvent_UpdataStatus(localFunction);
break;
case SPK.ElectricSocket:
case SPK.PanelSocket:
SocketPage.UpdataState(localFunction);
break;
case SPK.ElectricTV:
break;
case SPK.ElectricTuyaAirCleaner:
case SPK.ElectricTuyaAirCleaner2:
case SPK.ElectricTuyaFan:
case SPK.ElectricTuyaFan2:
case SPK.ElectricTuyaWeepRobot:
case SPK.ElectricTuyaWeepRobot2:
case SPK.ElectricTuyaWaterValve:
case SPK.ElectricTuyaWaterValve2:
case SPK.SensorPir:
case SPK.SensorDoorWindow:
case SPK.SensorSmoke:
case SPK.SensorWater:
case SPK.ClothesHanger:
case SPK.SenesorMegahealth:
case SPK.SenesorMegahealth2:
case SPK.AirFreshStandard:
case SPK.HvacAirFresh:
case SPK.SensorGas:
//设备状态推送
//状态更新
Stan.HdlDeviceStatuPushLogic.Current.UpdateDeviceStatu(updateTemp.sid, updateTemp.status);
break;
}
HomePage.UpdataFunctionStates(localFunction);
RoomPage.UpdataStates(localFunction);
FunctionPage.UpdataStates(localFunction);
ClassificationPage.UpdataInfo(localFunction);
}
catch (Exception ex)
{
MainPage.Log($"A协议更新状态异常:{ex.Message}");
}
}
}
}
}
}