using System; using System.Diagnostics; using System.IO.Ports; namespace Bro.Common.Link { /// /// 串口连接 /// 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; } /// /// 打开串口连接 /// /// 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; } /// /// 关闭串口连接 /// 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); } } /// /// 销毁 /// public override void Fnit() { Close(); } /// /// 接收数据 /// /// /// /// 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; } /// /// 发送数据 /// /// /// /// 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; } } }