0

I have data streaming in from a serial device. I have this as a hex string, where the data packets always begin with F4.

i am using:

while (_serialPort.BytesToRead > 0)
        {
            var chunk = new byte[_serialPort.BytesToRead];
            _serialPort.Read(chunk, 0, chunk.Length);

            _text += BitConverter.ToString(chunk);
        }

And as it is BytesToRead, the chunk variable is always different. How should i be splitting out the packets as they come in?

I am thinking:

If string contains F4, start pushing data into buffer. At next F4, stop, process existing buffer and start to fill again.

Is this a viable approach? What is the best way to approach this?

anti
  • 3,011
  • 7
  • 36
  • 86
  • What do you mean by *"hex string"*? Is this `F4` a byte value of 0xF4 or two ASCII characters "F4" or ??? If the data portion of the message can also contain this start byte/sequence, then solely relying on this one test is prone to misidentifying message frames. At the very least you also need to verify message alignment with somekind of message integrity verification, such as a checksum (or even better CRC32), and/or detection of an ending byte/sequence. See http://stackoverflow.com/questions/16177947/identification-of-packets-in-a-byte-stream/16180135#16180135 for some basic concepts. – sawdust Aug 02 '16 at 05:35

1 Answers1

0

Standard practice is to recycle the buffer

//you should re-use the buffer
var chunk = new byte[8]; //this should be the actual packet size sent by the device    

int bytesRead;
while ((bytesRead = _serialPort.Read(chunk, 0, chunk.Length)) > 0)
{
     _text += BitConverter.ToString(chunk, 0, bytesRead);
}

Now, if your packets are fixed-length then you should be good after you set chunk[] to the correct size. If they are not, you will want to use a StringBuilder to buffer it as text and then use the usual string parsing techniques.

hoodaticus
  • 3,772
  • 1
  • 18
  • 28
  • Hi, thank you for your reply. I think the packet size is 50. How can i ensure that the packet starts at `F4`? – anti Aug 01 '16 at 20:26
  • @anti - if the packets start at F4 and the packet size is guaranteed to be 50, then they might - if you're lucky - ALL start at F4 if you set the chunk size to 50. If not - if it's in fact variable length - then we have to do some text buffering. Let me know if you want that answer as it's a bit more work. Thanks! – hoodaticus Aug 01 '16 at 20:40
  • the device is already streaming when i connect to it, so sadly the start point is completely arbitrary. The last bite is actually a checksum, but i can't find any info on how to use it to check packet size! – anti Aug 01 '16 at 21:05