using System;
|
using System.Diagnostics;
|
using System.IO.Ports;
|
|
namespace Bro.Common.Link
|
{
|
/// <summary>
|
/// 串口连接
|
/// </summary>
|
public class SerialLink : LinkBase
|
{
|
// 默认串口号
|
public const int DFT_PORT = 1;
|
// 默认波特率
|
public const int DFT_BAUD_RATE = 9600;
|
|
// 串口号
|
public int Port { get;set;}
|
// 波特率
|
public int BaudRate { get;set;}
|
// 串口连接
|
private SerialPort SerialPort = new SerialPort();
|
|
public SerialLink()
|
{
|
IsConn = false;
|
|
Port = DFT_PORT;
|
BaudRate = DFT_BAUD_RATE;
|
}
|
|
/// <summary>
|
/// 打开串口连接
|
/// </summary>
|
/// <returns></returns>
|
public override bool Open()
|
{
|
if ( SerialPort.IsOpen )
|
{
|
return true;
|
}
|
|
try
|
{
|
SerialPort.PortName = "COM" + this.Port;
|
SerialPort.BaudRate = this.BaudRate;
|
SerialPort.WriteBufferSize = this.SendBuffLen;
|
SerialPort.ReadBufferSize = this.RecvBuffLen;
|
|
SerialPort.Open();
|
|
base.IsConn = true;
|
|
return true;
|
}
|
catch(Exception ex)
|
{
|
Trace.TraceError("SerialLink:{0} Open fail, ex:{1}-{2}", this.Desp, ex.Message, ex.StackTrace);
|
}
|
|
return false;
|
}
|
|
/// <summary>
|
/// 关闭串口连接
|
/// </summary>
|
public override void Close()
|
{
|
try
|
{
|
if ( !SerialPort.IsOpen )
|
{
|
return;
|
}
|
|
SerialPort.Close();
|
}
|
catch(Exception ex)
|
{
|
Trace.TraceError("SerialLink:{0} Close fail, ex:{1}-{2}", this.Desp, ex.Message, ex.StackTrace);
|
}
|
|
}
|
|
/// <summary>
|
/// 销毁
|
/// </summary>
|
public override void Fnit()
|
{
|
Close();
|
}
|
|
/// <summary>
|
/// 接收数据
|
/// </summary>
|
/// <param name="rcvBuf"></param>
|
/// <param name="bufLen"></param>
|
/// <returns></returns>
|
public override int Recv(byte[] rcvBuf, int offset)
|
{
|
int rcvLen = -1;
|
|
if ( null == rcvBuf )
|
{
|
return -1;
|
}
|
|
try
|
{
|
var len = rcvBuf.Length - offset;
|
if ( len <= 0 )
|
{
|
return -1;
|
}
|
|
rcvLen = SerialPort.Read(rcvBuf, offset, len);
|
}
|
catch(Exception ex)
|
{
|
Trace.TraceError("SerialLink:{0} Recv fail, ex:{1}-{2}", this.Desp, ex.Message, ex.StackTrace);
|
}
|
|
return rcvLen;
|
}
|
|
/// <summary>
|
/// 发送数据
|
/// </summary>
|
/// <param name="sndBuf"></param>
|
/// <param name="offset"></param>
|
/// <returns></returns>
|
public override bool Send(byte[] sndBuf, int offset, int len)
|
{
|
if ( null == sndBuf )
|
{
|
return false;
|
}
|
|
try
|
{
|
SerialPort.Write(sndBuf, offset, len);
|
|
return true;
|
}
|
catch(Exception ex)
|
{
|
Trace.TraceError("SerialLink:{0} Send fail, ex:{1}-{2}", this.Desp, ex.Message, ex.StackTrace);
|
}
|
|
return false;
|
}
|
|
}
|
}
|