using DataVApi.Order;
using DataVAPI.Controllers;
using DataVAPI.Model;
using DataVAPI.ModelDataBus;
using DataVAPI.Tool;
using DataVAPI.Tool.IOT;
using DataVAPI.Tool.控制台显示;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace DataVAPI.UpAndDown
{
///
/// 上下线通知
///
public class ProcessServer
{
///
/// 上报大屏总Model
///
public ScreenMonitorModel devModel { get; set; }
public DeviceController deviceController { get; set; }
public LogController logController { get; set; }
public ScreenController screenController { get; set; }
public AlarmController alarmController { get; set; }
public OrderProvider orderProvider { get; set; }
public List devStatuses { get; set; }=new List();
#region 不需要监听
private static ProcessServer _instance;
public static ProcessServer Instance
{
get
{
if (_instance == null)
_instance = new ProcessServer();
return _instance;
}
}
public ProcessServer()
{
deviceController = new DeviceController();
logController = new LogController();
alarmController = new AlarmController();
screenController = new ScreenController();
orderProvider = new OrderProvider();
}
#endregion
bool FistBOOL = false;
///
/// 初始化
///
public void Initialize()
{
devModel = new ScreenMonitorModel();
devModel.operatingDeviceStatus = new OperatingDeviceStatus(); devModel.operatingDeviceStatus.data = new List();//现场设备于状态
devModel.infoMessage = new InfoMessage(); devModel.infoMessage.data = new List();//通知消息
//加载店铺信息 //加载店铺信息
LoadingShopInformation();
//MQTT 数据接收处理
ConsoleHelper.WriteInfoLine("尝试连接阿里云.");
//设置变量
IOTDevServer.GetInstance().Set(DataBus.ProductKey, DataBus.DeviceName, DataBus.DeviceSecret);
IOTDevServer.GetInstance().SetSub(new List { IOTDevServer.HeartbeatSubTopic, IOTDevServer.BroadcastTopic });
if (IOTDevServer.GetInstance().CreateLinks(DataBus.ProductKey, DataBus.DeviceName, DataBus.DeviceSecret))
{
//订阅上下线
Subscribe(IOTDevServer.HeartbeatSubTopic);
//订阅主播消息
Subscribe(IOTDevServer.BroadcastTopic);
ConsoleHelper.WriteInfoLine($"阿里云【Transit】连接成功");
}
else
{
ConsoleHelper.WriteErrorLine($"阿里云【Transit】连接失败");
}
IOTDevServer.UNConnectMqtt += new Action((o) => { ConsoleHelper.WriteSuccessLine(o); });
IOTDevServer.DevIOTAction += DevIOTActionHandler;
QueueTask();
ConsoleHelper.WriteSuccessLine("开始接收数据,执行队列任务!");
}
///
/// 队列任务
///
private void QueueTask()
{
Executer.GetInstance().Start(new Action(() =>
{
while (true)
{
try
{
if (!IOTDevServer.GetInstance().GetIsConnected())
{
if (IOTDevServer.GetInstance().CreateLinks(DataBus.ProductKey, DataBus.DeviceName, DataBus.DeviceSecret))
{
ConsoleHelper.WriteInfoLine($"阿里云【Transit】重新连接成功");
//订阅上下线
Subscribe(IOTDevServer.HeartbeatSubTopic);
//订阅主播消息
Subscribe(IOTDevServer.BroadcastTopic);
}
else
{
ConsoleHelper.WriteErrorLine($"阿里云【Transit】重新连接失败");
}
Thread.Sleep(360000);
}
}
catch (Exception ex)
{
ConsoleHelper.WriteErrorLine(ex.Message);
}
}
}), "阿里云重新连接");
Executer.GetInstance().Start(new Action(() =>
{
while (true)
{
try
{
if (IOTDevServer.GetInstance().GetIsConnected())
{
SentData(null);
//FindDataAlarm();
Thread.Sleep(3000);
}
}
catch (Exception ex)
{
ConsoleHelper.WriteErrorLine(ex.Message);
}
}
}), "队列任务执行");
}
public void FindDataAlarm()
{
devModel?.operatingDeviceStatus.data?.ForEach(par =>
{
if (!string.IsNullOrEmpty(par.clientId))
{
par.IsAlarm = alarmController.QueryClientProcess(par.clientId);
}
});
}
///
/// 加载店铺信息
///
///
public void LoadingShopInformation(string clientId = "")
{
try
{
devStatuses = devModel.operatingDeviceStatus.data;
ConsoleHelper.WriteSuccessLine("加载店铺集合中.");
JsonMsg> jsonMsg = deviceController.Query("", "", DateTime.MinValue, DateTime.MinValue);
if (jsonMsg?.obj?.data.Count > 0)
{
//if ((devStatuses.Count != devModel.operatingDeviceStatus.data.Count) || devStatuses.Count<=0)
{
devModel.operatingDeviceStatus.data.Clear();
jsonMsg?.obj?.data?.ForEach(par =>
{
int chid = 0;
try
{
chid = int.Parse(par.ClientId);
}
catch (Exception ex)
{
chid = 0;
}
if (chid > 0)
{
DevStatus devStatus = new DevStatus()
{
deviceName = par.devicename,
gmtCreate = par.devicesecret,
productKey = par.productkey,
DeviceMC = par.devtype,
DeviceMS = par.remark,
DeviceSJ = par.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
DeviceZT = "离线",
clientId = par.ClientId,
deviceId = par.DeviceId
};
ConsoleHelper.WriteSuccessLine($"加载设备.{par.devtype} {par.remark}");
DevStatus dev= devStatuses?.Find(k => k.deviceName == par.devicename);
if (dev != null && dev.DeviceZT == "在线") { devStatus.SetStatus(dev.DeviceZT); }
devModel.operatingDeviceStatus.data.Insert(0, devStatus);
if (dev != null && dev.DeviceZT == "在线")
{
OnOrOffline(dev.DeviceZT, devModel.operatingDeviceStatus.data, devStatus);
}
}
});
ConsoleHelper.WriteSuccessLine($"加载设备数[ {jsonMsg?.obj?.data?.Count} ]台...");
}
}
else
{
ConsoleHelper.WriteSuccessLine("查询店铺集合为空.");
}
}
catch (Exception ex)
{
ConsoleHelper.WriteErrorLine($"错误{ex.Message}");
}
}
///
/// 订阅主题
///
///
public void Subscribe(string subscribe)
{
IOTDevServer.GetInstance().IOT_Subscribe(subscribe);
ConsoleHelper.WriteSuccessLine("订阅主题: " + subscribe);
}
public void Publish(string PubTopic, CommandModel command)
{
ConsoleHelper.WriteWarningLine("发送数据 " + PubTopic + Tools.JsonConvertTools(command));
IOTDevServer.GetInstance().IOT_Publish(PubTopic, Tools.JsonConvertTools(command));
}
///
/// 更新内存集合
///
///
public void SentData(ReceiveModel receiveModel)
{
try
{
if (receiveModel?.deviceContext != null && receiveModel?.status != null)//状态变更消息
{
devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName)?.SetStatus(receiveModel.status.value);
//devModel?.infoMessage?.data?.Add(new DeviceBase { DeviceMC = receiveModel.deviceContext.deviceName, DeviceMS = $"设备{receiveModel.status.value}了!", DeviceSJ = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
DevStatus dev = devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName);
if (dev == null) { LoadingShopInformation(); }
dev = devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName);
if (dev != null)
{
logController.Create(new LogTable
{
devicename = receiveModel.deviceContext.deviceName,
ClientId = dev.clientId,
DeviceId = dev.deviceId,
LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
LogType = "提示",
LogMessage = $"设备{receiveModel.status.value}了!",
LogVla = "通知"
});
OnOrOffline(receiveModel.status.value, devModel.operatingDeviceStatus.data, dev);
}
else
{
LoadingShopInformation();
}
}
//devModel.OrderLine = orderProvider.OrderLine(new DataVApi.Order.RequestModel.FullScreenBasic());
//devModel.OrderDataState = orderProvider.GetAllOrderDataState(new DataVApi.Order.RequestModel.FullScreenInput());
////devModel.LocSale = orderProvider.GetLocSale();
//object obj = orderProvider.OrderNumber(new DataVApi.Order.RequestModel.FullScreenBasic());
//devModel.OrderNumber = Tools.JsonToObjectTools(Tools.JsonConvertTools(obj));
ScreenMonitorModel screen1Monitor = Tools.JsonToObjectTools(devModel.ToJSON());
#region 1.设置data默认值
//if (screen1Monitor.operatingDeviceStatus.data.Count == 0)
//{
// screen1Monitor.operatingDeviceStatus.data.Add(new DevStatus { DeviceMC = "", DeviceMS = "", DeviceSJ = "", deviceName = "", DeviceZT = "", gmtCreate = "" });
//}
//if (screen1Monitor.infoMessage.data.Count == 0)
//{
// screen1Monitor.infoMessage.data.Add(new DeviceBase { DeviceMC = "", DeviceMS = "", DeviceSJ = "" });
//}
#endregion
string JSON = screen1Monitor.ToJSON();
if (!string.IsNullOrEmpty(JSON))
{
//screenController.CreateOrUpdate(new LargeScreenTable() { json = JSON, devicename = "Transit", ClientId = "-10", DeviceId = "-10" });
IOTDevServer.GetInstance().IOT_Publish(IOTDevServer.ScreenShowPubTopic, JSON);
}
//if (devModel.infoMessage.data != null && devModel.infoMessage.data.Count > 0)
//{
// List bases = devModel.infoMessage.data.ToList();
// bases?.ForEach(par =>
// {
// if (string.IsNullOrEmpty(par.DeviceMC)) devModel.infoMessage.data.Remove(par);
// if (!string.IsNullOrEmpty(par.DeviceSJ) && DateTime.Now.AddSeconds(-5) > DateTime.Parse(par.DeviceSJ))
// {
// devModel.infoMessage.data.Remove(par);
// }
// });
//}
}
catch (Exception ex)
{
ConsoleHelper.WriteErrorLine($"错误{ex.Message}");
}
}
///
/// 上下线调整
///
///
///
///
///
///
private static List OnOrOffline(string status, List list, T present)
{
int now = list.IndexOf(present);
switch (status)
{
case "离线":
list.Remove(present);
list.Add(present);
break;
default:
//在线
list.Remove(present);
list.Insert(0, present);
break;
}
return list;
}
///
/// list 位置交换
///
///
///
///
///
///
private static List Swap(List list, int index1, int index2)
{
var temp = list[index1];
list[index1] = list[index2];
list[index2] = temp;
return list;
}
///
/// MQTT 消息
///
///
///
private void DevIOTActionHandler(string topic, string message)
{
if (string.IsNullOrEmpty(topic)) return;
if (topic == IOTDevServer.HeartbeatSubTopic)//上下线订阅主题
{
ReceiveModel receiveModel = Tools.JsonToObjectTools(message);
if (receiveModel != null && receiveModel.status != null)//上下线通知
{
if (receiveModel.deviceContext.deviceName != "Transit" && receiveModel.deviceContext.deviceName != "Transit_Test")
{
ConsoleHelper.WriteWarningLine("接收数据 " + topic + " 数据 " + message);
SentData(receiveModel);
}
}
}
else if (topic == IOTDevServer.BroadcastTopic)//广播主题
{
if (message.Contains("AlarmType"))
{
AlarmTable alarm = Tools.JsonToObjectTools(message);
if (alarm.State == "n")
{
AlarmTable al = alarmController.mg.QueryKeyID(alarm.KeyID);
if (al != null)
{
alarmController.mg.Modify(al.Id, "State", "n");
}
}
else
{
alarmController.Create(alarm);
}
FindDataAlarm();
}
else if (message.Contains("LogType"))
{
logController.Create(Tools.JsonToObjectTools(message));
}
else if (message == "刷新店铺列表")
{
LoadingShopInformation();
}
}
//else if (topic == IOTDevServer.TargetStatusSubTopic)//属性变更
//{
// ReceiveModel rEmodel = Tools.JsonToObjectTools(message);
// string name= rEmodel.deviceContext.deviceName;
// string status = rEmodel.props.NodeStatus.value;
// string id = deviceController.QueryDeviceName(name)?.obj?.data?.ClientId;
// screenController.CreateOrUpdate(new LargeScreenTable() { json = status, devicename = name, ClientId = id, DeviceId = "" });
//}
}
}
}