I need to send commands to a serial port to communicate with a Enfora modem. For every command, I will get a reply but the length of the reply string may vary. I need to know how write and then wait for the reply until it finishes...
So i thought of making a thread that reads from the serial port and the program only writes...
The thread function
private void thread_Handler()
{
while(true)
this.read();
}
private void read()
{
if (this.rtbMessages.InvokeRequired)
{
try
{
SetTextCallback d = new SetTextCallback(read);
this.Invoke(d);
}
catch{}
}
else
{
readBuffer = serialPort.ReadExisting();
rtbMessages.AppendText(readBuffer);
}
}
So this thread is always trying to read from the com PORT and I send the messages this way
writeBuffer = "COMMAND 1";
serialPort.Write(writeBuffer);
writeBuffer = "COMMAND 2";
serialPort.Write(writeBuffer);
However I don't get the reply from the second command I send with Write()... I tried removing the thread and using ReadExisting() after every Write() but that also didn't work.
The only way I could get it to work was to add a
System.Threading.Thread.Sleep(1000);
after every call to Write, then I get all the replies from every Write() command... But I don't want to use this, I want to know of another way to effectively write and get every reply from every command I send regardless of the length of the reply string and how long it takes for me to receive the reply message.
Sometimes I will keep getting messages forever until I send another command to stop generating messages.
Thank you!