CometRFMatchConnection.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System.Collections.Generic;
  2. using System.IO.Ports;
  3. using System.Linq;
  4. using System.Text;
  5. using Aitex.Core.RT.Log;
  6. using MECF.Framework.Common.Communications;
  7. using MECF.Framework.Common.Utilities;
  8. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFMatchs.Comet
  9. {
  10. public class CometRFMatchMessage : BinaryMessage
  11. {
  12. public string Command { get; set; }
  13. public string ErrorCode { get; set; }
  14. public byte[] Data { get; set; }
  15. }
  16. public class CometRFMatchConnection : SerialPortConnectionBase
  17. {
  18. private static byte _start = 0xAA;
  19. private static byte _address = 0x21;
  20. private List<byte> _msgBuffer = new List<byte>();
  21. public CometRFMatchConnection(string portName, int baudRate = 115200, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One)
  22. : base(portName, baudRate, dataBits, parity, stopBits, "", false)
  23. {
  24. }
  25. public override bool SendMessage(byte[] message)
  26. {
  27. return base.SendMessage(message);
  28. }
  29. protected override MessageBase ParseResponse(byte[] rawMessage)
  30. {
  31. CometRFMatchMessage msg = new CometRFMatchMessage();
  32. if (rawMessage == null || rawMessage.Length < 1)
  33. {
  34. return msg;
  35. }
  36. _msgBuffer.AddRange(rawMessage);
  37. if (_msgBuffer.Count < 4)
  38. {
  39. return msg;
  40. }
  41. byte checkSum = 0;
  42. for (int i = 0; i < _msgBuffer.Count - 1; i++)
  43. {
  44. checkSum += _msgBuffer[i];
  45. }
  46. if (checkSum == _msgBuffer[_msgBuffer.Count - 1])
  47. {
  48. msg.RawMessage = _msgBuffer.ToArray();
  49. _msgBuffer.Clear();
  50. }
  51. else
  52. {
  53. var index = _msgBuffer.FindIndex(4, m => m == _start);
  54. if (index < 0)
  55. {
  56. return msg;
  57. }
  58. msg.RawMessage = _msgBuffer.Take(index).ToArray();
  59. _msgBuffer.RemoveRange(0, msg.RawMessage.Length);
  60. }
  61. if (msg.RawMessage.Length < 4)
  62. {
  63. msg.IsFormatError = true;
  64. LOG.Error($"invalid response");
  65. return msg;
  66. }
  67. if (msg.RawMessage[0] != _start)
  68. {
  69. msg.IsFormatError = true;
  70. LOG.Error($"invalid start byte");
  71. return msg;
  72. }
  73. if (msg.RawMessage[1] != _address)
  74. {
  75. msg.IsFormatError = true;
  76. LOG.Error($"invalid address byte");
  77. return msg;
  78. }
  79. msg.Data = msg.RawMessage.Skip(2).Take(msg.RawMessage.Length - 3).ToArray();
  80. msg.IsResponse = true;
  81. msg.IsAck = true;
  82. msg.IsComplete = true;
  83. return msg;
  84. }
  85. }
  86. }