FfuAAFConnection.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using MECF.Framework.Common.Communications;
  7. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.FFUs.AAF
  8. {
  9. public class FfuAAFMessage : BinaryMessage
  10. {
  11. public byte Preamble { get; set; }
  12. public byte Command { get; set; }
  13. public byte GroupAddress { get; set; }
  14. public byte Data1 { get; set; }
  15. public byte Data2 { get; set; }
  16. }
  17. public class FfuAAFConnection : SerialPortConnectionBase
  18. {
  19. private List<byte> _lstCacheBuffer = new List<byte>();
  20. public FfuAAFConnection(string portName) : base(portName,9600,8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One,"\r",false)
  21. {
  22. }
  23. public override bool SendMessage(byte[] message)
  24. {
  25. _lstCacheBuffer.Clear();
  26. return base.SendMessage(message);
  27. }
  28. protected override MessageBase ParseResponse(byte[] rawMessage)
  29. {
  30. _lstCacheBuffer.AddRange(rawMessage);
  31. byte[] temps = _lstCacheBuffer.ToArray();
  32. FfuAAFMessage msg = new FfuAAFMessage();
  33. msg.IsResponse = false;
  34. msg.IsAck = false;
  35. msg.IsComplete = false;
  36. msg.RawMessage = _lstCacheBuffer.ToArray();
  37. if (temps.Length < 4) return msg;
  38. if (temps.LastOrDefault() != ModRTU_CRC(temps.Take(temps.Length - 1).ToArray()))
  39. return msg;
  40. msg.Preamble = temps[0];
  41. msg.Command = temps[1];
  42. msg.GroupAddress = temps[2];
  43. if (temps.Length > 4) msg.Data1 = temps[3];
  44. if (temps.Length > 5) msg.Data2 = temps[4];
  45. msg.IsResponse = true;
  46. msg.IsAck = true;
  47. msg.IsComplete = true;
  48. return msg;
  49. }
  50. private static byte ModRTU_CRC(byte[] buffer)
  51. {
  52. //ushort crc = 0xFFFF;
  53. // var buf = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, buffer));
  54. var buf = buffer;
  55. var len = buffer.Length;
  56. byte temp = buffer[0];
  57. for (int i = 1; i < buffer.Length; i++)
  58. {
  59. temp = (byte)(temp ^ buffer[i]);
  60. }
  61. return (byte)~temp;
  62. }
  63. }
  64. }