c# 串口SerialPort

2021-03-29 05:29

阅读:544

标签:gif   recv   new   desc   16进制   reg   错误   存储   int start   

创建SerialPortFun类

技术分享图片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using LogSpace;

namespace SerialPortSpace
{
    public class SerialPortFun
    {
        /// 
        /// 串口及串口缓存数据
        /// 
        public static List LstComPort = new List();

        /// 
        /// 是否在进行串口结束操作
        /// 
        public static bool PortIsCloseing = false;

        /// 
        /// 初始化串口,并返回当前串口的结构
        /// 
        /// 
        /// 
        /// 
        /// 
        public static ComPort InitSerialPort(SerialPort Port, string PortNo, int BaudRate, BagStruct CurBagStruct, string StartStr, string EndStr, string PortNameDesc, string PortRemark)
        {
            Port.PortName = PortNo;
            Port.BaudRate = BaudRate;
            Port.DataBits = 8;
            Port.Parity = Parity.None;
            Port.StopBits = StopBits.One;
            Port.NewLine = "\r\n";
            Port.WriteTimeout = 5000;
            Port.ReadTimeout = 5000;
            Port.Handshake = Handshake.None;
            Port.ReceivedBytesThreshold = 1;
            Port.RtsEnable = true;
            Port.DataReceived += Port_DataReceived;//定义接收数据事件

            ComPort PortItem = new ComPort();
            PortItem.Port = Port;
            PortItem.PortRealName = PortNameDesc;
            PortItem.PortDesc = PortRemark;
            PortItem.PortIsRcving = false;
            PortItem.LastRebackTime = DateTime.Now;
            PortItem.RcvBag = CurBagStruct;
            PortItem.StartStr = StartStr;
            PortItem.EndStr = EndStr;
            PortItem.SendOrder = new List();

            PortItem.RcvData = string.Empty;
            PortItem.RcvLst = new List();
            if (LstComPort.Count(c => c.Port == Port) > 0)
            {
                LstComPort.RemoveAll(c => c.Port == Port);
            }
            LstComPort.Add(PortItem);
            return PortItem;
        }
        /// 
        /// 定义数据包中每项的开始位置及所占字节数
        /// 
        /// 
        /// 
        /// 
        public static BagItemPosition SetBagItemPosition(int StartPosition, int Length)
        {
            BagItemPosition Item = new BagItemPosition();
            Item.StartPosition = StartPosition;
            Item.Length = Length;
            return Item;
        }

        /// 
        /// 定义返回数据包结构
        /// 
        /// 字节顺序约定 0--高字节在前,低字节在后,1--高字节在后,低字节在前
        /// 包头所占字节数
        /// 命令所占字节数
        /// 其他位总共占字节数
        /// 数据长度位所占字节数
        /// 校验位所占字节数
        /// 包尾所占字节数
        /// 
        public static BagStruct SetBagStruct(int ByteOrder, BagItemPosition HeadItem, BagItemPosition CmdItem, BagItemPosition OthItem, BagItemPosition DataLenItem, int RealDataItem, int VerItem, int EndItem)
        {
            BagStruct CurRcvBagStruct = new BagStruct();
            CurRcvBagStruct.ByteOrder = ByteOrder;
            CurRcvBagStruct.Head = HeadItem;
            CurRcvBagStruct.Cmd = CmdItem;
            CurRcvBagStruct.Other = OthItem;
            CurRcvBagStruct.DataLen = DataLenItem;
            CurRcvBagStruct.RealDataPos = RealDataItem;
            CurRcvBagStruct.VerifyLen = VerItem;
            CurRcvBagStruct.EndLen = EndItem;
            return CurRcvBagStruct;
        }

        /// 
        /// 打开串口
        /// 
        /// 
        public static void OpenSerialPort(SerialPort Port)
        {
            if (!Port.IsOpen)
            {
                Port.Open();
            }
        }
       
        /// 
        /// 发送串口数据
        /// 
        /// 
        /// 
        public static bool SetPortData(SerialPort Port, string Data)
        {
            bool CurSendFlag = false;
            if (Port.IsOpen)
            {
                byte[] buf = strToHexByte(Data);
                Port.Write(buf, 0, buf.Length);
                CurSendFlag = true;
            }
            return CurSendFlag;
        }

        #region 接收串口应答包

        /// 
        /// 接收串口应答包
        /// 
        /// 
        /// 
        public static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (PortIsCloseing)
            {
                return;
            }
            SerialPort port = sender as SerialPort;
            DateTime CurTime = DateTime.Now;
            string RcvData = string.Empty;
            if (LstComPort != null)
            {
                if (LstComPort.Count(c => c.Port.PortName == port.PortName) > 0)
                {
                    ComPort comPort = LstComPort.Find(c => c.Port.PortName == port.PortName);
                    try
                    {
                        Log.WriteLogToLocal(CurTime + "接收前" + comPort.PortRealName + "数据包临时数据:\r\n" + comPort.RcvData + "\r\n------------------------\r\n", "Log\\IBO_LOG", comPort.PortDesc + "_Receive");
                        RcvData = comPort.RcvData;
                        comPort.PortIsRcving = true;//正在接收串口数据
                        StringBuilder CurRcvData = new StringBuilder();
                        if (port.IsOpen && port.BytesToRead != 0)
                        {
                            while (port.BytesToRead != 0)
                            {
                                byte[] recvBytes = new byte[port.BytesToRead];
                                int bytes = port.Read(recvBytes, 0, recvBytes.Length);
                                if (recvBytes.Length != 0)
                                {
                                    foreach (byte b in recvBytes)
                                    {
                                        CurRcvData.Append(b.ToString("X2") + " ");
                                    }
                                }
                                //Thread.Sleep(20);
                            }
                            Log.WriteLogToLocal(CurTime + "接收" + comPort.PortRealName + "原始数据:\r\n" + CurRcvData + "\r\n------------------------\r\n", "Log\\IBO_LOG", comPort.PortDesc + "_Receive");
                            RcvData += CurRcvData;
                            CurRcvData.Clear();
                            //接收到的数据进行处理,并存储在串口对应的接收队列中
                            //SerialPortFun.DealPortData(comPort, RcvData, CurTime);
                            SerialPortFun.ConcatFullBag(comPort, comPort.RcvBag, RcvData, CurTime);
                            comPort.LastRebackTime = CurTime;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLogToLocal(CurTime + "接收" + comPort.PortRealName + "串口数据(" + RcvData + ")错误:(" + ex.Message+")"+ex.StackTrace + "\r\n", "Log\\IBO_LOG\\ErrorLog", comPort.PortDesc + "_Receive");
                    }
                    finally
                    {
                        comPort.PortIsRcving = false;//接收串口数据完毕
                    }
                }
            }
        }

        #endregion
        /// 
        /// 接收到的数据进行处理,并存储在串口对应的接收队列中
        /// 
        /// 
        /// 
        /// 
        /// 
        public static void ConcatFullBag(ComPort port, BagStruct Struct, string CurRcvData, DateTime CurTime)
        {
            Log.WriteLogToLocal(CurTime + "数据包处理" + port.PortRealName + "原始数据:\r\n" + CurRcvData + "\r\n------------------------\r\n", "Log\\IBO_LOG", port.PortDesc + "_Receive");
            string temp = CurRcvData;
            while (true)
            {
                //校验包头,包尾
                if (!temp.StartsWith(port.StartStr))
                {
                    int index = temp.IndexOf(port.StartStr);
                    if (index == -1)
                        temp = "";
                    else
                        temp = temp.Remove(0, index);
                }
                if (temp.Length > 0)
                {
                    int NoDataBagLen = Struct.Head.Length + Struct.Cmd.Length + Struct.Other.Length + Struct.DataLen.Length + Struct.VerifyLen + Struct.EndLen;
                    int BagDataLen = 0;
                    if (temp.Length > (Struct.DataLen.StartPosition * 3 + Struct.DataLen.Length * 3))
                    {
                        #region 获取数据包的业务数据长度
                        BagDataLen = GetBagDataLen(Struct, temp);
                        //string CurDataLen = "";
                        //string CurDataLenOrg = temp.Substring(Struct.DataLen.StartPosition * 3, Struct.DataLen.Length * 3);
                        //if (Struct.ByteOrder == 1)//高字节在后,低字节在前
                        //{
                        //    CurDataLen = ReverseStr(CurDataLenOrg, 2);
                        //    BagDataLen = Convert.ToInt32(CurDataLen, 16);//16进制
                        //}
                        //else
                        //{
                        //    CurDataLen = CurDataLenOrg;
                        //    BagDataLen = Convert.ToInt32(CurDataLen, 10);//华气特殊 10进制
                        //}
                        #endregion
                    }
                    if (BagDataLen > 0 && temp.Length / 3 >= NoDataBagLen + BagDataLen)
                    {
                        string FullBag = temp.Substring(0, (NoDataBagLen + BagDataLen) * 3);
                        BagItemContent CurBagItem = new BagItemContent();
                        CurBagItem.Head = FullBag.Substring(Struct.Head.StartPosition * 3, Struct.Head.Length * 3).Replace(" ", "");
                        CurBagItem.Cmd = FullBag.Substring(Struct.Cmd.StartPosition * 3, Struct.Cmd.Length * 3).Replace(" ", "");
                        CurBagItem.Other = FullBag.Substring(Struct.Other.StartPosition * 3, Struct.Other.Length * 3).Replace(" ", "");
                        CurBagItem.DataLen = FullBag.Substring(Struct.DataLen.StartPosition * 3, Struct.DataLen.Length * 3).Replace(" ", "");
                        CurBagItem.RealData = FullBag.Substring(Struct.RealDataPos * 3, BagDataLen * 3);
                        CurBagItem.Verify = FullBag.Substring(FullBag.Length - (Struct.VerifyLen + Struct.EndLen) * 3, Struct.VerifyLen * 3).Replace(" ", "");
                        CurBagItem.End = FullBag.Substring(FullBag.Length - Struct.EndLen * 3, Struct.EndLen * 3).Replace(" ", "");
                        if (Struct.ByteOrder == 1)//高字节在后,低字节在前
                        {
                            CurBagItem.Head = Struct.Head.Length 
        /// 获取包长度
        /// 
        /// 
        /// 
        /// 
        public static int GetBagDataLen(BagStruct Struct, string AllBagData)
        {
            int BagDataLen = 0;
            string CurDataLen = "";
            AllBagData = AllBagData.Replace(" ", "");
            string CurDataLenOrg = AllBagData.Substring(Struct.DataLen.StartPosition * 2, Struct.DataLen.Length * 2);
            if (Struct.ByteOrder == 1)//高字节在后,低字节在前
            {
                CurDataLen = ReverseStr(CurDataLenOrg, 2);
                BagDataLen = Convert.ToInt32(CurDataLen, 16);//16进制  需改成通用
            }
            else
            {
                CurDataLen = CurDataLenOrg;
                BagDataLen = Convert.ToInt32(CurDataLen, 10);//华气特殊 10进制
            }
            return BagDataLen;
        }
        
        /// 
        /// 校验数据包
        /// 
        /// 
        /// 
        public static bool CheckBag(string BagHead, string BagEnd, BagStruct Struct, string BagStr, out int RealDataLen)
        {
            bool IsRight = true;
            RealDataLen = 0;
            BagStr = BagStr.Replace(" ", "");
            //校验包头,包尾
            if (!(BagStr.StartsWith(BagHead) && BagStr.EndsWith(BagEnd)))
            {
                IsRight = IsRight && false;
            }

            #region 校验包总长度
            int CurTotalBagLen = Struct.Head.Length + Struct.Cmd.Length + Struct.Other.Length + Struct.DataLen.Length + Struct.VerifyLen + Struct.EndLen;
            if (BagStr.Length  0; i--)
                    //{
                    //    CurDataLen += CurDataLenOrg.Substring((i - 1) * 2, 2);
                    //}
                    RealDataLen = Convert.ToInt32(CurDataLen, 16);
                }
                else
                {
                    CurDataLen = CurDataLenOrg;
                    RealDataLen = Convert.ToInt32(CurDataLen, 10);//华气特殊
                }
                CurTotalBagLen += RealDataLen;
                if (BagStr.Length / 2 != CurTotalBagLen)
                {
                    IsRight = IsRight && false;
                }
            }
            #endregion

            return IsRight;
        }

        /// 
        /// 反转字符串
        /// 
        /// 
        /// 
        /// 
        public static string ReverseStr(string Str, int Len)
        {
            Str = Str.Replace(" ", "");
            string NewStr = "";
            List ls = new List();
            for (int i = 0; i    
        /// 16进制字符串转字节数组   
        ///    
        ///    
        ///    
        public static byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i 
技术分享图片

创建数据接收

技术分享图片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace SerialPortSpace
{
    /// 
    /// 接收数据类
    /// 
    public class PortReciveDataItem
    {
        public BagItemContent ReciveDataItem { get; set; }
        public DateTime ReciveTime { get; set; }
        public string ReciveDataStr { get; set; }
    }
    
    /// 
    /// 串口缓存数据
    /// 
    public class ComPort
    {
        /// 
        /// 串口
        /// 
        public SerialPort Port
        {
            set;
            get;
        }
        
        /// 
        /// 当前串口名称
        /// 
        public string PortRealName
        {
            set;
            get;
        }
        
        /// 
        /// 当前串口描述
        /// 
        public string PortDesc
        {
            set;
            get;
        }

        /// 
        /// 当前串口是否正在接收数据---关闭串口判断
        /// 
        public bool PortIsRcving
        {
            set;
            get;
        }

        /// 
        /// 最近返回数据时间
        /// 
        public DateTime LastRebackTime
        {
            get;
            set;
        }

        /// 
        /// 定义接收包结构
        /// 
        public BagStruct RcvBag
        {
            get;
            set;
        }
        
        /// 
        /// 开始字符
        /// 
        public string StartStr
        {
            set;
            get;
        }

        /// 
        /// 结束字符
        /// 
        public string EndStr
        {
            set;
            get;
        }
        /// 
        /// 串口发送是指令集合
        /// 
        public List SendOrder
        {
            set;
            get;
        }

        /// 
        /// 存储不完整包 临时数据
        /// 
        public string RcvData
        {
            set;
            get;
        }
        
        /// 
        /// 接收到的串口数据--完整包,临时存放
        /// 
        public List RcvLst
        {
            set;
            get;
        }
    }

    /// 
    /// 接收包的结构定义
    /// 
    public class BagStruct
    {
        /// 
        /// 字节顺序约定 0--高字节在前,低字节在后,1--高字节在后,低字节在前
        /// 
        public int ByteOrder
        {
            set;
            get;
        }
        /// 
        /// 包头所占字节数
        /// 
        public BagItemPosition Head
        {
            set;
            get;
        }
        /// 
        /// 命令字段所占字节数
        /// 
        public BagItemPosition Cmd
        {
            set;
            get;
        }
        /// 
        /// 除实际数据包中数据长度及实际数据以外的其他数据项所占字节数
        /// 
        public BagItemPosition Other
        {
            set;
            get;
        }

        /// 
        /// 数据字段长度项所占字节数
        /// 
        public BagItemPosition DataLen
        {
            set;
            get;
        }

        /// 
        /// 实际数据所占字节数---可变的,可以根据实际数据包由DataLen计算所得
        /// 
        public int RealDataPos//开始位置
        {
            set;
            get;
        }

        /// 
        /// 校验位所占字节数
        /// 
        public int VerifyLen
        {
            set;
            get;
        }

        /// 
        /// 包尾所占字节数
        /// 
        public int EndLen
        {
            set;
            get;
        }
    }
    /// 
    /// 定义数据包中每项的开始位置及所占字节数
    /// 
    public class BagItemPosition
    {
        /// 
        /// 开始位置
        /// 
        public int StartPosition
        {
            set;
            get;
        }
        /// 
        /// 所占字节数
        /// 
        public int Length
        {
            set;
            get;
        }
    }

    /// 
    /// 接收包的结构内容
    /// 
    public class BagItemContent
    {
        /// 
        /// 包头
        /// 
        public string Head
        {
            set;
            get;
        }

        /// 
        /// 命令字段
        /// 
        public string Cmd
        {
            set;
            get;
        }

        /// 
        /// 除实际数据包中数据长度及实际数据以外的其他数据项
        /// 
        public string Other
        {
            set;
            get;
        }

        /// 
        /// 数据字段长度项
        /// 
        public string DataLen
        {
            set;
            get;
        }

        /// 
        /// 实际数据
        /// 
        public string RealData
        {
            set;
            get;
        }

        /// 
        /// 校验位
        /// 
        public string Verify
        {
            set;
            get;
        }

        /// 
        /// 包尾
        /// 
        public string End
        {
            set;
            get;
        }
    }   

    
}
技术分享图片

 

c# 串口SerialPort

标签:gif   recv   new   desc   16进制   reg   错误   存储   int start   

原文地址:https://www.cnblogs.com/soundcode/p/9309226.html


评论


亲,登录后才可以留言!