[英]How to detect a serial bit byte error in SerialPort class C#
我正在使用 System.IO.Ports.SerialPort 从串行通信中读取数据。 问题是我想在读取字节数组缓冲区并写入文件时确定哪个字节是坏的。 如果我知道哪个字节是坏的,那么我可以重新创建正确的文件,因为我知道文件的 hash。 但它看起来像 System.IO.Ports.SerialPort 只提供了一种使用 SerialPort.ParityReplace 属性“覆盖”错误字节的方法。 如果我正在读取一百万字节的数组,那么我不想设置一个位模式作为替换值,然后在海量数组中搜索这个位模式,因为我可能有很多匹配项。 有没有办法让我在读取字节缓冲区时确定哪个字节未通过奇偶校验检查? 如果不是,那么在通过串行发送文件时对我来说获得奇偶校验样式错误检测的更好方法是什么?
下面的代码是我目前查看串行数据的方式,但如果它更快或提供更高的可靠性,我对其他方法持开放态度。
//... earlier code:
_serialPort.ReadBufferSize = 100000000;
//... more irrelevant code
Thread.Sleep(150000); // wait for 150 seconds for the data to come in.
byte[] HundredKBBuffer = new byte[_serialPort.ReadBufferSize]; // the byte array I'll read from
//read data then discard buffer to get new data from the transmitting machine
_serialPort.Read(HundredKBBuffer, 0, HundredKBBuffer.Length);
_serialPort.DiscardInBuffer();
Console.WriteLine("data received");
//code that reads the byte array, looks for header and trailer and writes file
findHeadAndWriteDataToFile(HundredKBBuffer);
您是否尝试过以 stream 的形式异步读取数据,而不是一次等待获取整个块? 这听起来会让您有更多机会进行错误检查。
第一个想法是在每个字节之后进行奇偶校验,但您可能会降低通信速度(1 个字节的数据,1 个字节的奇偶校验)。
您也可以使用 CRC 代码,它类似于奇偶校验的扩展。 例如,您发送 8 个字节,第 9 个字节是 CRC。 这允许您控制指定大小的数据包的数据。 CRC function 看起来像这样(它是 CRC-8 function,但您可以使用另一个):
private byte CRC8(byte[] Array, int length)
{
byte CRC = 0x00;
int length_buffer = length;
int length_refreshed = length;
CRC = Array[0];
length_refreshed--; ;
for (; length_refreshed > 0; length_refreshed--)
{
CRC = (byte)(((int)CRC) ^ (int)Array[length_buffer - length_refreshed]);
}
return CRC;
}
编辑在这里检查CRC: https://en.wikipedia.org/wiki/Cyclic_redundancy_check
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.