做工業通信有很長時間了,特別是串口(232/485),有VB/VC/C各種版本的串口操作代碼,這些代碼也經過了多年的現場考驗,應該說是比較健壯的代碼,但是目前卻沒有C#相對成熟的串口操作代碼,最近用Moxa的設備開發基於WinCE5.0的串口操作代碼,所以就擴充完善了一下串口操作,特別是SendCommand函數,這是我比較常用的主從通信代碼,不喜歡用事件或線程接數據,在規定的超時時間內直接循環判斷要接收的數據。
下面是具體的代碼:
public class PortData
{
public event PortDataReceivedEventHandle Received;
public event SerialErrorReceivedEventHandler Error;
public SerialPort port;
public bool ReceiveEventFlag = false; //接收事件是否有效 false表示有效
public PortData(string sPortName, int baudrate,Parity parity,SerialInterface.SerialMode mode)
{
port = new SerialPort(sPortName, baudrate, parity, 8, StopBits.One);
port.RtsEnable = true;
port.ReadTimeout = 3000;
port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorEvent);
}
~PortData()
{
Close();
}
public void Open()
{
if (!port.IsOpen)
{
port.Open();
}
}
public void Close()
{
if (port.IsOpen)
{
port.Close();
}
}
//數據發送
public void SendData(byte[] data)
{
if (port.IsOpen)
{
port.Write(data, 0, data.Length);
}
}
public void SendData(byte[] data,int offset,int count)
{
if (port.IsOpen)
{
port.Write(data, offset, count);
}
}
//發送命令
public int SendCommand(byte[] SendData, ref byte[] ReceiveData,int Overtime)
{
if(port.IsOpen)
{
ReceiveEventFlag = true; //關閉接收事件
port.DiscardInBuffer(); //清空接收緩沖區
port.Write(SendData, 0, SendData.Length);
int num=0,ret=0;
while (num++ < Overtime)
{
if (port.BytesToRead >= ReceiveData.Length) break;
System.Threading.Thread.Sleep(1);
}
if (port.BytesToRead >= ReceiveData.Length)
ret = port.Read(ReceiveData, 0, ReceiveData.Length);
ReceiveEventFlag = false; //打開事件
return ret;
}
return -1;
}
public void ErrorEvent(object sender, SerialErrorReceivedEventArgs e)
{
if (Error != null) Error(sender, e);
}
//數據接收
public void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//禁止接收事件時直接退出
if (ReceiveEventFlag) return;
byte[] data = new byte[port.BytesToRead];
port.Read(data, 0, data.Length);
if (Received != null) Received(sender, new PortDataReciveEventArgs(data));
}
public bool IsOpen()
{
return port.IsOpen;
}
}
public delegate void PortDataReceivedEventHandle(object sender, PortDataReciveEventArgs e);
public class PortDataReciveEventArgs : EventArgs
{
public PortDataReciveEventArgs()
{
this.data = null;
}
public PortDataReciveEventArgs(byte[] data)
{
this.data = data;
}
private byte[] data;
public byte[] Data
{
get { return data; }
set { data = value; }
}
}
【附注】1~9 串口的名稱是 "COMx:",>9的以前用\\\\.\\COMx:比較好使,但是在moxa 661設備上卻不行,要用如下格式"$device\\COM" + PortNo.ToString() + "\0",也許這是moxa修改了相應的串口驅動。