工作中写的一串口通信类 ( Archived on 2008-6-17 20:30:18 420 Views )
using System;
using System.IO.Ports;
using System.Threading;
namespace TripodDemo
{
/// <summary>
/// 串口操作通用类,抽象类防止类别直接实例化
/// </summary>
public abstract class ComPort : IDisposable
{
/// <summary>
/// 使用变量锁定对象
/// </summary>
private object objComm = new object();
/// <summary>
/// 串口对象
/// </summary>
private SerialPort com;
private bool disposed = false;
#region SerialPort
public ComPort()
{
com = new SerialPort("COM1", 9600);
OpenCom();
}
public ComPort(SerialPort sp)
{
com = sp;
OpenCom();
}
private void OpenCom()
{
try
{
if (!com.IsOpen)
{
com.ReadTimeout = 3000;
com.WriteTimeout = 3000;
com.Open();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region Dispose & Close
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (!disposed && disposing && com != null && com.IsOpen)
{
com.Close();
disposed = true;
}
}
public void Close()
{
Dispose(true);
}
#endregion
#region 发送数据
/// <summary>
/// 发送数据
/// </summary>
/// <param name="bwrite">写数据</param>
/// <param name="returnDataLen">读数据长度</param>
/// <param name="bread">读数据</param>
/// <param name="msel">超时毫秒</param>
/// <returns>是否执行成功</returns>
public bool SendData(byte[] bwrite, int returnDataLen, out byte[] bread, int msel)
{
lock (objComm)
{
bread = new byte[returnDataLen];
long l = DateTime.UtcNow.Ticks + msel * 10000;
com.DiscardInBuffer();
com.DiscardOutBuffer();
com.Write(bwrite, 0, bwrite.Length);
while (com.BytesToRead < returnDataLen && DateTime.UtcNow.Ticks < l)
{
Thread.Sleep(1);
}
//串口无反应
if (com.BytesToRead < returnDataLen)
{
return false;
}
try
{
com.Read(bread, 0, bread.Length);
return true;
}
catch (TimeoutException)
{
return false;
}
}
}
#endregion
}
public class SerialQ01 : ComPort
{
#region 构造函数
public SerialQ01()
: base()
{
//constructor
}
public SerialQ01(SerialPort sp)
: base(sp)
{
//constructor
}
#endregion
#region 读时间
public bool ReadDeviceTime(byte macno, out string time)
{
int retLen = 10;
byte[] bread;
//构建命令
byte b1 = 0xAA;
byte b2 = 0x00;
byte b3 = 0x32;
byte[] bwrite = { b1, b2, b2, macno, macno, b3, b3 };
bool bRet = SendData(bwrite, retLen, out bread, 1000);
#if DEBUG
foreach (byte b in bread)
{
System.Diagnostics.Debug.WriteLine(b.ToString("X2"));
}
#endif
time = string.Empty;
if (bRet)
{
if (bread[0] == 0xCC && bread[1] == 0x30 && bread[2] == 0x30)
{
time = string.Format("20{0}-{1}-{2} {3}:{4}", bread[3].ToString("X2"), bread[4].ToString("X2"), bread[5].ToString("X2"), bread[6].ToString("X2"), bread[7].ToString("X2"));
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
#endregion
}
}