终端一体化运控平台
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

609 řádky
23 KiB

  1. using BPA.Message;
  2. using BPA.Message.Enum;
  3. using BPASmartClient.Model;
  4. using BPASmartClient.Peripheral;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Collections.ObjectModel;
  14. using BPASmartClient.Model.单片机;
  15. using BPA.Models;
  16. using BPA.Helper;
  17. namespace BPASmartClient.Device
  18. {
  19. /// <summary>
  20. /// 设备基类
  21. /// </summary>
  22. public abstract class BaseDevice : IDevice
  23. {
  24. public BaseDevice()
  25. {
  26. }
  27. #region 属性
  28. /// <summary>
  29. /// 订单物料信息
  30. /// </summary>
  31. public OrderMaterialDelivery orderMaterialDelivery { get; set; } = new OrderMaterialDelivery();
  32. /// <summary>
  33. /// 配方数据信息
  34. /// </summary>
  35. public RecipeBoms recipeBoms { get; set; } = new RecipeBoms();
  36. /// <summary>
  37. /// 设备ID
  38. /// </summary>
  39. public int DeviceId { get; set; }
  40. /// <summary>
  41. /// 设备所有状态
  42. /// </summary>
  43. public DeviceStatus Status { get; set; } = new DeviceStatus();
  44. /// <summary>
  45. /// 设备名称
  46. /// </summary>
  47. public string Name { get; set; }
  48. /// <summary>
  49. /// 当前订单数量
  50. /// </summary>
  51. protected int OrderCount { get; set; }
  52. /// <summary>
  53. /// 设备初始化中
  54. /// </summary>
  55. protected bool Initing { get; set; }
  56. /// <summary>
  57. /// 设备类型
  58. /// </summary>
  59. public abstract DeviceClientType DeviceType { get; }
  60. /// <summary>
  61. /// 是否忙碌
  62. /// </summary>
  63. public bool IsBusy { get; protected set; }
  64. /// <summary>
  65. /// 是否健康
  66. /// </summary>
  67. public bool IsHealth { get; protected set; }
  68. /// <summary>
  69. /// 设备运行日志
  70. /// </summary>
  71. public List<object> Log { get; set; } = new List<object>();
  72. /// <summary>
  73. /// 设备运行告警与错误
  74. /// </summary>
  75. public List<object> Error { get; set; } = new List<object>();
  76. /// <summary>
  77. /// mork_F暂用余量列表
  78. /// </summary>
  79. public List<BatchingInfo> BatchingInfos { get; set; } = new List<BatchingInfo>();
  80. /// <summary>
  81. /// 设备变量监控
  82. /// </summary>
  83. public ObservableCollection<VariableMonitor> variableMonitors { get; set; } = new ObservableCollection<VariableMonitor>();
  84. /// <summary>
  85. /// 外设状态,硬件设备数据
  86. /// </summary>
  87. protected ConcurrentDictionary<string, object> peripheralStatus = new ConcurrentDictionary<string, object>();
  88. protected
  89. /// <summary>
  90. /// 外设设备集合
  91. /// </summary>
  92. private List<IPeripheral> peripherals;
  93. /// <summary>
  94. /// <炒锅>:<外设状态,硬件设备数据>的键值对
  95. /// </summary>
  96. protected Dictionary<int, ConcurrentDictionary<string, object>> dicPort2peripheralStatus = new Dictionary<int, ConcurrentDictionary<string, object>>();
  97. public Action<int, object> AddErrorAction { get; set; }
  98. public Action<int, object> DeleteErrorAction { get; set; }
  99. public List<BPASmartClient.Model.Alarm> alarms { get; set; } = new List<BPASmartClient.Model.Alarm>();
  100. public IAlarm InterfaceAlarm { get; set; }
  101. public AlarmHelper alarmHelper { get; set; } = new AlarmHelper();
  102. public IStatus InterfaceStatus { get; set; }
  103. public ObservableCollection<Variable> variables { get; set; } = new ObservableCollection<Variable>();
  104. #endregion
  105. /// <summary>
  106. /// 写控制
  107. /// </summary>
  108. /// <param name="address"></param>
  109. /// <param name="value"></param>
  110. public void WriteControl(string address, object value)
  111. {
  112. if (peripherals != null)
  113. {
  114. for (int i = 0; i < peripherals.Count; i++)
  115. {
  116. peripherals.ElementAt(i).WriteData(address, value);
  117. }
  118. }
  119. }
  120. /// <summary>
  121. /// 多设备分开写控制
  122. /// </summary>
  123. /// <param name="address"></param>
  124. /// <param name="value"></param>
  125. public void WriteControlExact(string address, object value, int i)
  126. {
  127. if (peripherals != null)
  128. {
  129. if (peripherals.Count > i)
  130. {
  131. peripherals.ElementAt(i).WriteData(address, value);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// 设备过程日志显示
  137. /// </summary>
  138. /// <param name="info"></param>
  139. public void DeviceProcessLogShow(string info)
  140. {
  141. Log.Insert(0, new { Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), Type = "流程", Text = info });
  142. //MessageLog.GetInstance.DeviceProcessLogShow(DeviceId.ToString(), info);
  143. MessageLog.GetInstance.Show($"{DeviceId.ToString()};{info}");
  144. if (Log.Count > 100) { Log.RemoveAt(Log.Count - 1); }
  145. }
  146. public void Initliaze()
  147. {
  148. }
  149. public void Initliaze(List<IPeripheral> peripherals)
  150. {
  151. peripherals.ForEach(p =>
  152. {
  153. p.DeviceId = this.DeviceId;
  154. p.Init();
  155. });
  156. this.peripherals = peripherals;
  157. }
  158. public virtual void StartMain()
  159. {
  160. TaskManage.GetInstance.StartLong(new Action(() =>
  161. {
  162. int i = 0;
  163. foreach (var peripheral in peripherals)
  164. {
  165. string TypeName = peripheral.GetType().FullName.Replace("BPASmartClient.", "");
  166. Status.Update($"{TypeName}.IsConnected", peripheral.IsConnected);
  167. Status.Update($"{TypeName}.IsWork", peripheral.IsWork);
  168. //做为炒锅与状态字典的新数据
  169. ConcurrentDictionary<string, object> newPeripheralStatus = new ConcurrentDictionary<string, object>();
  170. foreach (var key in peripheral.GetAllStatus().Keys)
  171. {
  172. peripheralStatus[key] = peripheral.GetAllStatus()[key];
  173. //新的硬件设备数据存储
  174. newPeripheralStatus[key] = peripheral.GetAllStatus()[key];
  175. if (TypeName != "PLC.PLCMachine")
  176. {
  177. Status.Update($"{TypeName}.{key}", peripheral.GetAllStatus()[key]);
  178. }
  179. }
  180. if (dicPort2peripheralStatus.ContainsKey(i))
  181. {
  182. dicPort2peripheralStatus[i] = newPeripheralStatus;
  183. }
  184. else
  185. {
  186. //将存储的新硬件设备数据放入字典中,i是作为炒锅编号。
  187. dicPort2peripheralStatus.Add(i, newPeripheralStatus);
  188. }
  189. i++;
  190. }
  191. if (AddErrorAction != null && DeleteErrorAction != null)
  192. {
  193. foreach (var item in Status.GetStatusT())
  194. {
  195. if (item.Name == "Warning" || item.Name == "Fault")
  196. {
  197. if (item.Status != "无故障" && item.Status != "无警告" && item.Status != "未发生故障")
  198. {
  199. var res = Error?.FirstOrDefault(p => p.GetType().GetProperty("Text").GetValue(p).ToString() == item.Ms);
  200. if (res == null)
  201. {
  202. object obj = new
  203. {
  204. Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  205. Type = item.Name == "Warning" ? "警告" : "故障",
  206. Text = item.Ms
  207. };
  208. Error.Add(obj);
  209. AddErrorAction?.Invoke(DeviceId, obj);
  210. }
  211. }
  212. else
  213. {
  214. var res = Error?.FirstOrDefault(p => p.GetType().GetProperty("Text").GetValue(p).ToString().Contains(item.id));
  215. if (res != null)
  216. {
  217. Error.Remove(res);
  218. DeleteErrorAction?.Invoke(DeviceId, res);
  219. }
  220. }
  221. }
  222. }
  223. }
  224. Thread.Sleep(100);
  225. }), $"GetAllStatus:{DeviceId}");
  226. DoMain();
  227. SimOrder();
  228. GetGvlStatus();
  229. InitResetTask();
  230. InitTask();
  231. }
  232. private void ResetStatus()
  233. {
  234. this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList().ForEach(item =>
  235. {
  236. var res = item.FieldType.GetInterfaces();
  237. if (res != null)
  238. {
  239. foreach (var faces in res)
  240. {
  241. if (faces.Name == "IStatus") InterfaceStatus = item.GetValue(this) as IStatus;
  242. }
  243. }
  244. });
  245. }
  246. private void GetGvlStatus()
  247. {
  248. this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList().ForEach(item =>
  249. {
  250. var res = item.FieldType.GetInterfaces();
  251. if (res != null)
  252. {
  253. foreach (var faces in res)
  254. {
  255. if (faces.Name == "IStatus")
  256. {
  257. InterfaceStatus = item.GetValue(this) as IStatus;
  258. GetMonitorData(InterfaceStatus);
  259. }
  260. else if (faces.Name == "IAlarm")
  261. {
  262. InterfaceAlarm = item.GetValue(this) as IAlarm;
  263. alarmHelper.AddAction += new Action<string>((s) =>
  264. {
  265. var res = alarmHelper.Alarms.FirstOrDefault(p => p.Info == s);
  266. if (res != null)
  267. {
  268. object obj = new
  269. {
  270. Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  271. Type = res.Grade,
  272. Text = res.Info
  273. };
  274. Error.Insert(0, obj);
  275. AddErrorAction?.Invoke(DeviceId, obj);
  276. }
  277. });
  278. alarmHelper.RemoveAction += new Action<string>((s) =>
  279. {
  280. var res = Error.FirstOrDefault(p => p.GetType().GetProperty("Text").GetValue(p).ToString() == s);
  281. if (res != null && Error.Contains(res))
  282. {
  283. Error.Remove(res);
  284. DeleteErrorAction?.Invoke(DeviceId, res);
  285. }
  286. });
  287. TaskManage.GetInstance.StartLong(new Action(() =>
  288. {
  289. AlarmMonitoring();
  290. Thread.Sleep(500);
  291. }), $"报警检测监控:{DeviceId}");
  292. }
  293. }
  294. }
  295. });
  296. }
  297. /// <summary>
  298. /// 报警监控
  299. /// </summary>
  300. /// <param name="alarm"></param>
  301. /// <param name="alarmHelper"></param>
  302. private void AlarmMonitoring()
  303. {
  304. if (InterfaceAlarm == null) return;
  305. foreach (var item in InterfaceAlarm.GetType().GetProperties())
  306. {
  307. var res = item.GetValue(InterfaceAlarm);
  308. if (res != null && res is bool blen)
  309. {
  310. if (item.CustomAttributes.Count() > 0 && item.CustomAttributes.ElementAt(0)?.ConstructorArguments.Count() > 0)
  311. {
  312. var info = item.GetCustomAttribute<AlarmAttribute>().AlarmInfo;
  313. if (info != null) alarmHelper.EdgeAlarm(blen, $"{info.ToString()}-{DeviceId}");
  314. }
  315. }
  316. }
  317. }
  318. private void InitResetTask()
  319. {
  320. #region 复位程序
  321. TaskManage.GetInstance.StartLong(new Action(() =>
  322. {
  323. if (RTrig.GetInstance($"ResetProgram:{DeviceId}").Start(Initing))
  324. {
  325. DeviceProcessLogShow("启动初始化");
  326. //记录监控数据
  327. DeviceProcessLogShow($"监控数据:【 {variableMonitors.ToJSON()} 】");
  328. TaskManage.GetInstance.StopTask($"MainTask:{DeviceId}", new Action(() =>
  329. {
  330. TaskManage.GetInstance.StopTask($"ReadData:{DeviceId}", new Action(() =>
  331. {
  332. TaskManage.GetInstance.StopTask($"GvlStatusMonitor:{DeviceId}", new Action(() =>
  333. {
  334. ActionManage.GetInstance.Send("ClearOrders");
  335. ResetProgram();
  336. ResetStatus();
  337. InitTask();
  338. }));
  339. }));
  340. }));
  341. }
  342. Thread.Sleep(10);
  343. }), $"ResetProgram:{DeviceId}");
  344. #endregion
  345. }
  346. private void InitTask()
  347. {
  348. #region 数据读取
  349. TaskManage.GetInstance.StartLong(new Action(() =>
  350. {
  351. ReadData();
  352. Thread.Sleep(10);
  353. }), $"ReadData:{DeviceId}", true);
  354. #endregion
  355. #region 任务流程
  356. TaskManage.GetInstance.StartLong(new Action(() =>
  357. {
  358. MainTask();
  359. Thread.Sleep(10);
  360. }), $"MainTask:{DeviceId}", true);
  361. #endregion
  362. #region 设备状态监控
  363. TaskManage.GetInstance.StartLong(new Action(() =>
  364. {
  365. UpdateValue(InterfaceStatus);
  366. Thread.Sleep(1000);
  367. }), $"GvlStatusMonitor:{DeviceId}");
  368. #endregion
  369. }
  370. /// <summary>
  371. /// 获取监控信息
  372. /// </summary>
  373. private void GetMonitorData(IStatus status)
  374. {
  375. if (status == null) return;
  376. List<VariableMonitor> vm = new List<VariableMonitor>();
  377. foreach (var item in status.GetType().GetProperties())
  378. {
  379. if (item.CustomAttributes.Count() > 0)
  380. {
  381. var attributeName = item.CustomAttributes.FirstOrDefault(p => p.AttributeType.Name == "VariableMonitorAttribute");
  382. if (attributeName == null) return;
  383. var plcadd = item.GetCustomAttribute<VariableMonitorAttribute>()?.PLCAddress;
  384. var modadd = item.GetCustomAttribute<VariableMonitorAttribute>()?.ModbusTcpAddress;
  385. var notes = item.GetCustomAttribute<VariableMonitorAttribute>()?.Notes;
  386. if (item.PropertyType?.BaseType?.Name == "Array")
  387. {
  388. if (plcadd?.Length > 0)
  389. {
  390. var arrayRes = item.GetValue(status, null);
  391. if (arrayRes != null && arrayRes is Array arr)
  392. {
  393. for (int i = 0; i < arr.Length; i++)
  394. {
  395. var res = vm.FirstOrDefault(p => p.VarName == $"{item.Name}_{i + 1}");
  396. if (res == null)
  397. {
  398. string[] plc = plcadd?.Substring(1).Split('.');
  399. string TempPlcAddress = string.Empty;
  400. if (plc?.Length == 2)
  401. {
  402. int add = int.Parse(plc[1]);
  403. int firstAdd = int.Parse(plc[0]);
  404. if (add >= 0 && add < 7)
  405. {
  406. add += i;
  407. }
  408. else if (add >= 7)
  409. {
  410. add = 0;
  411. firstAdd++;
  412. }
  413. plc[0] = firstAdd.ToString();
  414. plc[1] = add.ToString();
  415. TempPlcAddress = $"M{plc[0]}.{plc[1]}";
  416. }
  417. vm.Add(new VariableMonitor()
  418. {
  419. Id = vm.Count + 1,
  420. VarName = $"{item.Name}_{i + 1}",
  421. Notes = $"{notes}_{i + 1}",
  422. ModbusTcpAddress = $"{int.Parse(modadd) + i}",
  423. PLCAddress = TempPlcAddress,
  424. });
  425. }
  426. }
  427. }
  428. }
  429. else
  430. {
  431. var arrayRes = item.GetValue(status, null);
  432. if (arrayRes != null && arrayRes is Array arr)
  433. {
  434. for (int i = 0; i < arr.Length; i++)
  435. {
  436. var res = vm.FirstOrDefault(p => p.VarName == $"{item.Name}_{i + 1}");
  437. if (res == null)
  438. {
  439. vm.Add(new VariableMonitor()
  440. {
  441. Id = vm.Count + 1,
  442. VarName = $"{item.Name}_{i + 1}",
  443. Notes = $"{notes}_{i + 1}",
  444. });
  445. }
  446. }
  447. }
  448. }
  449. }
  450. else
  451. {
  452. var res = vm.FirstOrDefault(p => p.VarName == item.Name);
  453. if (res == null)
  454. {
  455. vm.Add(new VariableMonitor()
  456. {
  457. Id = vm.Count + 1,
  458. VarName = item.Name,
  459. Notes = notes,
  460. ModbusTcpAddress = modadd,
  461. PLCAddress = plcadd,
  462. });
  463. }
  464. }
  465. }
  466. }
  467. //监控列表排序
  468. //vm.OrderBy(p => p.VarName).ToList().ForEach(item => { variableMonitors.Add(item); });
  469. vm.ForEach(item => { variableMonitors.Add(item); });
  470. }
  471. /// <summary>
  472. /// 更新数据
  473. /// </summary>
  474. /// <param name="status"></param>
  475. public void UpdateValue(IStatus status)
  476. {
  477. if (status == null) return;
  478. foreach (var item in status.GetType().GetProperties())
  479. {
  480. if (item.CustomAttributes.Count() > 0)
  481. {
  482. if (item.PropertyType?.BaseType?.Name == "Array")
  483. {
  484. var arrayRes = item.GetValue(status);
  485. if (arrayRes != null && arrayRes is Array arr)
  486. {
  487. for (int i = 0; i < arr.Length; i++)
  488. {
  489. int index = Array.FindIndex(variableMonitors.ToArray(), p => p.VarName == $"{item.Name}_{i + 1}");
  490. if (index >= 0 && index < variableMonitors.Count)
  491. {
  492. variableMonitors.ElementAt(index).CurrentValue = arr.GetValue(i)?.ToString();
  493. }
  494. }
  495. }
  496. }
  497. else
  498. {
  499. int index = Array.FindIndex(variableMonitors.ToArray(), p => p.VarName == item.Name);
  500. if (index >= 0 && index < variableMonitors.Count)
  501. {
  502. variableMonitors.ElementAt(index).CurrentValue = item.GetValue(status)?.ToString();
  503. }
  504. }
  505. }
  506. }
  507. }
  508. public abstract void DoMain();
  509. public abstract void Stop();
  510. /// <summary>
  511. /// 数据读取
  512. /// </summary>
  513. public abstract void ReadData();
  514. /// <summary>
  515. /// 主流程控制
  516. /// </summary>
  517. public abstract void MainTask();
  518. /// <summary>
  519. /// 复位程序
  520. /// </summary>
  521. public abstract void ResetProgram();
  522. /// <summary>
  523. /// 模拟订单
  524. /// </summary>
  525. public abstract void SimOrder();
  526. public object GetError()
  527. {
  528. return new { data = Error };
  529. }
  530. public object GetLog()
  531. {
  532. return new { data = Log };
  533. }
  534. public object GetVariableMonitor()
  535. {
  536. return new { data = variableMonitors };
  537. }
  538. /// <summary>
  539. /// 获取某个对象中的属性值
  540. /// </summary>
  541. /// <param name="info"></param>
  542. /// <param name="field"></param>
  543. /// <returns></returns>
  544. public object GetPropertyValue(object info, string field)
  545. {
  546. if (info == null) return null;
  547. Type t = info.GetType();
  548. IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
  549. return property.First().GetValue(info, null);
  550. }
  551. }
  552. }