I am trying to get what comes in from the port and compare it with what I currently have

  • Thread starter Thread starter jayderk
  • Start date Start date
J

jayderk

Hello All,

I am trying to get this function to work correctly and can not seem to do
so.

basically this function searches the port.input for a time of
"secondsToSearch" for a message that starts with "message".
you can see that I don't even bother searching until the length of data in
the buffer is greater then what I am searching for.

can you see any problems with this?


private bool searchRxForMessage(string message, int secondsToSearch)
{
Library.CfDebugger.WriteDebugLine("search for:" + message);
DateTime finish = new
DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.
Hour,DateTime.Now.Minute,DateTime.Now.Second + secondsToSearch);
DateTime current = DateTime.Now;
txtTx.Text = "Start loop";
//this.refresh();
while( (((TimeSpan)(finish - current)).TotalSeconds >= 0) )
{
Library.CfDebugger.WriteDebugLine("input buffer:" +
port.InputLen.ToString());
if(port.InputLen >= message.Length)
{
string stringToSearch =
Encoding.ASCII.GetString(port.Input,0,port.InputLen);
Library.CfDebugger.WriteDebugLine(stringToSearch);
if(stringToSearch.StartsWith(message))
return true;
}
current = DateTime.Now;
}
txtTx.Text = " stop loop";
//this.refresh();

Library.CfDebugger.WriteDebugLine("didn't find it");
return false;
}
 
Don't use a polling mechanism rather switch to catching an event of when
data is available and then run your logic

If you insist on your approach, off the top of my head here are some
suggestions

1. Use DateTime.Now.AddSeconds to calculate your finish variable
2. Use String.IndexOf to check for the existence of another string within a
string
3. Although I don't know the specifics of your comms, relying on the text
length seems dodgy; why not append new Input to your stringToSearch until
e.g. your timeout is reached.

Again, I suggest making the code event driven...

Cheers
Daniel
 
Back
Top