终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

458 rivejä
16 KiB

  1. using BPA.Communication;
  2. using BPA.Helper;
  3. using BPA.Message;
  4. using IWshRuntimeLibrary;
  5. using Microsoft.Web.WebView2.Wpf;
  6. using Newtonsoft.Json;
  7. using System;
  8. using System.Collections;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.Drawing;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using System.Windows.Controls;
  19. using System.Windows.Forms;
  20. using System.Windows.Shapes;
  21. using System.Xml;
  22. namespace BPASmartClient.ScreenLib
  23. {
  24. /// <summary>
  25. /// 主函数
  26. /// </summary>
  27. public class Main
  28. {
  29. #region 接口继承变量
  30. /// <summary>
  31. /// MQTT连接信息
  32. /// </summary>
  33. public string MQTTConnection { get; set; }
  34. /// <summary>
  35. /// 业务名称
  36. /// </summary>
  37. private string _Name = string.Empty;
  38. public string Name
  39. {
  40. get { return _Name; }
  41. set
  42. {
  43. _Name = value;
  44. ThreadServer();
  45. }
  46. }
  47. /// <summary>
  48. /// 是否自动重启(出现健康检查未通过时)
  49. /// </summary>
  50. public bool AutoRestart { get; set; }
  51. #endregion
  52. #region 自建变量
  53. /// <summary>
  54. /// 分餐机广告
  55. /// </summary>
  56. public List<AdDTO> SaasRouteReturn =new List<AdDTO> { };
  57. /// <summary>
  58. /// 是否运行
  59. /// </summary>
  60. public bool IsRunning { get; set; }
  61. /// <summary>
  62. /// Mqtt是否运行
  63. /// </summary>
  64. public bool IsRunningMqtt = false;
  65. /// <summary>
  66. /// Mqtt
  67. /// </summary>
  68. public MqttHelper mqttHelper = new MqttHelper();
  69. /// <summary>
  70. /// 主函数
  71. /// </summary>
  72. private static volatile Main _Instance;
  73. public static Main GetInstance => _Instance ?? (_Instance = new Main());
  74. public Main()
  75. {
  76. ReadPZ();
  77. if (PZdic.ContainsKey("MQTTConnection"))
  78. MQTTConnection = PZdic["MQTTConnection"];
  79. if (PZdic.ContainsKey("DeviceMC"))
  80. Name = PZdic["DeviceMC"];
  81. mqttDatasDic[ScreenDeviceType.大炒] = new ScreenModelMaxWok();
  82. mqttDatasDic[ScreenDeviceType.小炒] = new ScreenModelMinWok();
  83. mqttDatasDic[ScreenDeviceType.分餐机] = new ScreenModelSplitMeals();
  84. mqttDatasDic[ScreenDeviceType.煮面机] = new ScreenModelMorkS();
  85. }
  86. /// <summary>
  87. /// 设备数据
  88. /// </summary>
  89. public Dictionary<ScreenDeviceType, object> mqttDatasDic = new Dictionary<ScreenDeviceType, object>();
  90. /// <summary>
  91. /// 配置数据
  92. /// </summary>
  93. public Dictionary<string,string> PZdic=new Dictionary<string,string>();
  94. /// <summary>
  95. /// Mqtt消息队列
  96. /// </summary>
  97. public ConcurrentQueue<string> msg = new ConcurrentQueue<string>();
  98. #endregion
  99. #region 线程处理函数
  100. /// <summary>
  101. /// 线程服务
  102. /// </summary>
  103. public void ThreadServer()
  104. {
  105. TaskManage.GetInstance.StartLong(new Action(() =>
  106. {
  107. try
  108. {
  109. if (IsRunning && IsRunningMqtt)
  110. {
  111. if (msg.Count > 0 && msg.TryDequeue(out string s))
  112. {
  113. SendScreenDataModel read= JsonConvert.DeserializeObject<SendScreenDataModel>(s);
  114. if (read != null && read.Value!=null)
  115. {
  116. switch (read.Name)
  117. {
  118. case ScreenDeviceType.大炒:
  119. mqttDatasDic[read.Name] = JsonConvert.DeserializeObject<ScreenModelMaxWok>(read.Value.ToString());
  120. break;
  121. case ScreenDeviceType.小炒:
  122. mqttDatasDic[read.Name] = JsonConvert.DeserializeObject<ScreenModelMinWok>(read.Value.ToString());
  123. break;
  124. case ScreenDeviceType.分餐机:
  125. mqttDatasDic[read.Name] = JsonConvert.DeserializeObject<ScreenModelSplitMeals>(read.Value.ToString());
  126. break;
  127. case ScreenDeviceType.煮面机:
  128. mqttDatasDic[read.Name] = JsonConvert.DeserializeObject<ScreenModelMorkS>(read.Value.ToString());
  129. break;
  130. }
  131. }
  132. }
  133. }
  134. }
  135. catch (Exception ex)
  136. {
  137. MessageLog.GetInstance.ShowEx($"{Name}:线程服务异常,原因:{ex.Message}");
  138. }
  139. Thread.Sleep(100);
  140. }), $"{Name},线程服务");
  141. }
  142. #endregion
  143. #region 启动、停止、健康检查
  144. /// <summary>
  145. /// 开始服务
  146. /// </summary>
  147. public void Start()
  148. {
  149. try
  150. {
  151. ReadSass();
  152. //连接MQTT、Redis
  153. Connection();
  154. IsRunning = true;
  155. }
  156. catch (Exception ex)
  157. {
  158. MessageLog.GetInstance.ShowEx($"{Name}:MQTT或者Redis启动时,连接失败,原因:{ex.Message}");
  159. }
  160. }
  161. /// <summary>
  162. ///
  163. /// </summary>
  164. public void StartServer()
  165. {
  166. string path = System.Configuration.ConfigurationManager.AppSettings["StartServer"].ToString();
  167. string processName = "";
  168. try
  169. {
  170. if (System.IO.File.Exists(path))
  171. {
  172. processName = System.IO.Path.GetFileNameWithoutExtension(path);
  173. if (!IsProcess(processName))
  174. {
  175. Process.Start(path);
  176. }
  177. TaskManage.GetInstance.StartLong(new Action(() =>
  178. {
  179. try
  180. {
  181. if (!IsProcess(processName))
  182. {
  183. Process.Start(path);
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. MessageLog.GetInstance.ShowEx($"{Name}:线程服务异常,原因:{ex.Message}");
  189. }
  190. Thread.Sleep(3000);
  191. }), $"{Name},进程监控");
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. }
  197. }
  198. public bool IsProcess(string procName)
  199. {
  200. bool isProcess = false;
  201. Process[] ps = Process.GetProcessesByName(procName);
  202. if (ps.Length > 0)
  203. {
  204. isProcess=true;
  205. }
  206. return isProcess;
  207. }
  208. /// <summary>
  209. /// 关闭进程
  210. /// </summary>
  211. /// <param name="procName"></param>
  212. /// <returns></returns>
  213. public bool CloseProc(string procName)
  214. {
  215. bool result = false;
  216. ArrayList procList = new ArrayList();
  217. string tempName;
  218. int begpos;
  219. int endpos;
  220. foreach (Process thisProc in Process.GetProcesses())
  221. {
  222. tempName = thisProc.ToString();
  223. begpos = tempName.IndexOf("(") + 1;
  224. endpos = tempName.IndexOf(")");
  225. tempName = tempName[begpos..endpos];
  226. procList.Add(tempName);
  227. if (tempName == procName)
  228. {
  229. if (!thisProc.CloseMainWindow())
  230. // 当发送关闭窗口命令无效时强行结束进程
  231. thisProc.Kill();
  232. result = true;
  233. }
  234. }
  235. return result;
  236. }
  237. /// <summary>
  238. /// 停止服务
  239. /// </summary>
  240. public void Stop()
  241. {
  242. try
  243. {
  244. //0.设置运行标志
  245. IsRunning = false;
  246. mqttHelper.CloseConnect();
  247. }
  248. catch (Exception ex)
  249. {
  250. MessageLog.GetInstance.ShowEx($"{Name}:MQTT或者Redis停止时异常,原因:{ex.Message}");
  251. }
  252. }
  253. /// <summary>
  254. /// 健康检查
  255. /// </summary>
  256. /// <param name="msg"></param>
  257. /// <returns></returns>
  258. public bool Check(out string msg)
  259. {
  260. string msgage = string.Empty;
  261. bool IsTrue = false;
  262. if (IsRunningMqtt && IsRunning)
  263. IsTrue = true;
  264. else
  265. {
  266. if (!IsRunningMqtt)
  267. msgage += "Redis断开连接.";
  268. IsTrue = false;
  269. msgage = $"{Name}:健康检查失败,原因:{msgage}";
  270. }
  271. msg = msgage;
  272. return IsTrue;
  273. }
  274. #endregion
  275. #region 调用事件
  276. /// <summary>
  277. /// 调用Sass接口拿到广告
  278. /// </summary>
  279. public void ReadSass()
  280. {
  281. try
  282. {
  283. string SaasRoute = System.Configuration.ConfigurationManager.AppSettings["SaasRoute"].ToString();
  284. string res = APIHelper.GetInstance.GetRequest(SaasRoute);
  285. if (!string.IsNullOrEmpty(res))
  286. {
  287. HttpReturn httpReturn= JsonConvert.DeserializeObject<HttpReturn>(res);
  288. var Init =httpReturn?.data?.Devices?.Join(httpReturn?.data?.Stalls, t => t.GateId, x => x.Id, (t, x) => new AdDTO
  289. {
  290. Ad = x.Remaek,
  291. Device = t.Name,
  292. Stalls = x.Name,
  293. Address = t.Address,
  294. }).ToList();
  295. SaasRouteReturn= Init;
  296. }
  297. }
  298. catch (Exception ex)
  299. {
  300. }
  301. }
  302. /// <summary>
  303. /// 显示地址
  304. /// </summary>
  305. /// <param name="input"></param>
  306. /// <param name="view2"></param>
  307. public async void InitView2(string input, WebView2 view2, System.Windows.Controls.GroupBox group)
  308. {
  309. var height = 540;
  310. var width = 940;
  311. input = input.Replace("style=\"width: 100%;\"", "");
  312. StringBuilder sb = new StringBuilder();
  313. sb.Append("<html><style>body {width: " + width + "px;height: " + height + "px;margin: 0;padding:0;}body p {width: " + width + "px;height: " + height + "px;}body p img {width: 100%;height: 100%;}</style><script>function Set(width, height) { var body = document.getElementsByTagName('body')[0]; body.style.width = width + 'px';body.style.height = height + 'px';var p = document.getElementsByTagName('p')[0]; p.style.width = width + 'px';p.style.height = height + 'px';}</script><body>" + input + "</body></html>");
  314. var html = sb.ToString();
  315. string name = $"{Application.StartupPath}\\Html\\{Name}.html";
  316. if (!System.IO.Directory.Exists($"{Application.StartupPath}\\Html"))
  317. {
  318. System.IO.Directory.CreateDirectory($"{Application.StartupPath}\\Html");//不存在就创建文件夹 }
  319. }
  320. if (!System.IO.File.Exists(name))
  321. {
  322. //----------生成htm文件------------------――
  323. try
  324. {
  325. using (StreamWriter sw = new StreamWriter(name, false, System.Text.Encoding.GetEncoding("UTF-8"))) //保存地址
  326. {
  327. sw.WriteLine(html);
  328. sw.Flush();
  329. sw.Close();
  330. }
  331. }
  332. catch
  333. {
  334. }
  335. }
  336. else
  337. {
  338. string text = System.IO.File.ReadAllText(name);
  339. if (text.Replace("\r\n", "") != html)
  340. {
  341. try
  342. {
  343. using (StreamWriter sw = new StreamWriter(name, false, System.Text.Encoding.GetEncoding("UTF-8"))) //保存地址
  344. {
  345. sw.WriteLine(html);
  346. sw.Flush();
  347. sw.Close();
  348. }
  349. }
  350. catch
  351. {
  352. }
  353. }
  354. }
  355. view2.Source = new Uri(name);
  356. }
  357. /// <summary>
  358. /// 读取配置
  359. /// </summary>
  360. public void ReadPZ()
  361. {
  362. System.Configuration.ConfigurationManager.AppSettings.AllKeys?.ToList().ForEach(key => {
  363. PZdic[key]= System.Configuration.ConfigurationManager.AppSettings[key].ToString();
  364. });
  365. }
  366. /// <summary>
  367. /// 初始化连接Redis MQTT
  368. /// </summary>
  369. public void Connection()
  370. {
  371. try
  372. {
  373. //2.Mqtt连接
  374. if (!string.IsNullOrEmpty(this.MQTTConnection) && this.MQTTConnection.Contains(','))
  375. {
  376. string[] mqttcom = this.MQTTConnection.Split(',');
  377. if (mqttcom != null && mqttcom.Count() == 4)
  378. {
  379. mqttHelper.Connect(mqttcom[2], mqttcom[3], mqttcom[0], int.Parse(mqttcom[1]), $"{Name}:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
  380. }
  381. }
  382. mqttHelper.Disconnect = new Action(() =>
  383. {
  384. IsRunningMqtt = false;
  385. MessageLog.GetInstance.ShowEx($"{Name}:MQTT异常断开....");
  386. });
  387. mqttHelper.ConnectOk = new Action(() =>
  388. {
  389. IsRunningMqtt = true;//连接成功
  390. if (Name.Contains(","))
  391. {
  392. Name.Split(',')?.ToList().ForEach(x =>
  393. {
  394. if (x == "大炒")
  395. {
  396. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.大炒));
  397. }else if (x == "小炒")
  398. {
  399. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.小炒));
  400. }
  401. else if (x == "分餐机")
  402. {
  403. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.分餐机));
  404. }
  405. else if (x == "煮面机")
  406. {
  407. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.煮面机));
  408. }
  409. });
  410. }
  411. else
  412. {
  413. if (Name == "大炒")
  414. {
  415. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.大炒));
  416. }
  417. else if (Name == "小炒")
  418. {
  419. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.小炒));
  420. }
  421. else if (Name == "分餐机")
  422. {
  423. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.分餐机));
  424. }
  425. else if (Name == "煮面机")
  426. {
  427. mqttHelper.Subscrib(ScreenTOPIC.GetInstance.GetTopic(ScreenDeviceType.煮面机));
  428. }
  429. }
  430. });
  431. mqttHelper.MessageRecive = new Action<string>((s) => { msg.Enqueue(s); });
  432. }
  433. catch (Exception ex)
  434. {
  435. MessageLog.GetInstance.ShowEx($"{Name}:初始化连接 MQTT,原因:{ex.Message}");
  436. }
  437. }
  438. #endregion
  439. }
  440. }