实现是来并不难,主要是面向接口编程思想:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
//串口接口定义
public interface IComserial
{
int ReadBuf(byte[] buf, int offset, int count);
void WriteBuf(byte[] buf, int offSet, int count);
string ReadLine();
void WriteLine(string str);
string Com_port { get; set; }
int Com_Speed { get; set; }
int Read_Timeout { get; set; }
int Write_Timeout { get; set; }
string NewLine { get; set; }
bool Open();
bool Close();
bool IsOpen();
}
}
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class SerialComEntity : IComserial
{
public string Com_port { get; set; }
public int Com_Speed { get; set; }
public int Read_Timeout { get; set; }
public int Write_Timeout { get; set; }
public string NewLine { get ; set; }
private SerialPort serialPort;
~SerialComEntity()
{ this.Close(); }
public bool Close()
{
if (serialPort != null)
{
serialPort.Close();
serialPort.Dispose();
serialPort = null;
return true;
}
else
{
return false;
}
}
public bool IsOpen()
{
return serialPort != null && serialPort.IsOpen;
}
public bool Open()
{
Close();
this.serialPort = new SerialPort(Com_port, Com_Speed, Parity.None, 8, StopBits.One);
serialPort.ReadTimeout = this.Read_Timeout;
serialPort.WriteTimeout = Write_Timeout;
if (string.IsNullOrEmpty( this.NewLine))
{
serialPort.NewLine = this.NewLine;
}
try
{
serialPort.Open();
}
catch (Exception)
{
Close();
return false;
}
return true;
}
public int ReadBuf(byte[] buf, int offset, int count)
{
if (!this.IsOpen())
{
return -1;
}
return this.serialPort.Read(buf, offset, count);
}
public void WriteBuf(byte[] buf, int offSet, int count)
{
if (!this.IsOpen())
{
return;
}
serialPort.Write(buf, offSet, count);
}
public string ReadLine()
{
if (!Open())
{
return string.Empty;
}
return serialPort.ReadLine();
}
public void WriteLine(string str)
{
if (!Open())
{
return ;
}
serialPort.Write(str);
}
}
}