[英]Why the buffer is empty?
我正在嘗試檢查一些在GSM調制解調器上運行的AT命令的值。 我陷入了試圖檢查命令輸出是否包含某些值的情況。
使用以下代碼:
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());
}
}
}
我得到以下輸出:
為什么有時buff為空並稍后顯示?
有多余的對ReadExisting()
調用。 您不應該在main方法中讀取串行端口輸出,讓事件處理程序為您完成工作。 同樣,您應該將在事件處理程序中讀取的內容追加到buff
變量,以便檢查緩沖區時可以接收到的所有數據。
嘗試以下方法:
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);
}
}
}
您只能使用一次端口數據。 因為您在處理程序中使用了它,所以當您嘗試將其放入緩沖區時,它不再存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.