$--TTM,xx,x.x,x.x,a,x.x,x.x,a,x.x,x.x,a,c--c,a,a,hhmmss.ss,a*hh<CR><LF> 请使用QT按照TTM语句进行解析代码
时间: 2023-09-21 17:13:42 浏览: 152
QT 代码
5星 · 资源好评率100%
好的,以下是一个基于Qt的TTM语句解析代码示例:
```cpp
#include <QByteArray>
#include <QDebug>
// 解析TTM语句
void parseTTM(const QByteArray& sentence)
{
// 首先判断语句是否合法
if (sentence.size() < 21 || sentence[0] != '$' || sentence[6] != ',' || sentence[13] != ',' || sentence[20] != '*')
{
qDebug() << "Invalid TTM sentence: " << sentence;
return;
}
// 解析经纬度信息
double lat = 0.0;
if (sentence[7] == 'N')
{
lat = sentence.mid(8, 7).toDouble() / 60.0;
}
else if (sentence[7] == 'S')
{
lat = -1.0 * sentence.mid(8, 7).toDouble() / 60.0;
}
else
{
qDebug() << "Invalid TTM sentence: " << sentence;
return;
}
double lon = 0.0;
if (sentence[15] == 'E')
{
lon = sentence.mid(16, 8).toDouble() / 60.0;
}
else if (sentence[15] == 'W')
{
lon = -1.0 * sentence.mid(16, 8).toDouble() / 60.0;
}
else
{
qDebug() << "Invalid TTM sentence: " << sentence;
return;
}
// 解析船头向信息
double heading = sentence.mid(28, 5).toDouble();
// 解析时间信息
QByteArray timeData = sentence.mid(31, 9);
int hour = timeData.mid(0, 2).toInt();
int minute = timeData.mid(2, 2).toInt();
int second = timeData.mid(4, 2).toInt();
qDebug() << "Time: " << hour << ":" << minute << ":" << second;
// 解析校验和
QByteArray checksumData = sentence.mid(21, 2);
int calculatedChecksum = 0;
for (int i = 1; i < sentence.size() - 3; i++)
{
calculatedChecksum ^= sentence[i];
}
int checksum = checksumData.toInt(nullptr, 16);
if (calculatedChecksum != checksum)
{
qDebug() << "Invalid TTM sentence: " << sentence;
return;
}
// 打印解析结果
qDebug() << "Latitude: " << lat;
qDebug() << "Longitude: " << lon;
qDebug() << "Heading: " << heading;
}
int main()
{
// 假设接收到的TTM语句为以下字符串
QByteArray sentence = "$--TTM,xx,x.x,x.x,a,x.x,x.x,a,x.x,x.x,a,c--c,a,a,125912.00,a*1D\r\n";
parseTTM(sentence);
return 0;
}
```
这段代码解析了TTM语句中的经纬度信息、船头向信息和时间信息,并且进行了校验和的验证。其中,经纬度信息和船头向信息的解析比较简单,直接根据协议文档中的定义进行即可。时间信息可以使用Qt中的QTime类进行解析。校验和的计算可以使用异或运算。
阅读全文