25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

170 lines
5.2 KiB

  1. using System.Collections.Generic;
  2. using System.IO.Ports;
  3. namespace ThunderboltTimeSync {
  4. public class ThunderboltPacket {
  5. /// <summary>
  6. /// The validity of the packet.
  7. /// If <code>false</code>, the values of <code>ID</code>, <code>Data</code> and <code>RawData</code> must not be used.
  8. /// If <code>true</code>, the packet may still contain invalid values or be of incorrect length.
  9. /// </summary>
  10. public bool IsPacketValid { get; }
  11. /// <summary>
  12. /// The ID of the packet.
  13. /// </summary>
  14. public byte ID { get; }
  15. /// <summary>
  16. /// The data contained within the packet.
  17. /// </summary>
  18. public List<byte> Data { get; }
  19. /// <summary>
  20. /// The raw data of the packet.
  21. /// Contains the initial [DLE] byte, and the terminating [DLE][ETX] bytes. [DLE] values within the data are still stuffed.
  22. /// </summary>
  23. public List<byte> RawData { get; }
  24. public ThunderboltPacket(bool isPacketValid, byte id, List<byte> data, List<byte> rawData) {
  25. IsPacketValid = isPacketValid;
  26. ID = id;
  27. Data = data;
  28. RawData = rawData;
  29. }
  30. }
  31. public class ThunderboltSerialPort {
  32. private static readonly byte CHAR_DLE = 0x10;
  33. private static readonly byte CHAR_ETX = 0x03;
  34. private List<byte> packetBuffer;
  35. private bool inPacket;
  36. private SerialPort serialPort;
  37. /// <summary>
  38. /// A delegate which is called when a full packet is received over the serial port.
  39. /// </summary>
  40. /// <param name="packet">The packet which was received.</param>
  41. public delegate void PacketReceivedEventHandler(ThunderboltPacket packet);
  42. /// <summary>
  43. /// An event which is called when a full packet is received over the serial port.
  44. /// </summary>
  45. public event PacketReceivedEventHandler PacketReceived;
  46. /// <summary>
  47. /// Creates an instance of the ThunderboltSerialPort class, which processes serial data from a Thunderbolt and
  48. /// The serial port passed into the function must not be opened, or have a delegate already attached to the DataReceived event.
  49. /// </summary>
  50. /// <param name="serialPort">The serial port on which to communicate with the Thunderbolt.</param>
  51. public ThunderboltSerialPort(SerialPort serialPort) {
  52. packetBuffer = new List<byte>();
  53. inPacket = false;
  54. this.serialPort = serialPort;
  55. serialPort.DataReceived += DataReceived;
  56. }
  57. /// <summary>
  58. /// Begins processing serial data.
  59. /// </summary>
  60. public void Open() {
  61. serialPort.Open();
  62. }
  63. /// <summary>
  64. /// Converts a stuffed byte list (one where all 0x10 bytes are replaced with 0x10 0x10) into an unstuffed byte list.
  65. /// </summary>
  66. /// <param name="data">A reference to the list containing the data to be unstuffed.</param>
  67. /// <returns>True if the unstuffing was successful, false otherwise.</returns>
  68. private bool Unstuff(ref List<byte> data) {
  69. List<byte> newData = new List<byte>();
  70. bool inStuffedDLE = false;
  71. foreach (byte b in data) {
  72. if (b == CHAR_DLE) {
  73. if (!inStuffedDLE) {
  74. newData.Add(b);
  75. inStuffedDLE = true;
  76. } else {
  77. // If we see a DLE after we've already seen one (inStuffedDLE == true), we don't need to add the byte to the list because we already did when the first byte was encountered
  78. // Just set the flag to false so that if this stuffed DLE is immediately followed by another, it will be correctly parsed
  79. inStuffedDLE = false;
  80. }
  81. } else {
  82. if (inStuffedDLE) {
  83. return false;
  84. }
  85. newData.Add(b);
  86. }
  87. }
  88. data = newData;
  89. return true;
  90. }
  91. private void ProcessPacket() {
  92. byte id = packetBuffer[1];
  93. // Grab only the data - not the first [DLE]<id> or the last [DLE][ETX]
  94. List<byte> data = packetBuffer.GetRange(2, packetBuffer.Count - 4);
  95. bool isPacketValid = Unstuff(ref data);
  96. ThunderboltPacket packet;
  97. if (isPacketValid) {
  98. packet = new ThunderboltPacket(isPacketValid, id, data, packetBuffer);
  99. } else {
  100. packet = new ThunderboltPacket(isPacketValid, 0, new List<byte>(), new List<byte>());
  101. }
  102. PacketReceived?.Invoke(packet);
  103. }
  104. private void DataReceived(object sender, SerialDataReceivedEventArgs e) {
  105. int possibleCurrentByte;
  106. while ((possibleCurrentByte = serialPort.ReadByte()) != -1) {
  107. // Once we're sure the byte that was read wasn't -1 (which signifies the end of the read), we're safe to cast to a byte
  108. byte currentByte = (byte) possibleCurrentByte;
  109. if (inPacket) {
  110. packetBuffer.Add(currentByte);
  111. // Check buffer length to ensure we've reached a plausible end of packet.
  112. // 5 bytes is [DLE]<id><1 byte of data>[DLE][ETX]
  113. if (currentByte == CHAR_ETX && packetBuffer.Count >= 5) {
  114. int numberOfPrecedingDLEs = 0;
  115. // Count number of DLEs, excluding the first two bytes (initial DLE and id)
  116. for (int i = 2; i < packetBuffer.Count; ++i) {
  117. if (packetBuffer[i] == CHAR_DLE) {
  118. ++numberOfPrecedingDLEs;
  119. }
  120. }
  121. // Odd number of DLEs means the ETX does in fact signify the end of the packet
  122. if (numberOfPrecedingDLEs % 2 == 1) {
  123. ProcessPacket();
  124. packetBuffer.Clear();
  125. inPacket = false;
  126. }
  127. }
  128. } else {
  129. // A DLE received when not currently in a packet signifies the beginning of a packet
  130. if (currentByte == CHAR_DLE) {
  131. packetBuffer.Add(currentByte);
  132. inPacket = true;
  133. }
  134. }
  135. }
  136. }
  137. }
  138. }