I save an output of a command from console.
The output can have more than one line.
How can I search for specific words in all the output ?
Here is my current code:
string buff, ok;
ok = "OK";
SerialPort p = ...
// p initialization...
p.Write("AT+CMGL=\"REC UNREAD\" " + "\r");
System.Threading.Thread.Sleep(1000);
buff = p.ReadExisting();
if (buff.Contains(ok))
// do smth
an example of the output:
+CMGL: 10,"REC READ","0372022244",,"12/02/22,08:08:58+08" 2073692066616374757261207661206669206163686974617461206C612074696D702120446574616C696920696E206D6167617A696E656C6520566F6461666F6E6520736175206C612062616E6361206476732E OK
will this search all the lines from buff for ok ? or just the first line ? i tried it like this and it seems that he can not find “OK” in the output
namespace SerialTest
{
public class Program
{
public static void Main(string[] args)
{
string buff="0";
string ok = "OK";
SerialPort p = new SerialPort("COM28");
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
p.Open();
string line = "1";
p.Write("AT" + "\r");
buff = p.ReadExisting();
p.Write("AT+CMGF=1"+ "\r" );
buff = p.ReadExisting();
do
{
p.Write("AT+CMGL=\"REC UNREAD\" " + "\r");
buff = p.ReadExisting();
if (buff.Contains(ok))
Console.WriteLine("Everything is OK");
else
Console.WriteLine("NOK");
line = Console.ReadLine();
} while (line != "quit");
p.Close();
}
public static void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine((sender as SerialPort).ReadExisting());
}
}
}
p.ReadExisting()does read operations on aSerialPort.The MSDN documentation says:
This means that you might not get all the data you are expecting in one single call to
ReadExistingas that data might not ba available yet. You should probably loop through and read all the data from the serial port before doing theContainscheck.On a side note: using
Thread.Sleepespecially when dealing with serial operations is not a good idea. Instead of sleeping while waiting for the data, use theSerialPort.DataReceivedevent to read available data.Try this to correctly read data from your serial port and get rid of the
SleepAnd then have a timer set to check the output after 1 second.
In the timer event handler you check
data.Contains("OK");