终端一体化运控平台
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.
 
 
 

598 lines
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<Alarm> alarms { get; set; } = new List<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"), Type = "流程", Text = info });
  142. MessageLog.GetInstance.DeviceProcessLogShow(DeviceId.ToString(), info);
  143. if (Log.Count > 100) { Log.RemoveAt(Log.Count - 1); }
  144. }
  145. public void Initliaze()
  146. {
  147. }
  148. public void Initliaze(List<IPeripheral> peripherals)
  149. {
  150. peripherals.ForEach(p =>
  151. {
  152. p.DeviceId = this.DeviceId;
  153. p.Init();
  154. });
  155. this.peripherals = peripherals;
  156. }
  157. public virtual void StartMain()
  158. {
  159. ThreadManage.GetInstance().StartLong(new Action(() =>
  160. {
  161. int i = 0;
  162. foreach (var peripheral in peripherals)
  163. {
  164. string TypeName = peripheral.GetType().FullName.Replace("BPASmartClient.", "");
  165. Status.Update($"{TypeName}.IsConnected", peripheral.IsConnected);
  166. Status.Update($"{TypeName}.IsWork", peripheral.IsWork);
  167. //做为炒锅与状态字典的新数据
  168. ConcurrentDictionary<string, object> newPeripheralStatus = new ConcurrentDictionary<string, object>();
  169. foreach (var key in peripheral.GetAllStatus().Keys)
  170. {
  171. peripheralStatus[key] = peripheral.GetAllStatus()[key];
  172. //新的硬件设备数据存储
  173. newPeripheralStatus[key] = peripheral.GetAllStatus()[key];
  174. if (TypeName != "PLC.PLCMachine")
  175. {
  176. Status.Update($"{TypeName}.{key}", peripheral.GetAllStatus()[key]);
  177. }
  178. }
  179. if (dicPort2peripheralStatus.ContainsKey(i))
  180. {
  181. dicPort2peripheralStatus[i] = newPeripheralStatus;
  182. }
  183. else
  184. {
  185. //将存储的新硬件设备数据放入字典中,i是作为炒锅编号。
  186. dicPort2peripheralStatus.Add(i, newPeripheralStatus);
  187. }
  188. i++;
  189. }
  190. if (AddErrorAction != null && DeleteErrorAction != null)
  191. {
  192. foreach (var item in Status.GetStatusT())
  193. {
  194. if (item.Name == "Warning" || item.Name == "Fault")
  195. {
  196. if (item.Status != "无故障" && item.Status != "无警告" && item.Status != "未发生故障")
  197. {
  198. var res = Error?.FirstOrDefault(p => p.GetType().GetProperty("Text").GetValue(p).ToString() == item.Ms);
  199. if (res == null)
  200. {
  201. object obj = new
  202. {
  203. Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  204. Type = item.Name == "Warning" ? "警告" : "故障",
  205. Text = item.Ms
  206. };
  207. Error.Add(obj);
  208. AddErrorAction?.Invoke(DeviceId, obj);
  209. }
  210. }
  211. else
  212. {
  213. var res = Error?.FirstOrDefault(p => p.GetType().GetProperty("Text").GetValue(p).ToString().Contains(item.id));
  214. if (res != null)
  215. {
  216. Error.Remove(res);
  217. DeleteErrorAction?.Invoke(DeviceId, res);
  218. }
  219. }
  220. }
  221. }
  222. }
  223. Thread.Sleep(100);
  224. }), $"GetAllStatus:{DeviceId}");
  225. DoMain();
  226. SimOrder();
  227. GetGvlStatus();
  228. InitResetTask();
  229. InitTask();
  230. }
  231. private void ResetStatus()
  232. {
  233. this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList().ForEach(item =>
  234. {
  235. var res = item.FieldType.GetInterfaces();
  236. if (res != null)
  237. {
  238. foreach (var faces in res)
  239. {
  240. if (faces.Name == "IStatus") InterfaceStatus = item.GetValue(this) as IStatus;
  241. }
  242. }
  243. });
  244. }
  245. private void GetGvlStatus()
  246. {
  247. this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList().ForEach(item =>
  248. {
  249. var res = item.FieldType.GetInterfaces();
  250. if (res != null)
  251. {
  252. foreach (var faces in res)
  253. {
  254. if (faces.Name == "IStatus")
  255. {
  256. InterfaceStatus = item.GetValue(this) as IStatus;
  257. GetMonitorData(InterfaceStatus);
  258. }
  259. else if (faces.Name == "IAlarm")
  260. {
  261. InterfaceAlarm = item.GetValue(this) as IAlarm;
  262. alarmHelper.AddAction += new Action<string>((s) =>
  263. {
  264. var res = alarmHelper.Alarms.FirstOrDefault(p => p.Info == s);
  265. if (res != null)
  266. {
  267. object obj = new
  268. {
  269. Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  270. Type = res.Grade,
  271. Text = res.Info
  272. };
  273. Error.Insert(0, obj);
  274. AddErrorAction?.Invoke(DeviceId, obj);
  275. }
  276. });
  277. alarmHelper.RemoveAction += new Action<string>((s) =>
  278. {
  279. var res = Error.FirstOrDefault(p => p.GetType().GetProperty("Text").GetValue(p).ToString() == s);
  280. if (res != null && Error.Contains(res))
  281. {
  282. Error.Remove(res);
  283. DeleteErrorAction?.Invoke(DeviceId, res);
  284. }
  285. });
  286. ThreadManage.GetInstance().StartLong(new Action(() =>
  287. {
  288. AlarmMonitoring();
  289. Thread.Sleep(500);
  290. }), $"报警检测监控:{DeviceId}");
  291. }
  292. }
  293. }
  294. });
  295. }
  296. /// <summary>
  297. /// 报警监控
  298. /// </summary>
  299. /// <param name="alarm"></param>
  300. /// <param name="alarmHelper"></param>
  301. private void AlarmMonitoring()
  302. {
  303. if (InterfaceAlarm == null) return;
  304. foreach (var item in InterfaceAlarm.GetType().GetProperties())
  305. {
  306. var res = item.GetValue(InterfaceAlarm);
  307. if (res != null && res is bool blen)
  308. {
  309. if (item.CustomAttributes.Count() > 0 && item.CustomAttributes.ElementAt(0)?.ConstructorArguments.Count() > 0)
  310. {
  311. var info = item.GetCustomAttribute<AlarmAttribute>().AlarmInfo;
  312. if (info != null) alarmHelper.EdgeAlarm(blen, $"{info.ToString()}-{DeviceId}");
  313. }
  314. }
  315. }
  316. }
  317. private void InitResetTask()
  318. {
  319. #region 复位程序
  320. ThreadManage.GetInstance().StartLong(new Action(() =>
  321. {
  322. if (RTrig.GetInstance($"ResetProgram:{DeviceId}").Start(Initing))
  323. {
  324. ThreadManage.GetInstance().StopTask($"MainTask:{DeviceId}", new Action(() =>
  325. {
  326. ThreadManage.GetInstance().StopTask($"ReadData:{DeviceId}", new Action(() =>
  327. {
  328. ThreadManage.GetInstance().StopTask($"GvlStatusMonitor:{DeviceId}", new Action(() =>
  329. {
  330. ActionManage.GetInstance.Send("ClearOrders");
  331. ResetProgram();
  332. ResetStatus();
  333. InitTask();
  334. }));
  335. }));
  336. }));
  337. }
  338. Thread.Sleep(10);
  339. }), $"ResetProgram:{DeviceId}");
  340. #endregion
  341. }
  342. private void InitTask()
  343. {
  344. #region 数据读取
  345. ThreadManage.GetInstance().StartLong(new Action(() =>
  346. {
  347. ReadData();
  348. Thread.Sleep(10);
  349. }), $"ReadData:{DeviceId}", true);
  350. #endregion
  351. #region 任务流程
  352. ThreadManage.GetInstance().StartLong(new Action(() =>
  353. {
  354. MainTask();
  355. Thread.Sleep(10);
  356. }), $"MainTask:{DeviceId}", true);
  357. #endregion
  358. #region 设备状态监控
  359. ThreadManage.GetInstance().StartLong(new Action(() =>
  360. {
  361. UpdateValue(InterfaceStatus);
  362. Thread.Sleep(1000);
  363. }), $"GvlStatusMonitor:{DeviceId}");
  364. #endregion
  365. }
  366. /// <summary>
  367. /// 获取监控信息
  368. /// </summary>
  369. private void GetMonitorData(IStatus status)
  370. {
  371. if (status == null) return;
  372. foreach (var item in status.GetType().GetProperties())
  373. {
  374. if (item.CustomAttributes.Count() > 0)
  375. {
  376. var attributeName = item.CustomAttributes.FirstOrDefault(p => p.AttributeType.Name == "VariableMonitorAttribute");
  377. if (attributeName == null) return;
  378. var plcadd = item.GetCustomAttribute<VariableMonitorAttribute>()?.PLCAddress;
  379. var modadd = item.GetCustomAttribute<VariableMonitorAttribute>()?.ModbusTcpAddress;
  380. var notes = item.GetCustomAttribute<VariableMonitorAttribute>()?.Notes;
  381. if (item.PropertyType?.BaseType?.Name == "Array")
  382. {
  383. if (plcadd?.Length > 0)
  384. {
  385. var arrayRes = item.GetValue(status, null);
  386. if (arrayRes != null && arrayRes is Array arr)
  387. {
  388. for (int i = 0; i < arr.Length; i++)
  389. {
  390. var res = variableMonitors.FirstOrDefault(p => p.VarName == $"{item.Name}_{i + 1}");
  391. if (res == null)
  392. {
  393. string[] plc = plcadd?.Substring(1).Split('.');
  394. string TempPlcAddress = string.Empty;
  395. if (plc?.Length == 2)
  396. {
  397. int add = int.Parse(plc[1]);
  398. int firstAdd = int.Parse(plc[0]);
  399. if (add >= 0 && add < 7)
  400. {
  401. add += i;
  402. }
  403. else if (add >= 7)
  404. {
  405. add = 0;
  406. firstAdd++;
  407. }
  408. plc[0] = firstAdd.ToString();
  409. plc[1] = add.ToString();
  410. TempPlcAddress = $"M{plc[0]}.{plc[1]}";
  411. }
  412. variableMonitors.Add(new VariableMonitor()
  413. {
  414. Id = variableMonitors.Count,
  415. VarName = $"{item.Name}_{i + 1}",
  416. Notes = $"{notes}_{i + 1}",
  417. ModbusTcpAddress = $"{int.Parse(modadd) + i}",
  418. PLCAddress = TempPlcAddress,
  419. });
  420. }
  421. }
  422. }
  423. }
  424. else
  425. {
  426. var arrayRes = item.GetValue(status, null);
  427. if (arrayRes != null && arrayRes is Array arr)
  428. {
  429. for (int i = 0; i < arr.Length; i++)
  430. {
  431. var res = variableMonitors.FirstOrDefault(p => p.VarName == $"{item.Name}_{i + 1}");
  432. if (res == null)
  433. {
  434. variableMonitors.Add(new VariableMonitor()
  435. {
  436. Id = variableMonitors.Count,
  437. VarName = $"{item.Name}_{i + 1}",
  438. Notes = $"{notes}_{i + 1}",
  439. });
  440. }
  441. }
  442. }
  443. }
  444. }
  445. else
  446. {
  447. var res = variableMonitors.FirstOrDefault(p => p.VarName == item.Name);
  448. if (res == null)
  449. {
  450. variableMonitors.Add(new VariableMonitor()
  451. {
  452. Id = variableMonitors.Count,
  453. VarName = item.Name,
  454. Notes = notes,
  455. ModbusTcpAddress = modadd,
  456. PLCAddress = plcadd,
  457. });
  458. }
  459. }
  460. }
  461. }
  462. }
  463. /// <summary>
  464. /// 更新数据
  465. /// </summary>
  466. /// <param name="status"></param>
  467. public void UpdateValue(IStatus status)
  468. {
  469. if (status == null) return;
  470. foreach (var item in status.GetType().GetProperties())
  471. {
  472. if (item.CustomAttributes.Count() > 0)
  473. {
  474. if (item.PropertyType?.BaseType?.Name == "Array")
  475. {
  476. var arrayRes = item.GetValue(status);
  477. if (arrayRes != null && arrayRes is Array arr)
  478. {
  479. for (int i = 0; i < arr.Length; i++)
  480. {
  481. int index = Array.FindIndex(variableMonitors.ToArray(), p => p.VarName == $"{item.Name}_{i + 1}");
  482. if (index >= 0 && index < variableMonitors.Count)
  483. {
  484. variableMonitors.ElementAt(index).CurrentValue = arr.GetValue(i)?.ToString();
  485. }
  486. }
  487. }
  488. }
  489. else
  490. {
  491. int index = Array.FindIndex(variableMonitors.ToArray(), p => p.VarName == item.Name);
  492. if (index >= 0 && index < variableMonitors.Count)
  493. {
  494. variableMonitors.ElementAt(index).CurrentValue = item.GetValue(status)?.ToString();
  495. }
  496. }
  497. }
  498. }
  499. }
  500. public abstract void DoMain();
  501. public abstract void Stop();
  502. /// <summary>
  503. /// 数据读取
  504. /// </summary>
  505. public abstract void ReadData();
  506. /// <summary>
  507. /// 主流程控制
  508. /// </summary>
  509. public abstract void MainTask();
  510. /// <summary>
  511. /// 复位程序
  512. /// </summary>
  513. public abstract void ResetProgram();
  514. /// <summary>
  515. /// 模拟订单
  516. /// </summary>
  517. public abstract void SimOrder();
  518. public object GetError()
  519. {
  520. return new { data = Error };
  521. }
  522. public object GetLog()
  523. {
  524. return new { data = Log };
  525. }
  526. public object GetVariableMonitor()
  527. {
  528. return new { data = variableMonitors };
  529. }
  530. /// <summary>
  531. /// 获取某个对象中的属性值
  532. /// </summary>
  533. /// <param name="info"></param>
  534. /// <param name="field"></param>
  535. /// <returns></returns>
  536. public object GetPropertyValue(object info, string field)
  537. {
  538. if (info == null) return null;
  539. Type t = info.GetType();
  540. IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
  541. return property.First().GetValue(info, null);
  542. }
  543. }
  544. }