我要实现程序通过com向设备发送开门与关门的指令。每次发送指令后会返回一条指令用来判断开门是否成功。开门,关门的方法要封装成一个接口,以便其他程序调用,现在我不是很清楚,用serialport这个类,在开门或关门的方法中,我怎样利用DataReceived这个事件读取并处理两个方法的返回结果,谢谢!serialport类参考下面:
public ComPort()
{
}
//用于线程同步,初始状态设为非终止状态,使用手动重置方式
private EventWaitHandle allDone = new EventWaitHandle(false, EventResetMode.AutoReset);
SerialPort _serialPort = new SerialPort();
//声明获取时间委托
public delegate void EventHandlerDataReceived(byte[] param);
//获取数据事件
public EventHandlerDataReceived DataReceived;
//声明获取事件委托
public delegate void EventHandlerStatusChanged(string param);
//获取事件信息
public EventHandlerStatusChanged StatusChanged;
//串口号
public string PortName = "COM1";
//波特率
public int BautRate = 9600;
//效验位
public Parity Parity = System.IO.Ports.Parity.None;
//数据位
public int DataBits = 8;
//停止位
public StopBits StopBits = System.IO.Ports.StopBits.One;
//读写时间超时
public int ReadTimeout = 50;
public int WriteTimeout = 50;
/// <summary>
/// 打开端口
/// </summary>
public void Open()
{
//串口号
_serialPort.PortName = PortName;
//波特率
_serialPort.BaudRate = BautRate;
//效验位
_serialPort.Parity = Parity;
//数据位
_serialPort.DataBits = DataBits;
//停止位置
_serialPort.StopBits = StopBits;
//读写时间超时
_serialPort.ReadTimeout = ReadTimeout;
_serialPort.WriteTimeout = WriteTimeout;
try
{
//开启端口
_serialPort.Open();
//开启数据读取监控
StartReading();
}
catch (IOException)
{
_serialPort.Close();
StatusChanged(PortName + "端口被占用...");
}
//设置端口状态
// StatusChanged("端口:" + PortName + ",波特率:" + BautRate + ",效验位:" + Parity.ToString() + ",数据位置" + DataBits + "," + PortName + "已经打开...");
}
/// <summary>
/// 开启监听线程
/// </summary>
private void StartReading()
{
_serialPort.DataReceived += new SerialDataReceivedEventHandler(ReadData);
}
/// <summary>
/// 关闭端口连接
/// </summary>
public void close()
{
_serialPort.Close();
// StatusChanged("关闭" + PortName + "连接......");
}
/// <summary>
/// 获取端口状态
/// </summary>
/// <returns></returns>
public bool IsOpen()
{
return _serialPort.IsOpen;
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ReadData(Object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(300);
if (_serialPort.IsOpen)
{
//StatusChanged("正在获取数据... ...");
int bytes = _serialPort.BytesToRead;
byte[] buffer = new byte[bytes];
_serialPort.Read(buffer, 0, bytes);
DataReceived(buffer);
buffer = null;
allDone.Set();
//StatusChanged("获取数据成功... ...");
}
}
/// <summary>
/// 写入数据
/// </summary>
public void SendData(byte[] WriteData)
{
if (_serialPort.IsOpen)
{
allDone.WaitOne(500);
_serialPort.Write(WriteData, 0, WriteData.Length);
// StatusChanged("正在发送数据... ...");
}
}
//COM端口接收到数据后触发
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(120);//暂停120毫秒等一条完整的命令进入缓冲区
byte[] c = new byte[50];//用来接收缓冲区收到的数据
try
{
comPort.Read(c, 0, 50);
}
catch { }
string oldOrder = "";
for (int i = 0; i < 50; i++)
{
string re = Convert.ToString(c[i], 16).ToUpper();
oldOrder = oldOrder + re;
}
}
oldOrder就是你收到的数据。。。至于命令内容什么的你自己判断吧!