我正在尝试编写自己的 nmea 解析器,因为我只需要来自 gps 的一些信息,并且不需要解释所有消息。我遇到的问题是我的 nmea 消息验证器给了我一个错误的校验和。有人能看出我在做什么错吗?
我正在使用Codepedia - Calculating and Validating nmea sentence的想法。
// Returns True if a sentence's checksum matches the
// calculated checksum
// Calculates the checksum for a sentence
private static bool IsValid(string sentence)
{
if (sentence == "")
return false;
if (sentence.Length < 14)
return false;
try
{
string[] Words = GetWords(sentence);
Log.writeToLog(Words);
int checksum = 0;
string CheckToCompare = Words[Words.Length - 1];
StringBuilder sb = new StringBuilder();
for (int i = 1; i < (Words.Length - 2); i++)
{
sb.Append(Words[i]);
}
string sentecenToParse = sb.ToString();
foreach (char charY in sentecenToParse)
{
checksum ^= Convert.ToByte(charY);
}
Log.writeToLog("Checksum: " + checksum.ToString("X2"));
Log.writeToLog("Obtained CheckSum: " + CheckToCompare);
return String.Equals(checksum.ToString("X2"), CheckToCompare, StringComparison.OrdinalIgnoreCase);
}
catch (Exception exc)
{
Log.writeToLog("Exception caused by sentence:" + sentence);
Log.writeToLog("Exception error message: " + exc.Message);
return false;
}
}
// Divides a sentence into individual Words
public static string[] GetWords(string sentence)
{
char[] separator = { ',', '*' };
return sentence.Split(separator);
}
运行日志
10:30:07 23-02-2011 Opening Port
10:30:08 23-02-2011 Opened Port
10:30:10 23-02-2011 Processing Data
10:30:12 23-02-2011 $GPGGA
10:30:12 23-02-2011 102957.92
10:30:12 23-02-2011 4104.8569
10:30:12 23-02-2011 N
10:30:12 23-02-2011 00836.4700
10:30:12 23-02-2011 W
10:30:12 23-02-2011 1
10:30:12 23-02-2011 4
10:30:12 23-02-2011 15.100
10:30:12 23-02-2011 157.133
10:30:12 23-02-2011 M
10:30:12 23-02-2011 52.386
10:30:12 23-02-2011 M
10:30:12 23-02-2011 0
10:30:12 23-02-2011 0
10:30:13 23-02-2011 79
10:30:13 23-02-2011 Checksum: 6D
10:30:13 23-02-2011 Obtained CheckSum: 79
10:30:13 23-02-2011 Invalid sentence
10:30:13 23-02-2011 $GPRMC
10:30:13 23-02-2011 102957.92
10:30:13 23-02-2011 A
10:30:13 23-02-2011 4104.8569
10:30:13 23-02-2011 N
10:30:13 23-02-2011 00836.4700
10:30:13 23-02-2011 W
10:30:13 23-02-2011 0.000
10:30:13 23-02-2011 5.822
10:30:13 23-02-2011 230211
10:30:13 23-02-2011 0
10:30:13 23-02-2011 W
10:30:14 23-02-2011 A
10:30:14 23-02-2011 2B
10:30:14 23-02-2011 Checksum: 4E
10:30:15 23-02-2011 Obtained CheckSum: 2B
10:30:15 23-02-2011 Invalid sentence