Given that nothing in your program logic overlaps and you have a very synchronous process, your simple ladder / state machine approach should work fine. You just need to control how and when you progress through the states.
Here’s an approach that might work to handle the serial data - note it’s untested.
int myserialtimeout = 2000; //chosen to allow you time to
com1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
com1.ReadTimeout = myserialtimeout;
public static string ReadSerialData(SerialPort port, int maxBufSize = 300)
if (maxBufSize <= 0) throw new ArgumentOutOfRangeException("maxBufSize");
byte buf = new byte[maxBufSize];
int curPos = 0;
while (curPos < maxBufSize) //simply loop until you hit the timeout on any read.
int read = port.Read(buf, curPos, 1);
if (read == 0) break; // at this point, the timeout has occurred and you have no new data so step out of the while loop
curPos += read;
// think about if you need to clear the remaining port data using port.Flush();
// curPos will be zero if first read is zero.
if (curPos == 0) return null;
if (curPos == maxBufSize)
throw new InvalidOperationException("Line size > maxBufSize.");
// here you can check validity of the data sequence - this is one of my examples - but you may just pass this string back and parse it out later
if (buf[curPos] != 13)
return null; // if no delim found, assume comms failure. drop the current data and move on
//pass a string back
char ca = Encoding.UTF8.GetChars(buf);
return new string(ca);
From your main app you can simply use:
If response == null, then your data didn’t arrive and you should handle that. If it’s non-null then you need to parse it and validate that it is as expected, and then hand back to the ethernet response.
My suggestion would be to make sure you test each aspect of your app in independent modules - test that you can do ethernet incoming request handling and outgoing response; test that you can do outgoing serial requests and incoming serial response correctly - and only then try to link the two. You can “fake up” the data between the modules if needed, for instance you can simply change the “response” string instead of actually reading the value from the serial port and see how the ethernet handling works.
Hope that is a helpful suggestion.