日期:2014-05-18 浏览次数:21013 次
public class Sms
{
SerialPort port;
TimeSpan waitTime;
EventWaitHandle eventWait;
public Sms(string portName, int baudRate)
{
this.port = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
this.port.RtsEnable = true;
this.port.ReceivedBytesThreshold = 1;
this.port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
this.waitTime = TimeSpan.FromMinutes(1);
this.eventWait = new EventWaitHandle(false, EventResetMode.AutoReset);
}
public bool IsOpen
{
get
{
return this.port.IsOpen;
}
}
public bool Open()
{
this.port.Open();
return true;
}
public void Close()
{
this.port.Close();
}
public string GetCenterNumber()
{
var response = this.ExecAtCommand(@"AT+CSCA?");
var number = string.Empty;
if (!string.IsNullOrEmpty(response))
{
var reg = new System.Text.RegularExpressions.Regex("\\+86[0-9]{10,13}");
var mt = reg.Match(response);
if (mt.Success)
{
number = mt.Value.Substring(1);
}
}
return number;
}
public string ExecAtCommand(string commandText)
{
if (this.port.IsOpen)
{
this.port.DiscardOutBuffer();
this.port.DiscardInBuffer();
this.port.WriteLine(commandText);
this.eventWait.WaitOne(waitTime);
Thread.Sleep(500);
var response = this.port.ReadExisting();
return response;
}
else
{
return string.Empty;
}
}
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (this.port.BytesToRead > 0)
{
Thread.Sleep(500);
this.eventWait.Set();
}
}
}