I have a problem using serial ports. I have a Gadgeteer project on a Raptor board with three serial ports. For each serial port, I started a sender thread that sends data to a device every 250 milliseconds in a endless loop, and waits for a reply message from the device to be placed in a byte Queue. I started a second receiver thread that polls the serial port for incoming data and place the data bytes received on the same byte Queue. I use a lock for synchronization of the Queue access by the two threads.
The problem is that after working fine for about four hours, all three serial ports stop receiving data, and do not recover until my code re-boots the board.
I put a RS232 serial line analyzer device between the Raptor board and the device to monitor the data flow. I see that when the failure occurs, the Raptor board is transmitting the message, and the device is sending a reply, but my code never gets the data, that is, Port.Read function never returns with new data.
The core of the send function thread is this:
lock (RxDataQueue.SyncRoot)
{
//thread-safe initialize the Queue of data received from the PLC reader
RxDataQueue.Clear();
RxDataEvent.Reset();
}
RS232PLC.Port.Write(sendData);
RS232PLC.Port.Flush();
rv = RxDataEvent.WaitOne(SmartTruckData.SerialPortTimeout, false);
The core of the receive function thread is this:
/// <summary>
/// Received data polling thread for PLC serial port
/// </summary>
void RS232DataReader()
{
try
{
while (true)
{
//wait for RS232 data
if ((RS232Count = RS232PLC.Port.Read(RS232Data, 0, MaxRxDataQueueSize)) > 0)
{
//Put bytes received into a Queue, prevent the Queue size from expanding forever
lock (RxDataQueue.SyncRoot)
{
if (RxDataQueue.Count < MaxRxDataQueueSize)
{
for (int i = 0; i < RS232Count; i++)
{
if (RxDataQueue.Count < MaxRxDataQueueSize)
{
RxDataQueue.Enqueue(RS232Data[i]);
}
}
}
RxDataEvent.Set();
}
}
}
}
catch (Exception ex1)
{
KioskUtilities.LogException(code + " RS232DataReader() exception - ", ex1);
}
}