When I use a AutoResetEvent WaitOne() function and the RS232 module, the data received event handler for the RS232 module never gets called, it is blocked by WaitOne(). I am setting the AutoResetEvent signal inside the RS232 data received handler function. Here is my code:
using System;
using System.Collections;
using System.Text;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GT = Gadgeteer;
using GTI = Gadgeteer.Interfaces;
using GTME = Gadgeteer.Modules.GHIElectronics;
private GTME.RS232 rs232LCD;
private AutoResetEvent LineSentEvent;
private AutoResetEvent TimeoutEvent;
//After sending a command to the LCD, the program must wait since the display
//will not accept any other commands while executing the previous command.
//You will receive a NAK if Command is not in the list, Wrong number of command arguments, Invalid argument
//if all is good, you will receive a ACK packet.
private bool SendData(bool _WaitForACK, TimeSpan ts_time, int ms_time, params byte[] data)
{
bool retval = true;
if (rs232LCD.serialPort.IsOpen)
{
LineSentEvent.Reset();
TimeoutEvent.Reset();
Debug.Print(DateTime.Now.ToString("HH:mm:ss.fff") + " Transmit: " + BytesToHexString(data));
rs232LCD.serialPort.Write( data );
if (_WaitForACK)
{
retval = LineSentEvent.WaitOne(ms_time + 100, false);
if ( !retval )
Debug.Print(DateTime.Now.ToString("HH:mm:ss.fff") + " Transmit Error: Timeout waiting for ACK from LCD" );
}
else
{
timer.Interval = ts_time;
timer.Behavior = GT.Timer.BehaviorType.RunOnce;
timer.Start();
retval = TimeoutEvent.WaitOne(ms_time + 100, false);
if (!retval)
Debug.Print(DateTime.Now.ToString("HH:mm:ss.fff") + " Transmit Error: Timeout waiting for timer tick event");
}
LineSentEvent.Reset();
TimeoutEvent.Reset();
if ( timer.IsRunning ) timer.Stop();
}
else
{
Debug.Print("rs232LCD serial port is not open");
retval = false;
}
return retval;
}
/// <summary>
/// This is the function that will be called when data is available on the serial port.
/// This function will not be called again if the data isn't read in.
/// </summary>
/// <param name="sender">Object that sent called this function</param>
/// <param name="data">serial data received</param>
private void Display_DataReceived(GT.Interfaces.Serial sender, System.IO.Ports.SerialData data)
{
try
{
// Create a buffer that is the length of the data that is available
// the BytesToRead variable tells us how many bytes are waiting in a buffer.
byte[] readData = new byte[rs232LCD.serialPort.BytesToRead];
// Now we read the data into the buffer we just created, starting at the first byte.
rs232LCD.serialPort.Read(readData, 0, readData.Length);
Debug.Print(DateTime.Now.ToString("HH:mm:ss.fff") + " Receive: " + BytesToHexString(readData));
OnDisplayEvent( new DisplayEventArgs( readData ));
LineSentEvent.Set();
}
catch (Exception ex)
{
Debug.Print("KeyPad_DataReceived exception " + ex.Message);
}
}