IoHeartbeat.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Xml;
  3. using Aitex.Core.RT.Device;
  4. using Aitex.Core.RT.Event;
  5. using Aitex.Core.RT.IOCore;
  6. using Aitex.Core.Util;
  7. namespace Aitex.Core.RT.Device.Unit
  8. {
  9. /// <summary>
  10. /// 心跳包机制
  11. ///
  12. /// 功能:
  13. /// 1.C#送出给PLC,如果PLC检测到C#心跳信号停止,则判定C#程序运行异常,从而触发安全逻辑动作。
  14. /// 2.C#检测PLC返回的心跳包信号,如果检测到PLC心跳信号停止,则判定PLC程序运行异常,从而进行报警处理。
  15. /// </summary>
  16. public class IoHeartbeat : BaseDevice, IDevice
  17. {
  18. private readonly int PLC_Heart_Beat_Timeout_ms = 1000 * 120;
  19. private readonly AIAccessor _ai;
  20. private readonly AOAccessor _ao;
  21. private readonly DeviceTimer _updateTimer = new DeviceTimer(); //更新 AO信号 给PLC
  22. private readonly int MAX = 0x7FFF;
  23. private float _prevAiValue;
  24. private readonly DeviceTimer _connectTimer = new DeviceTimer();
  25. private readonly R_TRIG _trigConnectionLost = new R_TRIG();
  26. // --------------------------Constructor-----------------------
  27. //
  28. public IoHeartbeat(string module, XmlElement node, string ioModule = "")
  29. {
  30. base.Module = module;
  31. base.Name = node.GetAttribute("id");
  32. base.Display = node.GetAttribute("display");
  33. base.DeviceID = node.GetAttribute("schematicId");
  34. _ai = ParseAiNode("ai", node, ioModule);
  35. _ao = ParseAoNode("ao", node, ioModule);
  36. }
  37. public bool Initialize()
  38. {
  39. _updateTimer.Start(500);
  40. _connectTimer.Start(PLC_Heart_Beat_Timeout_ms);
  41. return true;
  42. }
  43. public void Monitor()
  44. {
  45. if (Math.Abs(_prevAiValue - _GetRealFloat(_ai)) > 0.01)
  46. {
  47. _connectTimer.Start(PLC_Heart_Beat_Timeout_ms);
  48. }
  49. _trigConnectionLost.CLK = _connectTimer.IsTimeout();
  50. if (_trigConnectionLost.Q)
  51. {
  52. EV.PostMessage(Module, EventEnum.PlcHeartBeatFail, Module, Display);
  53. }
  54. _prevAiValue = _GetRealFloat(_ai);
  55. //如果计时到达,则翻转心跳信号
  56. if (_updateTimer.IsTimeout())
  57. {
  58. float beat_val = _GetRealFloat(_ao);
  59. beat_val++;
  60. if (beat_val >= MAX)
  61. {
  62. beat_val = 0;
  63. }
  64. _SetRealFloat(_ao, beat_val);
  65. _updateTimer.Start(2000); //500 ms
  66. }
  67. }
  68. public void Terminate() { }
  69. public void Reset()
  70. {
  71. _connectTimer.Start(PLC_Heart_Beat_Timeout_ms);
  72. _trigConnectionLost.RST = true;
  73. }
  74. }
  75. }