我有一个用 C# 编写的小应用程序,它在 SerialPort 上侦听以获取信息。信息以:STX + data + ETX + BCC
. 然后我们计算传输数据包的 BCC 并进行比较。功能是:
private bool ConsistencyCheck(byte[] buffer)
{
byte expected = buffer[buffer.Length - 1];
byte actual = 0x00;
for (int i = 1; i < buffer.Length - 1; i++)
{
actual ^= buffer[i];
}
if ((expected & 0xFF) != (actual & 0xFF))
{
if (AppTools.Logger.IsDebugEnabled)
{
AppTools.Logger.Warn(String.Format("ConsistencyCheck failed: Expected: #{0} Got: #{1}", expected, actual));
}
}
return (expected & 0xFF) == (actual & 0xFF);
}
它似乎或多或少地起作用。它准确地不包括 STX 或 BCC,并且准确地将 ETX 包括在其计算中。它似乎大部分时间都在工作,但是我们至少有两台机器正在运行它,这两台机器都是 Windows 2008 64 位,其中 BCC 计算永远不会累加。从最近的日志中提取一个字节 20 被发送,我计算出 16 和一个 11 被发送的地方,我计算出 27。
我对这里发生的事情感到非常困惑。我在这里是否缺少 64 位或 Windows 2008“陷阱”?任何帮助甚至疯狂的想法都将不胜感激。
编辑:
这是读取数据的代码:
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// Retrieve number of bytes in the buffer
int bytes = serialPort.BytesToRead;
// Create a byte array to hold the awaiting data
byte[] received = new byte[bytes];
//read the data and store it
serialPort.Read(received, 0, bytes);
DataReceived(received);
}
该DataReceived()
函数获取该字符串并将其附加到全局StringBuilder
对象。然后它一直作为一个字符串构建器,直到它被传递给这些不同的函数,此时它.ToString()
被调用。
EDIT2:更改了代码以反映我更改的对字节/字节数组而不是字符串进行操作的例程。
EDIT3:我还没有弄清楚这一点,而且我得到了更多结果完全不一致的测试数据(发送校验和的数量每次都不同,没有模式)。感觉就像我只是在计算校验和错误,但我不知道如何。