问题
I am trying to check some values some AT commands ran on a GSM modem. I am stuck at the point where when trying to check if the output of a command contains some values is true or not.
Using the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Timers;
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();
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
p.Write("AT+CMGF=1"+ "\r" );
buff = p.ReadExisting();
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
do
{
p.Write("AT+CMGL=\"REC UNREAD\" " + "\r");
buff = p.ReadExisting();
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
/*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());
}
}
}
I get this output:
Why is it that sometimes buff is empty and is displayed later ?
回答1:
There are calls to ReadExisting()
that are superfluous.
You should not be reading your serial port output in the main method, let the event handler do the work for you.
Also, you should append what you read in the event handler to the buff
variable so that you can all the data received when you check your buffer.
Try this instead:
public class Program
{
public static void Main(string[] args)
{
ModemReader r = new ModemReader();
r.StartReading();
}
class ModemReader{
string buff="";
public void StartReading()
{
string ok = "OK";
SerialPort p = new SerialPort("COM28");
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
p.Open();
string line = "1";
p.Write("AT" + "\r");
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
p.Write("AT+CMGF=1"+ "\r" );
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
do
{
// Clear the buffer here
buff = "";
p.Write("AT+CMGL=\"REC UNREAD\" " + "\r");
Console.WriteLine("buff: \"{0}\"\nok: \"{1}\"", buff, ok);
if (buff.Contains(ok))
Console.WriteLine("Everything is OK");
else
Console.WriteLine("NOK");
line = Console.ReadLine();
} while (line != "quit");
p.Close();
}
public void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string s = (sender as SerialPort).ReadExisting();
buff += s;
Console.WriteLine(s);
}
}
}
回答2:
You can only consume the port data once. Because you consume it inside your handler, it is no longer present when you try to put it in your buffer.
来源:https://stackoverflow.com/questions/10968024/why-the-buffer-is-empty