C# SerialPort串口通信发送接收,处理接收数据完整

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;

namespace SerialPortCom
{
    public class SerialPortComImplement
    {
        public delegate void RecEventHandler(byte[] queueByte);
        public event RecEventHandler DataReceivedEvent;
        private SerialPort serialPort;
        private List buffer = new List(4096);
        /// 
        /// 初始化
        /// 
        /// 端口名称
        /// 波特率
        /// 数据位
        public SerialPortComImplement(string portName, int baudRate, int dataBits)
        {
            serialPort = new SerialPort(portName, baudRate, Parity.None);
            serialPort.DataBits = dataBits;
            serialPort.StopBits = StopBits.One;
            serialPort.ReadTimeout = 2000;
            serialPort.WriteBufferSize = 1024;
            serialPort.ReadBufferSize = 1024;
            serialPort.RtsEnable = true;
            serialPort.DtrEnable = true;
            serialPort.ReceivedBytesThreshold = 1;
            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceivedEventHandler);
        }
        /// 
        /// 串口数据接收事件
        /// 
        /// 
        /// 
        private void serialPort_DataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] readBuffer = null;
                int n = serialPort.BytesToRead;
                byte[] buf = new byte[n];
                serialPort.Read(buf, 0, n);
                //1.缓存数据           
                buffer.AddRange(buf);
                //2.完整性判断         
                while (buffer.Count >= 7)
                {
                    //至少包含标头(1字节),长度(1字节),校验位(2字节)等等
                    //2.1 查找数据标记头            
                    if (buffer[0] ==  0x00) //传输数据有帧头,用于判断       
                    {
                        int len = buffer[1];
                        if (buffer.Count < len + 2)
                        {
                            //数据未接收完整跳出循环
                            break;
                        }
                        readBuffer = new byte[len + 2];
                        //得到完整的数据,复制到readBuffer中    
                        buffer.CopyTo(0, readBuffer, 0, len + 2);
                        //从缓冲区中清除
                        buffer.RemoveRange(0, len + 2);
                        
                  
                        //触发外部处理接收消息事件
                            
                        }
                    }
                    else //开始标记或版本号不正确时清除           
                    {
                        buffer.RemoveAt(0);
                    }
                }
            }
            catch (Exception ex)
            {
                SerialPortLog.Error(ex, "");
            }
        }
        /// 
        /// 打开端口
        /// 
        public bool Open()
        {

            try
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                    return true;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                SerialPortLog.Error(ex, "");
                return false;
            }

        }
        /// 
        /// 发送字节
        /// 
        /// 要发送的字节
        /// 
        public bool Write(byte[] writeBytes)
        {
            if (Open())
            {
                try
                {
                    serialPort.Write(writeBytes, 0, writeBytes.Length);
                    string mergeStr = "发送:";
                    for (int j = 0; j < writeBytes.Length; j++)
                    {
                        mergeStr = mergeStr + writeBytes[j].ToString("x") + " ";
                    }
                    SerialPortLog.Info(mergeStr);
                    return true;
                }
                catch (Exception ex)
                {
                    SerialPortLog.Error(ex, "");
                    return false;
                }
            }
            return false;
        }
        /// 
        /// 发送字符串
        /// 
        /// 
        /// 
        public bool Write(string writeStrs)
        {
            if (Open())
            {
                try
                {
                    serialPort.Write(writeStrs);
                    Thread.Sleep(100);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }
        /// 
        /// 读取数据
        /// 
        /// 读取的字节数
        /// 
        public byte[] Read(int NumBytes)
        {
            byte[] inbuffer = null;

            if (serialPort.IsOpen && serialPort.BytesToRead > 0)
            {
                if (NumBytes > serialPort.BytesToRead)
                {
                    NumBytes = serialPort.BytesToRead;
                }
                try
                {
                    inbuffer = new byte[NumBytes];
                    int count = serialPort.Read(inbuffer, 0, NumBytes);
                }
                catch (TimeoutException timeoutEx)
                {
                    //超时异常
                    SerialPortLog.Error(timeoutEx, "");
                }
            }
            return inbuffer;
        }
        public byte[] Read()
        {
            return Read(serialPort.BytesToRead);
        }
        public string ReadLine()
        {
            try
            {
                if (serialPort.IsOpen && serialPort.BytesToRead > 0)
                {
                    string s = serialPort.ReadExisting();
                    return serialPort.ReadLine();
                }
                return null;
            }
            catch (TimeoutException timeoutEx)
            {
                SerialPortLog.Error(timeoutEx, "");
                return timeoutEx.Message;
            }
        }
        /// 
        /// 关闭串口
        /// 
        public void Close()
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                SerialPortLog.Error(ex, "");
            }
        }

        public bool IsOpen
        {
            get
            {
                return serialPort.IsOpen;
            }
        }
    }
}

你可能感兴趣的:(C#常用类)