如何检测串行端口类C#中的串行位字节错误



我正在使用System.IO.Ports.SerialPort从串行通信中读取数据。问题是,当我读取字节数组缓冲区并写入文件时,我想确定哪个字节是坏的。如果我知道哪个字节是坏的,那么我可以重新创建正确的文件,因为我知道文件的哈希。但看起来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);

您是否尝试过将数据作为流异步读取,而不是等待一次获取整个块?这听起来会让你有更多的机会进行错误检查。

使用.NET框架读取串行端口的正确方法是什么?

第一个想法是在每个字节之后进行奇偶校验,但可能会降低通信速度(1字节的数据,1字节的奇偶校验(。

您可以使用类似于奇偶校验扩展的CRC码。例如,您发送8个字节,第九个字节是CRC。这允许您控制指定大小数据包的数据。CRC函数如下(它是CRC-8函数,但您可以使用其他函数(:

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

相关内容

最新更新