串口数据解析通用方法

来源:互联网 发布:超人电力软件 编辑:程序博客网 时间:2024/06/06 03:30
#region 解析方法2
                // Listening = true;////设置标记,说明我已经开始处理数据,一会儿要使用系统UI的。
                isReceive = true;
                //将数据添加到缓存区
                buffer.AddRange(receiveByte);
                List<int> indexList = new List<int>();//存储包头包尾位置
                for (int i = 0; i < buffer.Count; i++)
                {
                    //如果发现包头获取包尾就记录
                    if (buffer[i] == 0x7E)
                    {
                        indexList.Add(i);
                    }
                }

                //存储接收数据包中包含的完整包
                List<byte[]> bufferList = new List<byte[]>();
                if (indexList.Count >= 2)
                {
                    //按位置截取数据包
                    for (int x = 0; x < indexList.Count; x++)
                    {
                        List<byte> list = new List<byte>();
                        if ((x + 1) < indexList.Count)
                        {
                            for (int y = indexList[x]; y <= indexList[x + 1]; y++)
                            {
                                list.Add(buffer[y]);
                            }
                            bufferList.Add(list.ToArray());
                        }
                    }
                }

                //解析数据包
                for (int j = 0; j < bufferList.Count; j++)
                {
                        //解析
                    
                    }
                }
               
                    //解析完成后移除缓冲区原数据
                    for (int h = 0; h < indexList.Count; h++)
                    {
                        if ((h + 1) < indexList.Count)
                        {
                            buffer.RemoveRange(indexList[h], indexList[h + 1] + 1);
                        }
                    }
                

                //判断剩余缓冲区是否还包含有包头或包尾,如果都不包含,直接清除缓冲区
                for (int g = 0; g < buffer.Count; g++)
                {
                    if (buffer[g] == 0x7E)
                    {

                    }
                    else
                    {
                        buffer.Clear();
                    }
                }

                Console.WriteLine();
                #endregion
原创粉丝点击