串口开展操作的类,主要包括写和读操作,类可设定串口主要参数、设定接收函数公式、开启串口資源、关掉串口資源,操作进行后,一定要关掉串口、接收串口数据信息事件、接收数据出差错事件、获取现阶段所有串口、把字节数型转化成十六进制字符串数组等作用。这一串口类已经过去了调节,可以应用:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Globalization;
namespace SerialClass
{
public class SerialClass
{
SerialPort _serialPort = null;
//界定授权委托
public delegate void SerialPortDataReceiveEventArgs(object sender, SerialDataReceivedEventArgs e, byte[] bits);
//界定接收数据信息事件
public event SerialPortDataReceiveEventArgs DataReceived;
//界定接收不正确事件
//public event SerialErrorReceivedEventHandler Error;
//接收事件是不是合理 false表明合理
public bool ReceiveEventFlag = false;
#region 获取串口名
private string protName;
public string PortName
{
get { return _serialPort.PortName; }
set
{
_serialPort.PortName = value;
protName = value;
}
}
#endregion
#region 获取视频码率
private int baudRate;
public int BaudRate
{
get { return _serialPort.BaudRate; }
set
{
_serialPort.BaudRate = value;
baudRate = value;
}
}
#endregion
#region 默认设置构造方法
/// <summary>
/// 默认设置构造方法,操作COM1,速率为9600,沒有奇偶校验,8位字节数,终止位是1 “COM1”, 9600, Parity.None, 8, StopBits.One
/// </summary>
public SerialClass()
{
_serialPort = new SerialPort();
}
#endregion
#region 构造方法
/// <summary>
/// 构造函数,
/// </summary>
/// <param name=”comPortName”></param>
public SerialClass(string comPortName)
{
_serialPort = new SerialPort(comPortName);
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.Even;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.RtsEnable = true;
_serialPort.ReadTimeout = 2000;
setSerialPort();
}
#endregion
#region 构造方法,可以自定串口的复位主要参数
/// <summary>
/// 构造方法,可以自定串口的复位主要参数
/// </summary>
/// <param name=”comPortName”>必须操作的COM口名字</param>
/// <param name=”baudRate”>COM的速率</param>
/// <param name=”parity”>奇偶校验位</param>
/// <param name=”dataBits”>数据信息长短</param>
/// <param name=”stopBits”>终止位</param>
public SerialClass(string comPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
_serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);
_serialPort.RtsEnable = true; //全自动要求
_serialPort.ReadTimeout = 3000;//请求超时
setSerialPort();
}
#endregion
#region 析构函数
/// <summary>
/// 析构函数,关掉串口
/// </summary>
~SerialClass()
{
if (_serialPort.IsOpen)
_serialPort.Close();
}
#endregion
#region 设定串口主要参数
/// <summary>
/// 设定串口主要参数
/// </summary>
/// <param name=”comPortName”>必须操作的COM口名字</param>
/// <param name=”baudRate”>COM的速率</param>
/// <param name=”dataBits”>数据信息长短</param>
/// <param name=”stopBits”>终止位</param>
public void setSerialPort(string comPortName, int baudRate, int dataBits, int stopBits )
{
if (_serialPort.IsOpen)
_serialPort.Close();
_serialPort.PortName = comPortName;
_serialPort.BaudRate = baudRate;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = dataBits;
_serialPort.StopBits = (StopBits)stopBits;
_serialPort.Handshake = Handshake.None;
_serialPort.RtsEnable = false;
_serialPort.ReadTimeout = 3000;
_serialPort.NewLine = “/r/n”;
setSerialPort();
}
#endregion
#region 设定接收函数公式
/// <summary>
/// 设定串口資源,还需轻载好几个设定串口的函数公式
/// </summary>
void setSerialPort()
{
if (_serialPort != null)
{
//设定开启DataReceived事件的字节为1
_serialPort.ReceivedBytesThreshold = 1;
//接收到一个字节时,也会开启DataReceived事件
_serialPort.DataReceived = new SerialDataReceivedEventHandler(_serialPort_DataReceived);
//接收数据信息出差错,开启事件
_serialPort.ErrorReceived = new SerialErrorReceivedEventHandler(_serialPort_ErrorReceived);
//打开串口
//openPort();
}
}
#endregion
#region 开启串口資源
/// <summary>
/// 开启串口資源
/// <returns>回到bool类型</returns>
/// </summary>
public bool openPort()
{
bool ok = false;
//假如串口是打开的,先关闭
if (_serialPort.IsOpen)
_serialPort.Close();
try
{
//打开串口
_serialPort.Open();
ok = true;
}
catch (Exception Ex)
{
throw Ex;
}
return ok;
}
#endregion
#region 关闭串口
/// <summary>
/// 关闭串口資源,实际操作结束后,一定要关闭串口
/// </summary>
public void closePort()
{
//假如串口处在打开情况,则关闭
if (_serialPort.IsOpen)
_serialPort.Close();
}
#endregion
#region 接受串口数据信息事情
/// <summary>
/// 接受串口数据信息事情
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//严禁接受事情时立即撤出
if (ReceiveEventFlag)
{
return;
}
try
{
System.Threading.Thread.Sleep(20);
byte[] _data = new byte[_serialPort.BytesToRead];
_serialPort.Read(_data, 0, _data.Length);
if (_data.Length == 0) { return; }
if (DataReceived != null)
{
DataReceived(sender, e, _data);
}
//_serialPort.DiscardInBuffer(); //清除接收缓冲区
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 获取数据出差错事情
/// <summary>
/// 获取数据出差错事情
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
void _serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
}
#endregion
#region 传送数据string种类
public void SendData(string data)
{
//传送数据
//严禁接受事情时立即撤出
if (ReceiveEventFlag)
{
return;
}
if (_serialPort.IsOpen)
{
_serialPort.Write(data);
}
}
#endregion
#region 传送数据byte种类
/// <summary>
/// 数据信息推送
/// </summary>
/// <param name=”data”>要传送的数据信息字节数</param>
public void SendData(byte[] data, int offset, int count)
{
//严禁接受事情时立即撤出
if (ReceiveEventFlag)
{
return;
}
try
{
if (_serialPort.IsOpen)
{
//_serialPort.DiscardInBuffer();//清除接收缓冲区
_serialPort.Write(data, offset, count);
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 推送指令
/// <summary>
/// 推送指令
/// </summary>
/// <param name=”SendData”>传送数据</param>
/// <param name=”ReceiveData”>获取数据</param>
/// <param name=”Overtime”>请求超时時间</param>
/// <returns></returns>
public int SendCommand(byte[] SendData, ref byte[] ReceiveData, int Overtime)
{
if (_serialPort.IsOpen)
{
try
{
ReceiveEventFlag = true; //关闭接受事情
_serialPort.DiscardInBuffer(); //清除接收缓冲区
_serialPort.Write(SendData, 0, SendData.Length);
int num = 0, ret = 0;
System.Threading.Thread.Sleep(10);
ReceiveEventFlag = false; //打开事情
while (num < Overtime)
{
if (_serialPort.BytesToRead >= ReceiveData.Length)
break;
System.Threading.Thread.Sleep(10);
}
if (_serialPort.BytesToRead >= ReceiveData.Length)
{
ret = _serialPort.Read(ReceiveData, 0, ReceiveData.Length);
}
else
{
ret = _serialPort.Read(ReceiveData, 0, _serialPort.BytesToRead);
}
ReceiveEventFlag = false; //打开事件
return ret;
}
catch (Exception ex)
{
ReceiveEventFlag = false;
throw ex;
}
}
return -1;
}
#endregion
#region 获得串口
/// <summary>
/// 获取全部已连接短信猫机器设备的串口
/// </summary>
/// <returns></returns>
public string[] serialsIsConnected()
{
List<string> lists = new List<string>();
string[] seriallist = getSerials();
foreach (string s in seriallist)
{
}
return lists.ToArray();
}
#endregion
#region 获得现阶段所有串口資源
/// <summary>
/// 得到现阶段电脑的全部串口資源
/// </summary>
/// <returns></returns>
public string[] getSerials()
{
return SerialPort.GetPortNames();
}
#endregion
#region 字节数型变换16
/// <summary>
/// 把字节数型转化成十六进制字符串数组
/// </summary>
/// <param name=”InBytes”></param>
/// <returns></returns>
public static string ByteToString(byte[] InBytes)
{
string StringOut = “”;
foreach (byte InByte in InBytes)
{
StringOut = StringOut String.Format(“{0:X2} “, InByte);
}
return StringOut;
}
#endregion
#region 十六进制字符串转字节型
/// <summary>
/// 把十六进制字符串转化成字节型(方式1)
/// </summary>
/// <param name=”InString”></param>
/// <returns></returns>
public static byte[] StringToByte(string InString)
{
string[] ByteStrings;
ByteStrings = InString.Split(” “.ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length];
for (int i = 0; i <= ByteStrings.Length-1 ; i )
{
//ByteOut[i] = System.Text.Encoding.ASCII.GetBytes(ByteStrings[i]);
ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
//ByteOut[i] =Convert.ToByte(“0x” ByteStrings[i]);
}
return ByteOut;
}
#endregion
#region 十六进制字符串转字节型
/// <summary>
/// 字符串转16进制字节二维数组(方式2)
/// </summary>
/// <param name=”hexString”></param>
/// <returns></returns>
public static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(” “, “”);
if ((hexString.Length % 2) != 0)
hexString = ” “;
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i )
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
#endregion
#region 字节型转十六进制字符串
/// <summary>
/// 字节二维数组转16进制字符串
/// </summary>
/// <param name=”bytes”></param>
/// <returns></returns>
public static string byteToHexStr(byte[] bytes)
{
string returnStr = “”;
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i )
{
returnStr = bytes[i].ToString(“X2”);
}
}
return returnStr;
}
#endregion
}
}
======================================================================================
启用方式:
static SerialClass sc = new SerialClass();
static void Main(string[] Args)
{
sc.DataReceived = new SerialClass.SerialPortDataReceiveEventArgs(sc_DataReceived);
sc.writeData(“at”);
Console.ReadLine();
sc.closePort();
}
static void sc_DataReceived(object sender, SerialDataReceivedEventArgs e, byte[] bits)
{
Console.WriteLine(Encoding.Default.GetString(bits));
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。