AeRfMatchConnection.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections.Generic;
  2. using System.IO.Ports;
  3. using Aitex.Core.RT.Log;
  4. using MECF.Framework.Common.Communications;
  5. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFMatchs.AE
  6. {
  7. public class AeRfMatchMessage : BinaryMessage
  8. {
  9. public byte Header { get; set; }
  10. public byte CommandNumber { get; set; }
  11. public byte OptionLength { get; set; }
  12. public byte[] Data { get; set; }
  13. public byte CheckSum { get; set; }
  14. public int Address { get; set; }
  15. public int DataLength { get; set; }
  16. public int MessageLength { get; set; }
  17. }
  18. public class AeRfMatchConnection : SerialPortConnectionBase
  19. {
  20. private List<byte> _lstCacheBuffer = new List<byte>();
  21. public AeRfMatchConnection(string portName, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One)
  22. : base(portName, baudRate, dataBits, parity, stopBits, "\r", false)
  23. {
  24. }
  25. public override bool SendMessage(byte[] message)
  26. {
  27. _lstCacheBuffer.Clear();
  28. return base.SendMessage(message);
  29. }
  30. protected override MessageBase ParseResponse(byte[] rawBuffer)
  31. {
  32. _lstCacheBuffer.AddRange(rawBuffer);
  33. AeRfMatchMessage msg = new AeRfMatchMessage();
  34. msg.RawMessage = rawBuffer;
  35. if (_lstCacheBuffer.Count >= 1 && _lstCacheBuffer[0] == 0x06)
  36. {
  37. msg.IsAck = true;
  38. _lstCacheBuffer.RemoveAt(0);
  39. }
  40. if (_lstCacheBuffer.Count < 4)
  41. {
  42. return msg;
  43. }
  44. msg.Header = _lstCacheBuffer[0];
  45. msg.CommandNumber = _lstCacheBuffer[1];
  46. msg.OptionLength = _lstCacheBuffer[2];
  47. msg.Address = _lstCacheBuffer[0] >> 3;
  48. msg.DataLength = (byte)(0x07 & _lstCacheBuffer[0]);
  49. msg.MessageLength = 3 + msg.DataLength ;//3=包头+Cmd+校验
  50. if (msg.DataLength >= 7)
  51. {
  52. msg.DataLength = _lstCacheBuffer[2];
  53. msg.MessageLength = 4 + msg.DataLength ;//4=包头+Cmd+length+校验
  54. }
  55. if (_lstCacheBuffer.Count < msg.MessageLength)
  56. return msg;
  57. msg.Data = _lstCacheBuffer.GetRange(msg.DataLength >= 7 ? 3 : 2, msg.DataLength).ToArray();
  58. byte sum = 0x00;
  59. for (var i = 0; i < msg.MessageLength - 1; i++)
  60. {
  61. sum ^= _lstCacheBuffer[i];
  62. }
  63. if (_lstCacheBuffer[msg.MessageLength - 1] != sum)
  64. {
  65. LOG.Error($"check sum failed, ");
  66. msg.IsFormatError = true;
  67. _lstCacheBuffer.Clear();
  68. return msg;
  69. }
  70. msg.IsResponse = true;
  71. _lstCacheBuffer.RemoveRange(0, msg.MessageLength);
  72. return msg;
  73. }
  74. }
  75. }