Note:
Answered this on a repost of this question but going to add it here as well because the repost might get deleted. Added also some more information.
I still don't think that there is a need for a ring buffer here.
You already have a buffer:
rxBuffer
. To make that a ring buffer all you have to do is handling the write access using
rxOffset
accordingly:
int bytesToRead = min(bytesCount, rxBuffer.Length - rxOffset);
port.Read(rxBuffer, rxOffset, bytesToRead);
rxOffset += bytesToRead;
if (rxOffset >= rxBuffer.Length)
{
bytesToRead = bytesCount - bytesToRead;
port.Read(rxBuffer, 0, bytesToRead);
rxOffset = bytesToRead;
}
Now you have a ring buffer. Depending on what to do with that you might implement a reader having another class level variable defining the current read position (and checking that
rxOffset
will not overrun that read position).
But implementing the above you might recognise that it does not solve your problem. Your problem is actually not how to implement a ring buffer but to define how the received data has to be handled (processed). That is a task which must be done before writing any line of code. Once you have defined that, you can think about possible implementations.
Assuming that you have a start sequence and a length field do this with each receiving:
- Locate the start seqence if not detected so far
- If start detected and enough following bytes has been received (length field present), get that
- If length present, receive until all package bytes has been received
- If a complete package data has been received, process the data
Note also that the above defines "states" as mentioned in an answer to your previous question.
If you think now about a possible implementation you might recognise that there is no need for a circular buffer. Using a "normal" buffer two times the size of the max. package length would be sufficient. All you need are
class member variables (in bold because that is important here) for the current receive position (
rxOffset
), the start sequence position, the length, and optionally the state. Once a package has been received and processed, reset all those variable.