Nishikant Tayade

Nishikant Tayade

  • NA
  • 22
  • 8.4k

Serial port data into RIng Buffer

Jun 8 2018 12:48 AM
I am developing a desktop application for serial port communication.The hardware connected to serial port sends the data in packet.
 
But the numbers of bytes in that packet is unknown,hence use of ring buffer.
 
there is no default implementation of circular/Ring Buffer in C#,that's why i am using one provided on GitHub
 
https://github.com/xorxornop/RingBuffer/blob/master/PartiallyConcurrent/RingBuffer.cs
 
I want to save data into Ring Buffer as received and then parse it(like checking for header bytes,for device id,for status byte etc) and if it's not there then discard it.
 
I have tried various implementation but was unable to have a correct implementation.
 
Below is the code :
  1. public class DataReceiveHandle  
  2. {  
  3. public static int MAX_PACKET_LENGTH = ChannelDataCount.count;  
  4. public static bool newData = false;  
  5. public static int rxOffset = 0;  
  6. public static int rxWrite = 0;  
  7. public static int rxRead = 0;  
  8. public static byte[] rxBuffer = new byte[MAX_PACKET_LENGTH];  
  9. public static byte[] rxPackage = new byte[MAX_PACKET_LENGTH];  
  10. public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)  
  11. {  
  12. if (e.EventType != SerialData.Chars) return;  
  13. SerialPort port = (SerialPort)sender;  
  14. int bytesCount = port.BytesToRead;  
  15. port.Read(rxBuffer, rxOffset, bytesCount);  
  16. SequentialRingBuffer rBuffer = new SequentialRingBuffer(4096, rxBuffer, true);  
  17. rxWrite=rBuffer.CurrentLength;  
  18. // rxOffset = rxOffset + bytesCount;  
  19. byte[] tempArray = new byte[256];  
  20. tempArray=rBuffer.ToArray();  
  21. foreach (byte item in tempArray)  
  22. {  
  23. Console.WriteLine(item);  
  24. }  
  25. }  
Can someone please provide an pseudo implementation of what should i do?