Of course, not long after posting I came up with a solution that is working fairly well. I’m still welcoming constructive criticism if anyone has any ideas for further optimization. I need this to work as quickly as possible.
private static string _lastCommand;
public DataReceiver DataProcessor;
private static string _commandBuffer;
private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
var received = _commandBuffer;
// Read all data and buffer to a string.
var bytesReceived = ((SerialPort) sender).BytesToRead;
var bytes = new byte[bytesReceived];
((SerialPort) sender).Read(bytes, 0, bytesReceived);
received += new string(Encoding.UTF8.GetChars(bytes));
// Make sure there is a command prefix.
var prefixNdx = received.IndexOf(COMMAND_PREFIX);
if (prefixNdx < 0) return; // No valid command prefix exists.
// If there is not also a suffix then carry the received data over to the next packet.
var suffixNdx = received.IndexOf(COMMAND_SUFFIX);
if (suffixNdx < 0)
_commandBuffer = received;
var command = "";
for(var ndx = prefixNdx; ndx < received.Length; ndx++)
var c = received[ndx];
if (c == COMMAND_SUFFIX)
if(command != "" && command != _lastCommand) ProcessCommand(command);
command = "";
else if (c != COMMAND_PREFIX) command += c;
_commandBuffer = command;
The data I’m currently sending is in the following format where
[ is the COMMAND_PREFIX
| is the COMMAND_DELIMITER
] is the COMMAND_SUFFIX