OK, so message traffic would be pretty low, and problems with the serial communication are rather unlikely. This is my first attempt (not tested!), it does NOT include communication recovery, that is: if something goes wrong (say a serial byte gets lost), it will continue to fail.
using System;
using System.IO.Ports;
using System.Threading;
namespace ConsoleApp1 {
class PortDataReceived {
private static SerialPort sp;
private const string PORTNAME = "COM3";
private const int MSGLEN = 21;
public static void Main(string\[\] args) {
sp = openPort();
Console.WriteLine("Press any key to terminate...");
Console.ReadKey();
if (sp!=null) sp.Close();
}
private static SerialPort openPort() {
try {
SerialPort port = new SerialPort(PORTNAME);
port.BaudRate = 56000;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.DataBits = 8;
port.Handshake = Handshake.None;
port.RtsEnable = true;
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
port.Open();
output("serial port " + PORTNAME + "opened");
return port;
} catch(Exception exc) {
reportError("Error opening serial port (" + exc.Message + ")");
return null;
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
// we will process one or more messages in a loop
// WARNING: if for some reason the serial data gets out of sync (first byte isn't 0xE0)
// then we will not recover, and the data will not be understood at all!
byte\[\] message = new byte\[MSGLEN\];
while (true) {
int count = sp.BytesToRead;
if (count == 0) return; // no more data, exit the handler
if (count >= MSGLEN) {
// we now read exactly 21 bytes, no more no less, so when several messages could be present
// we only obtain the first one in this iteration of the while loop
int got=sp.Read(message, 0, MSGLEN);
if (got == MSGLEN) {
processMessage(message);
} else {
// this should never happen
reportError("Insufficient data bytes in DataReceivedHandler");
}
} else {
// some bytes are present, but not enough; so wait some more
Thread.Sleep(100);
}
}
}
private static void processMessage(byte\[\] bb) {
// WARNING: this method gets called by DataReceived handler, so it will NOT run on the GUI thread,
// and would need Invoking when used in a Windows Forms project
int count = bb.Le