using BPA.Communication;
using BPA.Helper;
using BPA.Message;
using IWshRuntimeLibrary;
using Microsoft.Web.WebView2.Wpf;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Shapes;
using System.Xml;
namespace BPASmartClient.ScreenLib
{
///
/// 主函数
///
public class Main
{
#region 接口继承变量
///
/// MQTT连接信息
///
public string MQTTConnection { get; set; }
///
/// 业务名称
///
private string _Name = string.Empty;
public string Name
{
get { return _Name; }
set
{
_Name = value;
ThreadServer();
}
}
///
/// 是否自动重启(出现健康检查未通过时)
///
public bool AutoRestart { get; set; }
#endregion
#region 自建变量
///
/// 分餐机广告
///
public List SaasRouteReturn =new List { };
///
/// 是否运行
///
public bool IsRunning { get; set; }
///
/// Mqtt是否运行
///
public bool IsRunningMqtt = false;
///
/// Mqtt
///
public MqttHelper mqttHelper = new MqttHelper();
///
/// 主函数
///
private static volatile Main _Instance;
public static Main GetInstance => _Instance ?? (_Instance = new Main());
public Main()
{
ReadPZ();
if (PZdic.ContainsKey("MQTTConnection"))
MQTTConnection = PZdic["MQTTConnection"];
if (PZdic.ContainsKey("DeviceMC"))
Name = PZdic["DeviceMC"];
mqttDatasDic[ScreenDeviceType.大炒] = new ScreenModelMaxWok();
mqttDatasDic[ScreenDeviceType.小炒] = new ScreenModelMinWok();
mqttDatasDic[ScreenDeviceType.分餐机] = new ScreenModelSplitMeals();
mqttDatasDic[ScreenDeviceType.煮面机] = new ScreenModelMorkS();
}
///
/// 设备数据
///
public Dictionary mqttDatasDic = new Dictionary();
///
/// 配置数据
///
public Dictionary PZdic=new Dictionary();
///
/// Mqtt消息队列
///
public ConcurrentQueue msg = new ConcurrentQueue();
#endregion
#region 线程处理函数
///
/// 线程服务
///
public void ThreadServer()
{
TaskManage.GetInstance.StartLong(new Action(() =>
{
try
{
if (IsRunning && IsRunningMqtt)
{
if (msg.Count > 0 && msg.TryDequeue(out string s))
{
SendScreenDataModel read= JsonConvert.DeserializeObject(s);
if (read != null && read.Value!=null)
{
switch (read.Name)
{
case ScreenDeviceType.大炒:
mqttDatasDic[read.Name] = JsonConvert.DeserializeObject(read.Value.ToString());
break;
case ScreenDeviceType.小炒:
mqttDatasDic[read.Name] = JsonConvert.DeserializeObject(read.Value.ToString());
break;
case ScreenDeviceType.分餐机:
mqttDatasDic[read.Name] = JsonConvert.DeserializeObject(read.Value.ToString());
break;
case ScreenDeviceType.煮面机:
mqttDatasDic[read.Name] = JsonConvert.DeserializeObject(read.Value.ToString());
break;
}
}
}
}
}
catch (Exception ex)
{
MessageLog.GetInstance.ShowEx($"{Name}:线程服务异常,原因:{ex.Message}");
}
Thread.Sleep(100);
}), $"{Name},线程服务");
}
#endregion
#region 启动、停止、健康检查
///
/// 开始服务
///
public void Start()
{
try
{
ReadSass();
//连接MQTT、Redis
Connection();
IsRunning = true;
}
catch (Exception ex)
{
MessageLog.GetInstance.ShowEx($"{Name}:MQTT或者Redis启动时,连接失败,原因:{ex.Message}");
}
}
///
///
///
public void StartServer()
{
string path = System.Configuration.ConfigurationManager.AppSettings["StartServer"].ToString();
string processName = "";
try
{
if (System.IO.File.Exists(path))
{
processName = System.IO.Path.GetFileNameWithoutExtension(path);
if (!IsProcess(processName))
{
Process.Start(path);
}
TaskManage.GetInstance.StartLong(new Action(() =>
{
try
{
if (!IsProcess(processName))
{
Process.Start(path);
}
}
catch (Exception ex)
{
MessageLog.GetInstance.ShowEx($"{Name}:线程服务异常,原因:{ex.Message}");
}
Thread.Sleep(3000);
}), $"{Name},进程监控");
}
}
catch (Exception ex)
{
}
}
public bool IsProcess(string procName)
{
bool isProcess = false;
Process[] ps = Process.GetProcessesByName(procName);
if (ps.Length > 0)
{
isProcess=true;
}
return isProcess;
}
///
/// 关闭进程
///
///
///
public bool CloseProc(string procName)
{
bool result = false;
ArrayList procList = new ArrayList();
string tempName;
int begpos;
int endpos;
foreach (Process thisProc in Process.GetProcesses())
{
tempName = thisProc.ToString();
begpos = tempName.IndexOf("(") + 1;
endpos = tempName.IndexOf(")");
tempName = tempName[begpos..endpos];
procList.Add(tempName);
if (tempName == procName)
{
if (!thisProc.CloseMainWindow())
// 当发送关闭窗口命令无效时强行结束进程
thisProc.Kill();
result = true;
}
}
return result;
}
///
/// 停止服务
///
public void Stop()
{
try
{
//0.设置运行标志
IsRunning = false;
mqttHelper.CloseConnect();
}
catch (Exception ex)
{
MessageLog.GetInstance.ShowEx($"{Name}:MQTT或者Redis停止时异常,原因:{ex.Message}");
}
}
///
/// 健康检查
///
///
///
public bool Check(out string msg)
{
string msgage = string.Empty;
bool IsTrue = false;
if (IsRunningMqtt && IsRunning)
IsTrue = true;
else
{
if (!IsRunningMqtt)
msgage += "Redis断开连接.";
IsTrue = false;
msgage = $"{Name}:健康检查失败,原因:{msgage}";
}
msg = msgage;
return IsTrue;
}
#endregion
#region 调用事件
///
/// 调用Sass接口拿到广告
///
public void ReadSass()
{
try
{
string SaasRoute = System.Configuration.ConfigurationManager.AppSettings["SaasRoute"].ToString();
string res = APIHelper.GetInstance.GetRequest(SaasRoute);
if (!string.IsNullOrEmpty(res))
{
HttpReturn httpReturn= JsonConvert.DeserializeObject(res);
var Init =httpReturn?.data?.Devices?.Join(httpReturn?.data?.Stalls, t => t.GateId, x => x.Id, (t, x) => new AdDTO
{
Ad = x.Remaek,
Device = t.Name,
Stalls = x.Name,
Address = t.Address,
}).ToList();
SaasRouteReturn= Init;
}
}
catch (Exception ex)
{
}
}
///
/// 显示地址
///
///
///
public async void InitView2(string input, WebView2 view2, System.Windows.Controls.GroupBox group)
{
var height = 540;
var width = 940;
input = input.Replace("style=\"width: 100%;\"", "");
StringBuilder sb = new StringBuilder();
sb.Append("" + input + "");
var html = sb.ToString();
string name = $"{Application.StartupPath}\\Html\\{Name}.html";
if (!System.IO.Directory.Exists($"{Application.StartupPath}\\Html"))
{
System.IO.Directory.CreateDirectory($"{Application.StartupPath}\\Html");//不存在就创建文件夹 }
}
if (!System.IO.File.Exists(name))
{
//----------生成htm文件------------------――
try
{
using (StreamWriter sw = new StreamWriter(name, false, System.Text.Encoding.GetEncoding("UTF-8"))) //保存地址
{
sw.WriteLine(html);
sw.Flush();
sw.Close();
}
}
catch
{
}
}
else
{
string text = System.IO.File.ReadAllText(name);
if (text.Replace("\r\n", "") != html)
{
try
{
using (StreamWriter sw = new StreamWriter(name, false, System.Text.Encoding.GetEncoding("UTF-8"))) //保存地址
{
sw.WriteLine(html);
sw.Flush();
sw.Close();
}
}
catch
{
}
}
}
view2.Source = new Uri(name);
}
///
/// 读取配置
///
public void ReadPZ()
{
System.Configuration.ConfigurationManager.AppSettings.AllKeys?.ToList().ForEach(key => {
PZdic[key]= System.Configuration.ConfigurationManager.AppSettings[key].ToString();
});
}
///
/// 初始化连接Redis MQTT
///
public void Connection()
{
try
{
//2.Mqtt连接
if (!string.IsNullOrEmpty(this.MQTTConnection) && this.MQTTConnection.Contains(','))
{
string[] mqttcom = this.MQTTConnection.Split(',');
if (mqttcom != null && mqttcom.Count() == 4)
{
mqttHelper.Connect(mqttcom[2], mqttcom[3], mqttcom[0], int.Parse(mqttcom[1]), $"{Name}:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
}
}
mqttHelper.Disconnect = new Action(() =>
{
IsRunningMqtt = false;
MessageLog.GetInstance.ShowEx($"{Name}:MQTT异常断开....");
});
mqttHelper.ConnectOk = new Action(() =>
{
IsRunningMqtt = true;//连接成功
if (Name.Contains(","))
{
Name.Split(',')?.ToList().ForEach(x =>
{
if (x == "大炒")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.大炒));
}else if (x == "小炒")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.小炒));
}
else if (x == "分餐机")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.分餐机));
}
else if (x == "煮面机")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.煮面机));
}
});
}
else
{
if (Name == "大炒")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.大炒));
}
else if (Name == "小炒")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.小炒));
}
else if (Name == "分餐机")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.分餐机));
}
else if (Name == "煮面机")
{
mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.煮面机));
}
}
});
mqttHelper.MessageRecive = new Action((s) => { msg.Enqueue(s); });
}
catch (Exception ex)
{
MessageLog.GetInstance.ShowEx($"{Name}:初始化连接 MQTT,原因:{ex.Message}");
}
}
#endregion
}
}