using System;
using System.Collections.Generic;
using System.Text;
using HDL_ON.DriverLayer;
using HDL_ON.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Shared.Net;
namespace HDL_ON.DriverLayer
{
public class Control_Udp
{
//public Control_Udp()
//{
// MainPage.Log($"control bus udp 被创建,时间:{DateTime.Now}");
//}
///
/// 通讯端口
///
public int port = 0;
///
/// 控制失败次数
///
public int controlLostCount = 0;
///
/// 所有对一端口的控制都会放到这个集合里
///
static List controlList = new List(50);
public System.Net.IPEndPoint EndPoint
{
get
{
try
{
return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(new NetWiFi().BroadcastIpAddress.ToString()),6000);
}
catch
{
//防止异常导致程序退出
return new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 6000);
}
}
}
///
/// 发送数据,不需要等待回复
///
public void ControlBytesSend(Command command, byte subnetID, byte deviceID, byte[] gatewayBytes, int sendCount = 3)
{
var control = new Control_Udp();
control.Send(new Target()
{
IPEndPoint = EndPoint ,
Command = command,
SubnetID = subnetID,
DeviceID = deviceID,
AddData = gatewayBytes,
}, sendCount, false);
}
///
/// 重发验证
///
public static void ReceiveRepeatManager(string receiveFlag,byte []usefulBytes)
{
for (int i = 0; i < controlList.Count; i++)
{
try
{
var control = controlList[i];
if (control.SendFlag == receiveFlag)
{
control.UsefulBytes = usefulBytes;//
control.run();
}
}
catch (Exception ex)
{
Console.WriteLine($"control error : {ex.Message}");
}
}
}
///
/// 000E 搜索回复
///
public void ReceiveReadRemark(byte[] usefullBytes)
{
try
{
//账号没登录不回复
if ( UserInfo.Current == null || ! UserInfo.Current.IsLogin)
{
return;
}
Control.Ins.OpenTcpServer();
var sendStr = UserInfo.Current.AccountString;
if (usefullBytes.Length == 0)
{
SendRemark(sendStr);
}
else
{
bool isExit = false;
for (int i = 0, len = usefullBytes.Length; i < len; i++)
{
if (i % 2 == 0)
{
if ((usefullBytes[i] & 0xFF) == 252 && (usefullBytes[i + 1] & 0xFF) == 252)
{
isExit = true;
break;
}
}
}
if (!isExit)
{
//不存在,代表没收到本机的发送,继续回复
SendRemark(sendStr);
}
}
}
catch (Exception ex) {
Console.WriteLine($"回复bus搜索异常 : {ex.Message}");
}
}
///
/// 000F回复备注
///
void SendRemark(string sendStr)
{
byte[] sendBytes = new byte[20];
byte[] b1 = Encoding.GetEncoding("gb2312").GetBytes(sendStr);
Array.Copy(b1, 0, sendBytes, 0, 20 < b1.Length ? 20 : b1.Length);
var control = new Control_Udp();
control.Send(new Target()
{
IPEndPoint = EndPoint,
Command = Command.ReadRemarkACK,
SubnetID = 0xFF,
DeviceID = 0xFF,
AddData = sendBytes,
}, 0, false); //设置当前发送指令方式为:任何情况下本地发送、不限制、不加密明文发送
}
///
/// 控制bus场景
/// todo
///
public void ControlBusScenes(Scene scene)
{
if(Control.Ins.GatewayOnline_Local)
{
foreach (var f in scene.functions)
{
if (f.localFunction == null)
{
continue;
}
switch (f.localFunction.spk)
{
case SPK.CurtainSwitch:
foreach (var attr in f.status)
{
if (attr.key == FunctionAttributeKey.OnOff)
{
byte curtainState = 0;
switch (attr.value)
{
case "on":
curtainState = 1;
break;
case "off":
curtainState = 2;
break;
}
ControlBytesSend(Command.SetCurtainModelStutas, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID,
new byte[] { f.localFunction.bus.LoopId, curtainState });
break;
}
}
break;
case SPK.AcStandard:
AC acTemp = new AC();
byte onoff = 0;
byte mode = 0;
byte fan = 0;
foreach (var attr in f.status)
{
byte modeKey = 4;
switch (attr.key)
{
case FunctionAttributeKey.OnOff:
if(attr.value == "on")
{
onoff = 1;
}
else
{
onoff = 0;
}
break;
case FunctionAttributeKey.Mode:
switch (attr.value)
{
case "auto":
mode = 3;
modeKey = 8;
break;
case "cool":
mode = 0;
modeKey = 4;
break;
case "heat":
mode = 1;
modeKey = 7;
break;
case "dry":
mode = 4;
modeKey = 19;
break;
case "fan":
mode = 2;
modeKey = 2;
break;
}
break;
case FunctionAttributeKey.FanSpeed:
switch (attr.value)
{
case "high":
fan = 1;
break;
case "medium":
fan = 2;
break;
case "low":
fan = 3;
break;
case "auto":
fan = 0;
break;
default:
fan = 0;
break;
}
break;
}
ControlBytesSend(Command.InstructionPanelKey, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] { 3, onoff, f.localFunction.bus.LoopId });
ControlBytesSend(Command.InstructionPanelKey, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] { 6, mode, f.localFunction.bus.LoopId });
ControlBytesSend(Command.InstructionPanelKey, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] { 5, fan, f.localFunction.bus.LoopId });
ControlBytesSend(Command.InstructionPanelKey, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] { modeKey, modeKey, f.localFunction.bus.LoopId });
}
break;
case SPK.LightSwitch:
case SPK.LightDimming:
byte brightness = 0;
foreach (var attr in f.status)
{
switch (attr.key)
{
case FunctionAttributeKey.OnOff:
switch (attr.value)
{
case "on":
brightness = 100;
break;
case "off":
brightness = 0;
break;
}
break;
case FunctionAttributeKey.Brightness:
brightness = Convert.ToByte(attr.value);
break;
}
}
ControlBytesSend(Command.SetSingleLight, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID,
new byte[] { f.localFunction.bus.LoopId, brightness, (byte)(f.localFunction.delay / 255), (byte)(f.localFunction.delay % 255) });
break;
case SPK.LightRGB:
break;
case SPK.FloorHeatStandard:
if (f.status.Find((obj)=>obj.key ==FunctionAttributeKey.Mode) == null)
{
foreach (var dic in f.status)
{
switch (dic.key)
{
case FunctionAttributeKey.OnOff:
ControlBytesSend(Command.InstructionPanelKey, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] { 20, dic.value.ToString() == "on" ? (byte)1 : (byte)0, f.localFunction.bus.LoopId });
break;
case "mode":
ControlBytesSend(Command.InstructionPanelKey, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] { 21, Convert.ToByte(dic.value), f.localFunction.bus.LoopId });
break;
case FunctionAttributeKey.SetTemp:
ControlBytesSend(Command.InstructionPanelKey, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] {
25, Convert.ToByte(dic.value), f.localFunction.bus.LoopId });
break;
}
}
}
else
{
byte onoff_1 = 0;
byte setTemp_1 = 0;
byte mode_1 = 0;
foreach (var attr in f.status)
{
switch (attr.key)
{
case FunctionAttributeKey.OnOff:
if (attr.value == "on")
{
onoff_1 = 1;
}
else
{
onoff_1 = 0;
}
break;
case FunctionAttributeKey.SetTemp:
setTemp_1 = Convert.ToByte(attr.value);
break;
case FunctionAttributeKey.Mode:
switch (attr.value)
{
case "day":
mode_1 = 2;
break;
case "night":
mode_1 = 3;
break;
case "away":
mode_1 = 4;
break;
case "normal":
mode_1 = 1;
break;
case "timer":
mode_1 = 5;
break;
}
break;
}
}
ControlBytesSend(Command.SetFloorHeat, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID, new byte[] {
f. localFunction.bus.LoopId, onoff_1, 0, setTemp_1, mode_1, setTemp_1, setTemp_1, setTemp_1, 0, 0 });
}
break;
case SPK.ElectricSocket:
foreach (var attr in f.status)
{
if (attr.key == FunctionAttributeKey.OnOff)
{
byte onOffValue = 0;
switch (attr.value)
{
case "on":
onOffValue = 1;
break;
case "off":
onOffValue = 2;
break;
}
ControlBytesSend(Command.SetSingleLight, f.localFunction.bus.SubnetID, f.localFunction.bus.DeviceID,
new byte[] { f.localFunction.bus.LoopId, onOffValue });
break;
}
}
break;
}
}
}
else
{
foreach (var f in scene.functions)
{
var count = 0;
List actionObjs = new List();
Dictionary d = new Dictionary();
var pm = new DAL.Server.HttpServerRequest();
foreach (var temp in f.status)
{
if (f.localFunction == null)
{
continue;
}
d.Add(temp.key, temp.value);
var apiControlData = f.localFunction.GetApiControlData(d);
actionObjs.Add(apiControlData);
count++;
if (count > 9)
{
var result = pm.ControlDevice(actionObjs);
actionObjs = new List();
count = 0;
}
}
var pack = pm.ControlDevice(actionObjs);
}
}
}
///
/// 控制bus设备
///
///
///
public void WriteBusData(Function function, Dictionary commandDictionary)
{
try
{
var subnetId = function.bus.SubnetID;
var deviceId = function.bus.DeviceID;
var loopId = function.bus.LoopId;
switch (function.Spk_Prefix)
{
case FunctionCategory.Light:
switch (function.spk)
{
case SPK.LightCCT:
byte b0 = 100;//开关操作依据on_off字段,实际开关值依据brightness,当on_off为打开,brightness不能为0
if (function.trait_on_off.curValue.ToString() == "off")
{
b0 = 0;
}
else
{
b0 = Convert.ToByte( function.GetAttrState(FunctionAttributeKey.Brightness)) == 0 ? (byte)100 : Convert.ToByte(function.GetAttrState(FunctionAttributeKey.Brightness));
}
var bytes0 = new byte[] { function.bus.LoopId,
b0,
254, 0,Convert.ToByte(function.GetAttrState(FunctionAttributeKey.FadeTime)) ,2,
(byte)(Convert.ToInt32(function.GetAttrState(FunctionAttributeKey.CCT))/256),
(byte)(Convert.ToInt32(function.GetAttrState(FunctionAttributeKey.CCT))%256),
0,
0,0};
ControlBytesSend(Command.SetLogicLoopColor, subnetId, deviceId, bytes0, 1);
break;
case SPK.LightRGB:
byte b = 100;//开关操作依据on_off字段,实际开关值依据brightness,当on_off为打开,brightness不能为0
if (function.trait_on_off.curValue.ToString() == "off")
{
b = 0;
}
else
{
byte lightBri1 = Convert.ToByte(function.GetAttrState(FunctionAttributeKey.Brightness));
if (lightBri1 == 0)
{
b = 100;
}
else
{
b = lightBri1;
}
}
var tempLight = new Light();
var bytes = new byte[] { function.bus.LoopId,
b,
254, 0,Convert.ToByte(function.GetAttrState(FunctionAttributeKey.FadeTime)) ,3,
(byte)tempLight.GetColor(0,function),
(byte)tempLight.GetColor(1,function),
(byte)tempLight.GetColor(2,function),
0,0};
ControlBytesSend(Command.SetLogicLoopColor, subnetId, deviceId, bytes, 1);
break;
case SPK.LightDimming:
byte b1 = 100;
if (function.trait_on_off.curValue.ToString() == "off")
{
b1 = 0;
}
else
{
byte lightBri = Convert.ToByte(function.GetAttrState(FunctionAttributeKey.Brightness));
if (lightBri == 0)
{
b1 = 100;
}
else
{
b1 = lightBri;
}
}
ControlBytesSend(Command.SetSingleLight, subnetId, deviceId, new byte[] {
function.bus.LoopId,
b1,
0, Convert.ToByte(function.GetAttrState(FunctionAttributeKey.FadeTime)) });
break;
case SPK.LightSwitch:
ControlBytesSend(Command.SetSingleLight, subnetId, deviceId, new byte[] { function.bus.LoopId, function.trait_on_off.curValue.ToString() == "on" ? (byte)100 : (byte)0, 0, 0 });
break;
}
break;
case FunctionCategory.Curtain:
switch (function.spk)
{
case SPK.CurtainSwitch:
byte b1 = 0;
if (function.trait_on_off.curValue.ToString() == "stop")
{
b1 = 0;
}
else if (function.trait_on_off.curValue.ToString() == "on")
{
b1 = 1;
}
else
{
b1 = 2;
}
ControlBytesSend(Command.SetCurtainModelStutas, subnetId, deviceId, new byte[] { function.bus.LoopId, b1 });
break;
case SPK.CurtainTrietex:
case SPK.CurtainRoller:
if (function.trait_on_off.curValue.ToString() == "stop")
{
ControlBytesSend(Command.SetCurtainModelStutas, subnetId, deviceId, new byte[] { function.bus.LoopId, 0 });
}
else
{
ControlBytesSend(Command.SetCurtainModelStutas, subnetId, deviceId, new byte[] { 17, Convert.ToByte(function.GetAttrState(FunctionAttributeKey.Percent)) });
}
break;
}
break;
case FunctionCategory.AC:
switch (function.spk)
{
case SPK.AcStandard:
var ac = new AC();
//ControlBytesSend(Command.SetACMode, subnetId, deviceId, new byte[] { function.bus.LoopId, 0, 32, 32, 32, 32, 32, 0, function.trait_on_off.curValue.ToString() == "on" ? (byte)1 : (byte)0,
// ac.GetModeIndex(function),
// ac.GetFanIndex(function), Convert.ToByte(function.GetAttrState(FunctionAttributeKey.SetTemp)), 0 });
foreach (var dic in commandDictionary)
{
switch (dic.Key)
{
case FunctionAttributeKey.OnOff:
ControlBytesSend(Command.InstructionPanelKey, function.bus.SubnetID, function.bus.DeviceID, new byte[] { 3, function.trait_on_off.curValue.ToString() == "on" ? (byte)1 : (byte)0, function.bus.LoopId });
break;
case "mode":
ControlBytesSend(Command.InstructionPanelKey, function.bus.SubnetID, function.bus.DeviceID, new byte[] { 6, ac.GetModeIndex(function), function.bus.LoopId });
break;
case "fan":
ControlBytesSend(Command.InstructionPanelKey, function.bus.SubnetID, function.bus.DeviceID, new byte[] { 5, ac.GetFanIndex(function), function.bus.LoopId });
break;
case FunctionAttributeKey.SetTemp:
byte modeKey = 4;
switch (ac.GetModeIndex(function))
{
case 3:
modeKey = 8;
break;
case 0:
modeKey = 4;
break;
case 1:
modeKey = 7;
break;
case 4:
modeKey = 19;
break;
case 2:
modeKey = 2;
break;
}
ControlBytesSend(Command.InstructionPanelKey, function.bus.SubnetID, function.bus.DeviceID, new byte[] {
modeKey, Convert.ToByte(function.GetAttrState(FunctionAttributeKey.SetTemp)), function.bus.LoopId });
break;
default:
MainPage.Log($"功能未支持 : {dic.Key}");
break;
}
}
break;
}
break;
case FunctionCategory.FloorHeat:
var fhTemp = new FloorHeating();
switch (function.spk)
{
case SPK.FloorHeatStandard:
if (function.Fh_Mode_Temp.Count == 4)
{
if (function.GetAttribute(FunctionAttributeKey.Mode) == null)
{
foreach (var dic in commandDictionary)
{
switch (dic.Key)
{
case FunctionAttributeKey.OnOff:
ControlBytesSend(Command.InstructionPanelKey, function.bus.SubnetID, function.bus.DeviceID, new byte[] { 20, function.trait_on_off.curValue.ToString() == "on" ? (byte)1 : (byte)0, function.bus.LoopId });
break;
case "mode":
ControlBytesSend(Command.InstructionPanelKey, function.bus.SubnetID, function.bus.DeviceID, new byte[] { 21, fhTemp.GetModeIndex(function), function.bus.LoopId });
break;
case FunctionAttributeKey.SetTemp:
byte modeKey = 25;
switch (fhTemp.GetModeIndex(function))
{
case 1:
modeKey = 25;
break;
case 2:
modeKey = 26;
break;
case 3:
modeKey = 27;
break;
case 4:
modeKey = 28;
break;
}
ControlBytesSend(Command.InstructionPanelKey, function.bus.SubnetID, function.bus.DeviceID, new byte[] {
modeKey, Convert.ToByte(function.GetAttrState(FunctionAttributeKey.SetTemp)), function.bus.LoopId });
break;
default:
MainPage.Log($"功能未支持 : {dic.Key}");
break;
}
}
}
else
{
var onoffString = function.trait_on_off.curValue.ToString();
byte b1 = 1;
if (onoffString == "off")
{
b1 = 0;
}
var wm = fhTemp.GetWorkModeIndex(function);
if (wm > 0)
{
b1 += (byte)(16 + wm);
}
if (commandDictionary.ContainsKey("set_temp"))
{
var dicTempString = "";
commandDictionary.TryGetValue("set_temp", out dicTempString);
var dicTemp = Convert.ToByte(dicTempString);
var mode = function.GetAttrState(FunctionAttributeKey.Mode);
switch (mode)
{
case "day":
function.Fh_Mode_Temp["day"] = dicTemp;
break;
case "night":
function.Fh_Mode_Temp["night"] = dicTemp;
break;
case "away":
function.Fh_Mode_Temp["away"] = dicTemp;
break;
case "normal":
function.Fh_Mode_Temp["normal"] = dicTemp;
break;
}
}
var tt = fhTemp.GetTempUintIndex(function);
ControlBytesSend(Command.SetFloorHeat, subnetId, deviceId, new byte[] { function.bus.LoopId, b1,
(byte)tt,fhTemp.GetModeIndex(function), function.Fh_Mode_Temp["normal"], function.Fh_Mode_Temp["day"], function.Fh_Mode_Temp["night"], function.Fh_Mode_Temp["away"], 0, 0 });
}
}
break;
}
break;
case FunctionCategory.Electric:
switch (function.spk)
{
case SPK.ElectricFan:
if (function.trait_on_off.curValue.ToString() == "on")
{
ControlBytesSend(Command.SetSingleLight, subnetId, deviceId, new byte[] { function.bus.LoopId, Convert.ToByte(function.GetAttrState(FunctionAttributeKey.OpenLevel)) });
}
{
ControlBytesSend(Command.SetSingleLight, subnetId, deviceId, new byte[] { function.bus.LoopId, 0 });
}
break;
case SPK.ElectricSocket:
ControlBytesSend(Command.SetSingleLight, subnetId, deviceId, new byte[] { function.bus.LoopId, function.trait_on_off.curValue.ToString() == "on" ? (byte)100 : (byte)0 });
break;
}
break;
case FunctionCategory.AirFresh:
switch(function.spk)
{
case SPK.AirFreshJinmao:
//1 新风编号 1~200
//2 类型 第三方类型 0:金茂新风
//3 开关 0 - 关机,1 - 开机
byte switchValue = 0;
if (commandDictionary.ContainsKey(FunctionAttributeKey.OnOff) == true
&& commandDictionary[FunctionAttributeKey.OnOff] == "on")
{
switchValue = 1;
}
//4 运行模式 1 - 通风,2 - 加湿
byte airFreshMode = 1;
if (commandDictionary.ContainsKey(FunctionAttributeKey.Mode) == true
&& commandDictionary[FunctionAttributeKey.Mode] == "humidification")
{
airFreshMode = 2;
}
//5 节能舒适选择 1 - 舒适,2 - 节能
byte airFreshEnergy = 1;
if (commandDictionary.ContainsKey(FunctionAttributeKey.Energy) == true
&& commandDictionary[FunctionAttributeKey.Energy] == "true")
{
airFreshEnergy = 2;
}
//6 风速档位 0 - 自动,1 - 1档,2 - 2档,3 - 3档
byte airFreshFan = 0;
if (commandDictionary.ContainsKey(FunctionAttributeKey.FanSpeed) == true)
{
switch (commandDictionary[FunctionAttributeKey.FanSpeed])
{
case "auto":
airFreshFan = 0;
break;
case "level_1":
airFreshFan = 1;
break;
case "level_2":
airFreshFan = 2;
break;
case "level_3":
airFreshFan = 3;
break;
}
}
//7 湿度设定 %
//8 室内温度值 ℃
byte indoorTemp_airFrsh = 0;
if (commandDictionary.ContainsKey(FunctionAttributeKey.IndoorTemp) == true)
{
indoorTemp_airFrsh= Convert.ToByte(commandDictionary[FunctionAttributeKey.IndoorTemp]);
}
byte indoorHumidity_airFrsh = 0;
if (commandDictionary.ContainsKey(FunctionAttributeKey.IndoorHumidity) == true)
{
indoorHumidity_airFrsh = Convert.ToByte(commandDictionary[FunctionAttributeKey.IndoorHumidity]);
}
//9 室内湿度值 ℃
//10 过滤网剩余 %
//11 过滤网使用超时 1 超时 0 无
ControlBytesSend(Command.FreshAirControl_JinMao, subnetId, deviceId, new byte[] {
function.bus.LoopId,0, switchValue ,
airFreshMode,airFreshEnergy,
airFreshFan,
Convert.ToByte(function.GetAttrState(FunctionAttributeKey.Humidity)),
indoorTemp_airFrsh,
indoorHumidity_airFrsh,
//Convert.ToByte( function.GetAttrState(FunctionAttributeKey.FilterRemain)),
//function.GetAttrState(FunctionAttributeKey.FilterTimeout) =="true"?1:0,
0,0
});
break;
}
break;
}
#region 发送命令立即更新UI
//HomePage.UpdataFunctionStates(function);
//RoomPage.UpdataStates(function);
//FunctionPage.UpdataStates(function);
//ClassificationPage.UpdataInfo(function);
#endregion
}
catch (Exception ex)
{
MainPage.Log($"DataConversion_Bus Erorr : {ex.Message}");
}
}
///
/// 读取bus设备数据
///
public void ReadBusData(Function function)
{
try
{
var subnetId = function.bus.SubnetID;
var deviceId = function.bus.DeviceID;
var loopId = function.bus.LoopId;
switch (function.Spk_Prefix)
{
case FunctionCategory.Light:
switch (function.spk)
{
case SPK.LightSwitch:
case SPK.LightDimming:
ControlBytesSend(Command.ReadLightAllLoopBrightness, subnetId, deviceId, new byte[] { });
break;
case SPK.LightRGB:
ControlBytesSend(Command.ReadLogicLoopColor, subnetId, deviceId, new byte[] { function.bus.LoopId});
break;
case SPK.LightCCT:
ControlBytesSend(Command.ReadLogicLoopColor, subnetId, deviceId, new byte[] { function.bus.LoopId });
break;
}
break;
case FunctionCategory.Curtain:
switch (function.spk)
{
case SPK.CurtainSwitch:
case SPK.CurtainTrietex:
case SPK.CurtainRoller:
ControlBytesSend(Command.ReadCurtainStatus, subnetId, deviceId, new byte[] { function.bus.LoopId });
break;
}
break;
case FunctionCategory.AC:
switch (function.spk)
{
case SPK.AcStandard:
ControlBytesSend(Command.ReadACMode, subnetId, deviceId, new byte[] { function.bus.LoopId });
break;
}
break;
case FunctionCategory.FloorHeat:
switch (function.spk)
{
case SPK.FloorHeatStandard:
ControlBytesSend(Command.ReadFloorHeat, subnetId, deviceId, new byte[] { function.bus.LoopId });
break;
}
break;
case FunctionCategory.Electric:
switch (function.spk)
{
case SPK.ElectricFan:
ControlBytesSend(Command.SetSingleLight, subnetId, deviceId, new byte[] { function.bus.LoopId });
break;
case SPK.ElectricSocket:
ControlBytesSend(Command.SetSingleLight, subnetId, deviceId, new byte[] { function.bus.LoopId });
break;
}
break;
case FunctionCategory.Sensor:
byte sensorType = 0;
switch (function.spk)
{
case SPK.SensorTemperature:
sensorType = 2;
break;
case SPK.SensorHumidity:
sensorType = 3;
break;
case SPK.SensorTVOC:
sensorType = 5;
break;
case SPK.SensorPm25:
sensorType = 6;
break;
case SPK.SensorCO2:
sensorType = 7;
break;
}
ControlBytesSend(Command.ReadDeviceLoopInfo, subnetId, deviceId, new byte[] { 5, sensorType, function.bus.LoopId });
break;
case FunctionCategory.AirFresh:
switch(function.spk)
{
case SPK.AirFreshJinmao:
ControlBytesSend(Command.FreshAirRead_JinMao, subnetId, deviceId, new byte[] { function.bus.LoopId });
break;
}
break;
}
}
catch (Exception ex)
{
MainPage.Log($"Read DataConversion_Bus Erorr : {ex.Message}");
}
}
///
/// 添加到内存数组里面
///
void add()
{
///
/// 达到50条数据后就清理一下
///
if (50 < controlList.Count)
{
lock (controlList)
{
for (int i = 0; i < controlList.Count;)
{
if (controlList[i] == null || 3 <= controlList[i].packet.HaveSendCount)
{
controlList.RemoveAt(i);
}
else
{
i++;
}
}
}
}
controlList.Add(this);
}
//当前数据的关键数据
string sendFlag = string.Empty;
protected string SendFlag
{
get
{
return sendFlag;
}
set
{
sendFlag = value;
usefulBytes = null;
}
}
private byte[] usefulBytes;
///
/// 获取回来的有用信息,如果获取回来的数据为null,就会抛出异常信息
///
public byte[] UsefulBytes
{
get
{
if (null == usefulBytes)
{
// throw new Exception("不好意思,网络不稳定或者远程设备不在线,请稍候再试!");
}
return this.usefulBytes;
}
set
{
usefulBytes = value;
}
}
//发送数据了之后当前线程等待或者运行的信号
System.Threading.ManualResetEvent allDone = new System.Threading.ManualResetEvent(false);
///
/// 发送了数据后,线程就是等待状态,直到接收到反馈或者超时后退出
///
void wait()
{
allDone.Reset();
allDone.WaitOne();
}
///
/// 让当前线程继续执行
///
void run()
{
allDone.Set();
packet.HaveSendCount = 4;
}
//数据发送处理
void managerSendCount(object o)
{
add();
//Bus socket无法控制,重启机制
if (controlLostCount > 10)
{
UdpSocket._BusSocket.Stop();
new System.Threading.Thread(() =>
{
System.Threading.Thread.Sleep(1000);
UdpSocket._BusSocket.Start(UdpSocket._BusSocket.Port);
controlLostCount = 0;
})
{ IsBackground = true }.Start();
}
try
{
MainPage.Log("发送数据:" + SendFlag);
UdpSocket._BusSocket.AsyncBeginSend(packet);
packet.HaveSendCount--;
//这里是重发两次
while (packet.HaveSendCount < 3)
{
if (packet.FlagDateTime.AddMilliseconds(1000).Ticks <= DateTime.Now.Ticks)
{
MainPage.Log("重发数据:" + SendFlag);
UdpSocket._BusSocket.AsyncBeginSend(packet);
controlLostCount++;
}
System.Threading.Thread.Sleep(300);
}
}
catch (Exception ex)
{
MainPage.Log("managerSendCount:" + ex.ToString());
}
finally
{
allDone.Set();
}
}
///
/// 当前数据包
///
Packet packet;
///
/// 记录发送数据包
///
///
private void signPacket(Target target)
{
this.SendFlag = string.Format("{0},{1},{2},", target.SubnetID, target.DeviceID, (int)target.Command + 1);
switch (target.Command)
{
case Command.SetSingleLight:
case Command.ReadLogicLoopColor:
case Command.ReadACMode:
case Command.SetACMode:
case Command.ReadFloorHeat:
case Command.SetFloorHeat:
case Command.FreshAirRead:
case Command.FreshAirControl:
case Command.FreshAirRead_JinMao:
case Command.FreshAirControl_JinMao:
this.sendFlag += string.Format("{0}", target.AddData[0]);
break;
case Command.SetLogicLoopColor:
this.sendFlag += string.Format("{0},{1},{2}", target.AddData[0], target.AddData[1], target.AddData[2]);
break;
case Command.ReadLightAllLoopBrightness:
this.SendFlag += "";
break;
case Command.ReadGateway:
this.SendFlag = string.Format("{0},{1}", target.AddData[0], target.AddData[1]);
break;
case Command.ReadDeviceLoopInfo:
if (target.AddData[0] == 1)//特殊处理灯光类,DMX模块每一个回路不固定小类,根据具体设置来回复
this.sendFlag += string.Format("{0},{1}", target.AddData[0], target.AddData[2]);
else
this.sendFlag += string.Format("{0},{1},{2}", target.AddData[0], target.AddData[1], target.AddData[2]);
break;
case Command.InstructionPanelKey:
case Command.ReadInstructionPanelKey:
this.sendFlag += string.Format("{0},{1}", target.AddData[0], target.AddData[1]);
break;
default:
break;
}
}
//private void signAlinkPacket()
//{
//}
///
/// 发送数据
///
/// 发送对象
/// 重发次数
private void Send(Target target, int sendCount, bool isWait)
{
try
{
packet = new Packet(target.SendBytes, target.IPEndPoint);
packet.HaveSendCount = 3 - sendCount;
signPacket(target);
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(managerSendCount));
thread.IsBackground = true;
thread.Start(packet);
if (isWait)
{
this.wait();
}
}
catch(Exception ex)
{
MainPage.Log($"Send bus data error {ex.Message}");
}
}
///
/// 读取网关IP
///
public void SearchLocalGateway()
{
try
{
var sendJob = new JObject { { "id", Control.Ins.msg_id.ToString() }, { "time_stamp", Utlis.GetTimestamp ()} };
var bodyString = JsonConvert.SerializeObject(sendJob);
var sendBytes = Control.Ins.ConvertSendBodyData(CommunicationTopic.SearchLoaclGateway, bodyString);
//组播发送
packet = new Packet(sendBytes, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("239.0.168.188"), 8585));
packet.HaveSendCount = 4;
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(managerSendCount));
thread.IsBackground = true;
thread.Start(packet);
//wait();不需要等待
//hjSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//hjSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
//EndPoint ipep = new IPEndPoint(IPAddress.Parse(CsConst.myLocalIP), HDLUDP.UDPPort);
//hjSocket.Bind(ipep);
}
catch (Exception ex)
{
MainPage.Log($"Send bus data error {ex.Message}");
}
}
///
/// 发送udp A协议数据
///
public void SendLocalHdlLinkData(byte[] sendBytes,string id, bool isWait=false)
{
packet = new Packet(sendBytes, new System.Net.IPEndPoint(System.Net.IPAddress.Parse(Control.Ins.reportIp), 8585));
sendFlag = id;
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(managerSendCount));
thread.IsBackground = true;
thread.Start(packet);
if (isWait)
{
wait();
}
MainPage.Log($"发送Hdl-Link数据,IP:{Control.Ins.reportIp}:8585");
}
}
}