仍然不确定该问题的标题是什么...
我通过使用serialPort.ReadExisting()
(返回一个字符串)而不是serialPort.Read()
(返回一个字节数组)来利用.Net框架。我这样做的原因是因为serialPort.ReadExisting()
使我可以访问尚未与SerialPort缓冲区一起存储在缓冲区中的流数据。但是,此方法要求我以字符串形式读取数据,但似乎没有办法告诉串行端口“嘿,使用base64编码”,而我的选项是ASCII,UTF8等。serialPort.Encoding = Encoding.ASCII;
。现在,我知道我的数据不是问题,因为此测试有效:
string a = Convert.ToBase64String(transmitBytes,Base64FormattingOptions.None);
byte[] b = Convert.FromBase64String(a);
SHA256 sha256 = SHA256.Create();
byte[] hash1 = sha256.ComputeHash(transmitBytes);
byte[] hash2 = sha256.ComputeHash(b);
if (CompareHash(hash1,hash2))
Console.WriteLine("good check");
}
private static bool CompareHash(byte[] a1,byte[] a2)
{
for (int i = 0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
return false;
}
return true;
}
但是,如果我通过电线发送数据,则会遇到问题。我的理论是,这是因为ReadExisting()方法试图将这些位读取为7位ascii值,并且数据的许多部分都超出了6位base64字符的范围:[
,{{1之类的东西}}和_
会引起问题,如果接收端尝试读取7位而不是6位,则可能会发生此问题。
我试图在低噪声环境中建立串行通信,并且尝试了几种数据长度组合来发送每个串行消息。
令人反感的相关代码如下(最后一行抛出异常):
|
有什么想法可以调试,并希望修复正在发生的事情吗?我不想求助于serialPort.Read()
// sending machine is working I think
serialPort.DataBits = 8; //also tried (6 and 7) many many times)
_serialPort.Write(Convert.ToBase64String(transmitBytes,Base64FormattingOptions.None));
// receiver machine is trowing the format exception
serialPort.DataBits = 8; // also tried (6 and 7) many many times)
byte[] BigBuffer = new byte[_serialPort.ReadBufferSize];
// read data then discard buffer to get new data from the transmitting machine
BigBuffer = Convert.FromBase64String(_serialPort.ReadExisting()); // throws exception
其他测试方案: 我发送了一些不切实际的值字符串以进行调试,并得到了相同的异常。我必须让发送者感到满意,因此在接收器出现异常之前,它多次发送了该值。 这是原始字符串base64:
exception.Message = "The input is not a valid Base-64 string as it contains a non-base 64 character,more than two padding characters,or an illegal character among the padding characters."
这是从ReadExisting()接收到的字符串(由于串行端口设置为ASCII编码,因此我假设这是ASCII)。传递给Convert.FromBase64String()
时,此字符串会导致异常。utz+EDJUdpgLAAAATG9yZSBpbXBzdW3UAPpp4FQlifaZAzUzyh25062szzbhSyVs3ehe6nU+UYlnRSMB782r