连续读取和解析串行数据的快速方法 [英] Fast approach to read and parse serial-data continuously

查看:40
本文介绍了连续读取和解析串行数据的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程来读取和解析串行数据.消息采用二进制格式,以字符F"、S"、Q"或M"开头.没有换行符,也没有特殊的结束字符(上面的字符表示消息已完成以及准备好解析之前的所有内容).

I've got a thread to read and parse serial data. The messages are in binary format and start with either the character 'F', 'S', 'Q' or 'M'. There are no newlines and there is no special ending character (the characters above state that a message is finished and everything before it is ready to be parsed).

如何持续读取和解析数据?

How do I continuously read and parse the data?

我想到的是有一个 4096 字节长的输入缓冲区(字节数组),然后按照以下步骤操作:

All that comes to my mind is having a 4096 byte long input buffer (byte array) and then follow this procedure:

  • 手动跟踪缓冲区中的位置
  • 通过SerialPort.Read(buffer, position, byteCount)
  • 向其追加可用数据
  • 尝试从缓冲区中解析尽可能多的消息
  • 将其余部分复制到临时缓冲区
  • 重置输入缓冲区
  • 将临时缓冲区的内容复制到原始缓冲区
  • 设置缓冲区中的位置

你能想到更快/更简单的方法吗?

推荐答案

取得成功的一个非常简单的方法是停止尝试让它更快.没有意义,串口数据速率非常非常低,而现代计算机非常非常快.您的 Read() 调用只返回一个字节,很少返回 2.

A very simple way to get ahead is to stop trying to make it faster. There is no point, serial port data rates are very, very low and modern computers are very, very fast. Your Read() call only ever returns a single byte, rarely 2.

请注意,这很难看出,当您调试和单步执行代码时,您会人为地大大减慢程序的速度.允许接收更多字节,因此 Read() 调用返回更多字节.但是当程序以正常速度运行时不会发生这种情况.

Note that this is hard to see, when you debug and single-step through the code then you'll artificially slow down your program a great deal. Allowing more bytes to be received and thus more of them getting returned by the Read() call. But this doesn't happen when the program runs at normal speed.

所以使用 SerialPort.BaseStream.ReadByte() 代替.使代码非常简单.

So use SerialPort.BaseStream.ReadByte() instead. Makes the code very simple.

这篇关于连续读取和解析串行数据的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆