QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
LogFileParser.cc
Go to the documentation of this file.
1#include "LogFileParser.h"
2
8
9#include <QtConcurrent/QtConcurrent>
10#include <QtCore/QFileInfo>
11#include <QtCore/QFutureWatcher>
12#include <QtCore/QPointer>
13
14#include <algorithm>
15#include <cmath>
16#include <limits>
17
18QGC_LOGGING_CATEGORY(LogFileParserLog, "AnalyzeView.LogFileParser")
19
20namespace {
21
22LogParseResult _parseFile(const QString &filePath, const ProgressCallback &progressCallback = nullptr, const CancelToken &cancelToken = nullptr)
23{
24 const QString suffix = QFileInfo(filePath).suffix().toLower();
25
26 if (suffix == QStringLiteral("bin") || suffix == QStringLiteral("log")) {
27 return DataFlashParser::parseFile(filePath, progressCallback, cancelToken);
28 }
29
30 if (suffix == QStringLiteral("ulg")) {
31 return ULogParser::parseFile(filePath, progressCallback, cancelToken);
32 }
33
34 const QString fileTypeDescription = suffix.isEmpty()
35 ? LogFileParser::tr("no extension")
36 : QStringLiteral(".%1").arg(suffix);
37
38 LogParseResult result;
39 result.errorMessage = LogFileParser::tr(
40 "Unsupported file type (%1) for file '%2'. Expected .bin, .log, or .ulg.")
41 .arg(fileTypeDescription, filePath);
42 return result;
43}
44
45} // namespace
46
47// ============================================================================
48// LogFileParser
49// ============================================================================
50
52 : QObject(parent)
53{
54 qCDebug(LogFileParserLog) << this;
55}
56
58{
59 qCDebug(LogFileParserLog) << this;
60}
61
62bool LogFileParser::parseFile(const QString &filePath)
63{
64 ++_parseRequestId;
65 clear();
66 const LogParseResult result = _parseFile(filePath);
67 if (!result.ok) {
68 _setParseError(result.errorMessage);
69 return false;
70 }
71 _applyResult(result);
72 qCDebug(LogFileParserLog) << "Parsed fields" << _availableFields.count()
73 << "parameters" << _parameters.count()
74 << "events" << _events.count();
75 return true;
76}
77
78void LogFileParser::startParsingAsync(const QString &filePath)
79{
80 clear(); // cancels any in-flight parse, resets data
81
82 _cancelToken = std::make_shared<std::atomic<bool>>(false);
83 const quint64 requestId = ++_parseRequestId;
84 _parsing = true;
85 emit parsingChanged();
86
87 // Use QPointer so the background thread's invokeMethod posts are safe even if
88 // this object is destroyed before all pending events are drained from the queue.
89 QPointer<LogFileParser> self(this);
90 auto progressCallback = [self, requestId](float v) {
91 if (!self) return;
92 QMetaObject::invokeMethod(self.data(), [self, requestId, v]() {
93 if (!self || requestId != self->_parseRequestId) return;
94 self->_parseProgress = v;
95 emit self->parseProgressChanged();
96 }, Qt::QueuedConnection);
97 };
98
99 auto *watcher = new QFutureWatcher<LogParseResult>(this);
100 (void) connect(watcher, &QFutureWatcher<LogParseResult>::finished, this,
101 [this, watcher, filePath, requestId]() {
102 const LogParseResult result = watcher->result();
103 watcher->deleteLater();
104
105 if (requestId != _parseRequestId) {
106 return;
107 }
108
109 _parseProgress = 1.f;
111 _parsing = false;
112 emit parsingChanged();
113
114 if (!result.ok) {
115 _setParseError(result.errorMessage);
116 emit parseFileFinished(filePath, false, result.errorMessage);
117 return;
118 }
119
120 _applyResult(result);
121 emit parseFileFinished(filePath, true, QString());
122 });
123
124 watcher->setFuture(QtConcurrent::run([filePath, progressCallback, cancelToken = _cancelToken]() {
125 return _parseFile(filePath, progressCallback, cancelToken);
126 }));
127}
128
129void LogFileParser::_applyResult(const LogParseResult &result)
130{
131 _availableFields = result.availableFields;
132 _plottableFields = result.plottableFields;
133 _parameters = result.parameters;
134
135 // Enrich parameter rows with FactMetaData (decimal places, units,
136 // short description, enum strings/values) from the bundled metadata JSON.
137 if (!_parameters.isEmpty()) {
142 _parameters,
143 result.detectedVehicleType,
145 result.firmwareMinorVersion);
146 }
147 }
148 _events = result.events;
149 _messages = result.messages;
150 _modeSegments = result.modeSegments;
151 _dropouts = result.dropouts;
152
153 // Build mode color cache in first-appearance (chronological) order.
154 _modeColorCache.clear();
155 _modeNames.clear();
156 for (const QVariant &v : _modeSegments) {
157 const QString mode = v.toMap().value(QStringLiteral("mode")).toString();
158 if (!mode.isEmpty() && !_modeNames.contains(mode)) {
159 _modeColorCache.insert(mode, _modeColorCache.size());
160 _modeNames.append(mode);
161 }
162 }
163 _fieldSamples = result.fieldSamples;
164 _sampleCount = result.sampleCount;
165 _detectedVehicleType = result.detectedVehicleType;
168 emit parametersChanged();
169 emit eventsChanged();
170 emit messagesChanged();
171 emit modeSegmentsChanged();
172 emit modeNamesChanged();
173 emit dropoutsChanged();
175 if (_minTimestamp != result.minTimestamp || _maxTimestamp != result.maxTimestamp) {
176 _minTimestamp = result.minTimestamp;
177 _maxTimestamp = result.maxTimestamp;
178 emit timeRangeChanged();
179 }
180 emit sampleCountChanged();
181 if (_startTime != result.startTime) {
182 _startTime = result.startTime;
183 emit startTimeChanged();
184 }
185
186 _parseComplete = true;
188}
189
191{
192 if (_parsing) {
193 ++_parseRequestId;
194 if (_cancelToken) {
195 _cancelToken->store(true, std::memory_order_relaxed);
196 }
197 _parsing = false;
198 emit parsingChanged();
199 }
200
201 const bool oldParseComplete = _parseComplete;
202 _parseComplete = false;
203 if (oldParseComplete) { emit parseCompleteChanged(); }
204
205 if (!_parseError.isEmpty()) { _parseError.clear(); emit parseErrorChanged(); }
206 if (!_availableFields.isEmpty()) { _availableFields.clear(); emit availableFieldsChanged(); }
207 if (!_parameters.isEmpty()) { _parameters.clear(); emit parametersChanged(); }
208 if (!_events.isEmpty()) { _events.clear(); emit eventsChanged(); }
209 if (!_messages.isEmpty()) { _messages.clear(); emit messagesChanged(); }
210 if (!_modeSegments.isEmpty()) { _modeSegments.clear(); emit modeSegmentsChanged(); }
211 if (!_modeNames.isEmpty()) { _modeNames.clear(); _modeColorCache.clear(); emit modeNamesChanged(); }
212 if (!_dropouts.isEmpty()) { _dropouts.clear(); emit dropoutsChanged(); }
213 if (!_detectedVehicleType.isEmpty()) { _detectedVehicleType.clear(); emit detectedVehicleTypeChanged(); }
214 if (!_plottableFields.isEmpty()) { _plottableFields.clear(); emit plottableFieldsChanged(); }
215
216 _fieldSamples.clear();
217 _gpsLatField.clear();
218 _gpsLonField.clear();
219 _gpsAltField.clear();
220 if (_minTimestamp != -1.0 || _maxTimestamp != -1.0) {
221 _minTimestamp = -1.0;
222 _maxTimestamp = -1.0;
223 emit timeRangeChanged();
224 }
225 if (_sampleCount != 0) { _sampleCount = 0; emit sampleCountChanged(); }
226 if (!_startTime.isNull()) { _startTime = QDateTime(); emit startTimeChanged(); }
227 if (_parseProgress != 0.f) { _parseProgress = 0.f; emit parseProgressChanged(); }
228}
229
230QVariantList LogFileParser::fieldSamples(const QString &fieldName) const
231{
232 QVariantList output;
233 const auto it = _fieldSamples.constFind(fieldName);
234 if (it == _fieldSamples.cend()) { return output; }
235 const QVector<QPointF> &points = it.value();
236 output.reserve(points.size());
237 for (const QPointF &p : points) { output.append(p); }
238 return output;
239}
240
241QVariantMap LogFileParser::fieldMinMax(const QString &fieldName) const
242{
243 const auto it = _fieldSamples.constFind(fieldName);
244 if (it == _fieldSamples.cend() || it->isEmpty()) { return {}; }
245 const QVector<QPointF> &points = it.value();
246 double minY = std::numeric_limits<double>::max();
247 double maxY = std::numeric_limits<double>::lowest();
248 for (const QPointF &p : points) {
249 if (p.y() < minY) minY = p.y();
250 if (p.y() > maxY) maxY = p.y();
251 }
252 return QVariantMap{{QStringLiteral("min"), minY}, {QStringLiteral("max"), maxY}};
253}
254
255QVariantList LogFileParser::fieldSamplesFiltered(const QString &fieldName, double minX, double maxX, int pixelWidth) const
256{
257 QVariantList output;
258 const auto it = _fieldSamples.constFind(fieldName);
259 if (it == _fieldSamples.cend() || pixelWidth <= 0 || maxX <= minX) { return output; }
260
261 const QVector<QPointF> &points = it.value();
262
263 // Find the slice within [minX, maxX]
264 const auto sliceBegin = std::lower_bound(points.cbegin(), points.cend(), minX,
265 [](const QPointF &p, double t) { return p.x() < t; });
266 const auto sliceEnd = std::upper_bound(sliceBegin, points.cend(), maxX,
267 [](double t, const QPointF &p) { return t < p.x(); });
268
269 const qsizetype sliceCount = std::distance(sliceBegin, sliceEnd);
270 if (sliceCount == 0) { return output; }
271
272 // If already sparse enough, return slice as-is
273 if (sliceCount <= 4 * pixelWidth) {
274 output.reserve(sliceCount);
275 for (auto jt = sliceBegin; jt != sliceEnd; ++jt) { output.append(*jt); }
276 return output;
277 }
278
279 // Screen-space min/max bucketing: one bucket per pixel column.
280 // For each column track first, min-y, max-y, last indices; flush in time order.
281 output.reserve(4 * pixelWidth);
282 const double range = maxX - minX;
283
284 auto columnOf = [&](double x) -> int {
285 return static_cast<int>((x - minX) / range * pixelWidth);
286 };
287
288 // Per-column state
289 int curCol = -1;
290 qsizetype firstIdx = -1;
291 qsizetype minIdx = -1;
292 qsizetype maxIdx = -1;
293 qsizetype lastIdx = -1;
294
295 auto flush = [&]() {
296 if (firstIdx < 0) return;
297 // Collect the up-to-4 representative indices in time order, deduplicated
298 qsizetype indices[4] = { firstIdx, minIdx, maxIdx, lastIdx };
299 std::sort(indices, indices + 4);
300 qsizetype prev = -1;
301 for (qsizetype idx : indices) {
302 if (idx != prev) {
303 output.append(*(sliceBegin + idx));
304 prev = idx;
305 }
306 }
307 };
308
309 for (qsizetype i = 0; i < sliceCount; ++i) {
310 const QPointF &p = *(sliceBegin + i);
311 const int col = std::clamp(columnOf(p.x()), 0, pixelWidth - 1);
312 if (col != curCol) {
313 flush();
314 curCol = col;
315 firstIdx = i;
316 minIdx = i;
317 maxIdx = i;
318 } else {
319 if (p.y() < (sliceBegin + minIdx)->y()) minIdx = i;
320 if (p.y() > (sliceBegin + maxIdx)->y()) maxIdx = i;
321 }
322 lastIdx = i;
323 }
324 flush();
325
326 return output;
327}
328
329double LogFileParser::fieldValueAt(const QString &fieldName, double timestampSeconds) const
330{
331 const auto it = _fieldSamples.constFind(fieldName);
332 if (it == _fieldSamples.cend() || it->isEmpty()) {
333 return std::numeric_limits<double>::quiet_NaN();
334 }
335 const QVector<QPointF> &points = it.value();
336 const auto lower = std::lower_bound(points.cbegin(), points.cend(), timestampSeconds,
337 [](const QPointF &p, double t) { return p.x() < t; });
338
339 if (lower == points.cbegin()) { return lower->y(); }
340 if (lower == points.cend()) { return points.constLast().y(); }
341
342 const auto prev = std::prev(lower);
343 return (std::fabs(prev->x() - timestampSeconds) <= std::fabs(lower->x() - timestampSeconds))
344 ? prev->y() : lower->y();
345}
346
347QString LogFileParser::modeColor(const QString &modeName) const
348{
349 static const QStringList modePalette = {
350 QStringLiteral("#E53935"), // red
351 QStringLiteral("#FB8C00"), // orange
352 QStringLiteral("#FDD835"), // yellow
353 QStringLiteral("#43A047"), // green
354 QStringLiteral("#00897B"), // teal
355 QStringLiteral("#00ACC1"), // cyan
356 QStringLiteral("#1E88E5"), // blue
357 QStringLiteral("#5E35B1"), // indigo
358 QStringLiteral("#8E24AA"), // purple
359 QStringLiteral("#D81B60"), // pink
360 QStringLiteral("#6D4C41"), // brown
361 QStringLiteral("#546E7A"), // blue grey
362 };
363
364 const auto it = _modeColorCache.constFind(modeName);
365 if (it == _modeColorCache.constEnd()) {
366 return modePalette[0]; // unknown mode; cache was not seeded yet
367 }
368 return modePalette[it.value() % modePalette.size()];
369}
370
371QString LogFileParser::modeAt(double timestampSeconds) const
372{
373 for (const QVariant &v : _modeSegments) {
374 const QVariantMap seg = v.toMap();
375 const double start = seg.value(QStringLiteral("start")).toDouble();
376 const double end = seg.value(QStringLiteral("end")).toDouble();
377 if (timestampSeconds >= start && timestampSeconds <= end) {
378 return seg.value(QStringLiteral("mode")).toString();
379 }
380 }
381 return QString();
382}
383
384QVariantList LogFileParser::eventsNear(double timestampSeconds, double thresholdSeconds) const
385{
386 QVariantList matches;
387 const double threshold = std::max(0.0, thresholdSeconds);
388 const auto lower = std::lower_bound(_events.cbegin(), _events.cend(),
389 timestampSeconds - threshold,
390 [](const QVariant &v, double t) {
391 return v.toMap().value(QStringLiteral("time")).toDouble() < t;
392 });
393 for (auto it = lower; it != _events.cend(); ++it) {
394 const QVariantMap ev = it->toMap();
395 if (ev.value(QStringLiteral("time")).toDouble() > timestampSeconds + threshold) { break; }
396 matches.append(ev);
397 }
398 return matches;
399}
400
401void LogFileParser::_setParseError(const QString &error)
402{
403 if (_parseError != error) {
404 _parseError = error;
405 emit parseErrorChanged();
406 }
407}
408
410{
411 return _gpsAltField;
412}
413
414QVariantMap LogFileParser::gpsCoordAt(double timestampSeconds) const
415{
416 if (_gpsLatField.isEmpty() || _gpsLonField.isEmpty()) {
417 return {};
418 }
419
420 const auto latIt = _fieldSamples.constFind(_gpsLatField);
421 const auto lonIt = _fieldSamples.constFind(_gpsLonField);
422 if (latIt == _fieldSamples.cend() || lonIt == _fieldSamples.cend()) {
423 return {};
424 }
425
426 const QVector<QPointF> &latPts = latIt.value();
427 const QVector<QPointF> &lonPts = lonIt.value();
428 if (latPts.isEmpty() || lonPts.isEmpty()) {
429 return {};
430 }
431
432 // Binary search for the sample with timestamp closest to timestampSeconds.
433 int lo = 0;
434 int hi = latPts.size() - 1;
435 while (lo < hi) {
436 const int mid = (lo + hi) / 2;
437 if (latPts[mid].x() < timestampSeconds) {
438 lo = mid + 1;
439 } else {
440 hi = mid;
441 }
442 }
443 // lo is the first index >= timestampSeconds; compare with lo-1.
444 if (lo > 0) {
445 const double dPrev = timestampSeconds - latPts[lo - 1].x();
446 const double dCurr = latPts[lo].x() - timestampSeconds;
447 if (dPrev < dCurr) {
448 --lo;
449 }
450 }
451
452 const int lonIdx = std::min(lo, static_cast<int>(lonPts.size()) - 1);
453 QVariantMap coord;
454 coord[QStringLiteral("latitude")] = latPts[lo].y();
455 coord[QStringLiteral("longitude")] = lonPts[lonIdx].y();
456 return coord;
457}
458
459QVariantList LogFileParser::gpsPath() const
460{
461 // Candidate field-name pairs tried in priority order.
462 // All values are stored in degrees (the parsers handle any raw-unit conversion).
463 // statusField: if non-null, that field's value must be >= statusMinValue to accept the sample.
464 // This is used for APM GPS messages where Status < 3 means no valid 3D fix.
465 struct CandidatePair {
466 const char *latField;
467 const char *lonField;
468 const char *altField;
469 const char *statusField;
470 double statusMinValue;
471 };
472
473 static const CandidatePair candidates[] = {
474 // PX4 ULog — vehicle_global_position (EKF-fused position, double degrees)
475 { "vehicle_global_position.lat", "vehicle_global_position.lon", "vehicle_global_position.alt", nullptr, 0 },
476 { "vehicle_global_position.latitude_deg", "vehicle_global_position.longitude_deg", "vehicle_global_position.alt", nullptr, 0 },
477 // PX4 ULog — vehicle_gps_position / sensor_gps (newer firmware uses latitude_deg)
478 { "vehicle_gps_position.latitude_deg", "vehicle_gps_position.longitude_deg", "vehicle_gps_position.altitude_msl_m", nullptr, 0 },
479 { "vehicle_gps_position[0].latitude_deg", "vehicle_gps_position[0].longitude_deg", "vehicle_gps_position[0].altitude_msl_m", nullptr, 0 },
480 { "sensor_gps.latitude_deg", "sensor_gps.longitude_deg", "sensor_gps.altitude_msl_m", nullptr, 0 },
481 { "sensor_gps[0].latitude_deg", "sensor_gps[0].longitude_deg", "sensor_gps[0].altitude_msl_m", nullptr, 0 },
482 // APM DataFlash — GPS message (Status >= 3 = 3D fix; 'L' type already divided by 1e7)
483 { "GPS.Lat", "GPS.Lng", "GPS.Alt", "GPS.Status", 3 },
484 { "GPS2.Lat", "GPS2.Lng", "GPS2.Alt", "GPS2.Status", 3 },
485 // APM DataFlash — POS message (EKF-fused; no status field, 'L' type already divided by 1e7)
486 { "POS.Lat", "POS.Lng", "POS.Alt", nullptr, 0 },
487 };
488
489 for (const auto &c : candidates) {
490 const auto latIt = _fieldSamples.constFind(QLatin1String(c.latField));
491 const auto lonIt = _fieldSamples.constFind(QLatin1String(c.lonField));
492 if (latIt == _fieldSamples.cend() || lonIt == _fieldSamples.cend()) {
493 continue;
494 }
495
496 const QVector<QPointF> &latPts = latIt.value();
497 const QVector<QPointF> &lonPts = lonIt.value();
498 if (latPts.isEmpty() || lonPts.isEmpty()) {
499 continue;
500 }
501
502 // Resolve optional status field (same message, same sample count as lat/lon).
503 const QVector<QPointF> *statusPts = nullptr;
504 if (c.statusField) {
505 const auto statusIt = _fieldSamples.constFind(QLatin1String(c.statusField));
506 if (statusIt != _fieldSamples.cend() && !statusIt.value().isEmpty()) {
507 statusPts = &statusIt.value();
508 }
509 }
510
511 qCDebug(LogFileParserLog) << "gpsPath: found candidate" << c.latField
512 << "samples:" << latPts.size()
513 << "first lat:" << latPts.first().y()
514 << "first lon:" << lonPts.first().y();
515
516 QVariantList path;
517 const int n = std::min(latPts.size(), lonPts.size());
518 path.reserve(n);
519
520 for (int i = 0; i < n; i++) {
521 // Skip samples that don't have a valid GPS fix.
522 if (statusPts && i < statusPts->size() && (*statusPts)[i].y() < c.statusMinValue) {
523 continue;
524 }
525
526 const double lat = latPts[i].y();
527 const double lon = lonPts[i].y();
528
529 if (lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0
530 || (qFuzzyIsNull(lat) && qFuzzyIsNull(lon))) {
531 continue;
532 }
533 QVariantMap coord;
534 coord[QStringLiteral("latitude")] = lat;
535 coord[QStringLiteral("longitude")] = lon;
536 path.append(coord);
537 }
538
539 qCDebug(LogFileParserLog) << "gpsPath: valid points after filter:" << path.size();
540
541 if (!path.isEmpty()) {
542 _gpsLatField = QLatin1String(c.latField);
543 _gpsLonField = QLatin1String(c.lonField);
544 // Only cache the alt field if it actually exists and has samples;
545 // otherwise the altitude chart would be shown with no data.
546 const QLatin1String altField(c.altField);
547 const auto altIt = _fieldSamples.constFind(altField);
548 _gpsAltField = (altIt != _fieldSamples.cend() && !altIt.value().isEmpty()) ? altField : QLatin1String{};
549 return path;
550 }
551
552 qCDebug(LogFileParserLog) << "gpsPath: all" << n << "points filtered out for candidate" << c.latField;
553 }
554
555 qCDebug(LogFileParserLog) << "gpsPath: no GPS data found; available fields containing 'lat' or 'lon':";
556 for (auto it = _fieldSamples.cbegin(); it != _fieldSamples.cend(); ++it) {
557 const QString &fn = it.key();
558 if (fn.contains(QLatin1String("lat"), Qt::CaseInsensitive) || fn.contains(QLatin1String("lon"), Qt::CaseInsensitive)) {
559 qCDebug(LogFileParserLog) << " " << fn << "samples:" << it.value().size()
560 << (it.value().isEmpty() ? 0.0 : it.value().first().y());
561 }
562 }
563 return {};
564}
std::function< void(float)> ProgressCallback
std::shared_ptr< std::atomic< bool > > CancelToken
Error error
#define QGC_LOGGING_CATEGORY(name, categoryStr)
Q_INVOKABLE QVariantList eventsNear(double timestampSeconds, double thresholdSeconds) const
Q_INVOKABLE double fieldValueAt(const QString &fieldName, double timestampSeconds) const
Q_INVOKABLE QVariantList fieldSamplesFiltered(const QString &fieldName, double minX, double maxX, int pixelWidth) const
void parametersChanged()
Q_INVOKABLE QVariantMap fieldMinMax(const QString &fieldName) const
Q_INVOKABLE QVariantList fieldSamples(const QString &fieldName) const
void timeRangeChanged()
void parseProgressChanged()
void parseErrorChanged()
void dropoutsChanged()
Q_INVOKABLE void startParsingAsync(const QString &filePath)
void startTimeChanged()
void detectedVehicleTypeChanged()
void sampleCountChanged()
void parsingChanged()
LogFileParser(QObject *parent=nullptr)
void plottableFieldsChanged()
void availableFieldsChanged()
void modeSegmentsChanged()
void parseCompleteChanged()
Q_INVOKABLE QVariantMap gpsCoordAt(double timestampSeconds) const
Q_INVOKABLE QString modeAt(double timestampSeconds) const
Q_INVOKABLE QString gpsAltitudeFieldName() const
Q_INVOKABLE QVariantList gpsPath() const
void parseFileFinished(const QString &filePath, bool ok, const QString &errorMessage)
void modeNamesChanged()
Q_INVOKABLE void clear()
Q_INVOKABLE bool parseFile(const QString &filePath)
Q_INVOKABLE QString modeColor(const QString &modeName) const
void eventsChanged()
void messagesChanged()
static void enrichForAPM(QVariantList &parameters, const QString &vehicleType, int major, int minor)
static void enrichForPX4(QVariantList &parameters)
LogParseResult parseFile(const QString &filePath, const ProgressCallback &progressCallback, const CancelToken &cancelToken)
LogParseResult parseFile(const QString &filePath, const ProgressCallback &progressCallback, const CancelToken &cancelToken)
QVariantList modeSegments
QStringList plottableFields
QStringList availableFields
QHash< QString, QVector< QPointF > > fieldSamples