9#include <QtConcurrent/QtConcurrent>
10#include <QtCore/QFileInfo>
11#include <QtCore/QFutureWatcher>
12#include <QtCore/QPointer>
24 const QString suffix = QFileInfo(filePath).suffix().toLower();
26 if (suffix == QStringLiteral(
"bin") || suffix == QStringLiteral(
"log")) {
30 if (suffix == QStringLiteral(
"ulg")) {
34 const QString fileTypeDescription = suffix.isEmpty()
35 ? LogFileParser::tr(
"no extension")
36 : QStringLiteral(
".%1").arg(suffix);
40 "Unsupported file type (%1) for file '%2'. Expected .bin, .log, or .ulg.")
41 .arg(fileTypeDescription, filePath);
54 qCDebug(LogFileParserLog) <<
this;
59 qCDebug(LogFileParserLog) <<
this;
72 qCDebug(LogFileParserLog) <<
"Parsed fields" << _availableFields.count()
73 <<
"parameters" << _parameters.count()
74 <<
"events" << _events.count();
82 _cancelToken = std::make_shared<std::atomic<bool>>(
false);
83 const quint64 requestId = ++_parseRequestId;
89 QPointer<LogFileParser> self(
this);
90 auto progressCallback = [self, requestId](
float v) {
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);
99 auto *watcher =
new QFutureWatcher<LogParseResult>(
this);
100 (void) connect(watcher, &QFutureWatcher<LogParseResult>::finished,
this,
101 [
this, watcher, filePath, requestId]() {
103 watcher->deleteLater();
105 if (requestId != _parseRequestId) {
109 _parseProgress = 1.f;
120 _applyResult(result);
124 watcher->setFuture(QtConcurrent::run([filePath, progressCallback, cancelToken = _cancelToken]() {
125 return _parseFile(filePath, progressCallback, cancelToken);
137 if (!_parameters.isEmpty()) {
154 _modeColorCache.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);
186 _parseComplete =
true;
195 _cancelToken->store(
true, std::memory_order_relaxed);
201 const bool oldParseComplete = _parseComplete;
202 _parseComplete =
false;
208 if (!_events.isEmpty()) { _events.clear(); emit
eventsChanged(); }
209 if (!_messages.isEmpty()) { _messages.clear(); emit
messagesChanged(); }
211 if (!_modeNames.isEmpty()) { _modeNames.clear(); _modeColorCache.clear(); emit
modeNamesChanged(); }
212 if (!_dropouts.isEmpty()) { _dropouts.clear(); emit
dropoutsChanged(); }
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;
226 if (!_startTime.isNull()) { _startTime = QDateTime(); emit
startTimeChanged(); }
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); }
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();
252 return QVariantMap{{QStringLiteral(
"min"), minY}, {QStringLiteral(
"max"), maxY}};
258 const auto it = _fieldSamples.constFind(fieldName);
259 if (it == _fieldSamples.cend() || pixelWidth <= 0 || maxX <= minX) {
return output; }
261 const QVector<QPointF> &points = it.value();
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(); });
269 const qsizetype sliceCount = std::distance(sliceBegin, sliceEnd);
270 if (sliceCount == 0) {
return output; }
273 if (sliceCount <= 4 * pixelWidth) {
274 output.reserve(sliceCount);
275 for (
auto jt = sliceBegin; jt != sliceEnd; ++jt) { output.append(*jt); }
281 output.reserve(4 * pixelWidth);
282 const double range = maxX - minX;
284 auto columnOf = [&](
double x) ->
int {
285 return static_cast<int>((x - minX) / range * pixelWidth);
290 qsizetype firstIdx = -1;
291 qsizetype minIdx = -1;
292 qsizetype maxIdx = -1;
293 qsizetype lastIdx = -1;
296 if (firstIdx < 0)
return;
298 qsizetype indices[4] = { firstIdx, minIdx, maxIdx, lastIdx };
299 std::sort(indices, indices + 4);
301 for (qsizetype idx : indices) {
303 output.append(*(sliceBegin + idx));
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);
319 if (p.y() < (sliceBegin + minIdx)->y()) minIdx = i;
320 if (p.y() > (sliceBegin + maxIdx)->y()) maxIdx = i;
331 const auto it = _fieldSamples.constFind(fieldName);
332 if (it == _fieldSamples.cend() || it->isEmpty()) {
333 return std::numeric_limits<double>::quiet_NaN();
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; });
339 if (lower == points.cbegin()) {
return lower->y(); }
340 if (lower == points.cend()) {
return points.constLast().y(); }
342 const auto prev = std::prev(lower);
343 return (std::fabs(prev->x() - timestampSeconds) <= std::fabs(lower->x() - timestampSeconds))
344 ? prev->y() : lower->y();
349 static const QStringList modePalette = {
350 QStringLiteral(
"#E53935"),
351 QStringLiteral(
"#FB8C00"),
352 QStringLiteral(
"#FDD835"),
353 QStringLiteral(
"#43A047"),
354 QStringLiteral(
"#00897B"),
355 QStringLiteral(
"#00ACC1"),
356 QStringLiteral(
"#1E88E5"),
357 QStringLiteral(
"#5E35B1"),
358 QStringLiteral(
"#8E24AA"),
359 QStringLiteral(
"#D81B60"),
360 QStringLiteral(
"#6D4C41"),
361 QStringLiteral(
"#546E7A"),
364 const auto it = _modeColorCache.constFind(modeName);
365 if (it == _modeColorCache.constEnd()) {
366 return modePalette[0];
368 return modePalette[it.value() % modePalette.size()];
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();
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;
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; }
401void LogFileParser::_setParseError(
const QString &
error)
403 if (_parseError !=
error) {
416 if (_gpsLatField.isEmpty() || _gpsLonField.isEmpty()) {
420 const auto latIt = _fieldSamples.constFind(_gpsLatField);
421 const auto lonIt = _fieldSamples.constFind(_gpsLonField);
422 if (latIt == _fieldSamples.cend() || lonIt == _fieldSamples.cend()) {
426 const QVector<QPointF> &latPts = latIt.value();
427 const QVector<QPointF> &lonPts = lonIt.value();
428 if (latPts.isEmpty() || lonPts.isEmpty()) {
434 int hi = latPts.size() - 1;
436 const int mid = (lo + hi) / 2;
437 if (latPts[mid].x() < timestampSeconds) {
445 const double dPrev = timestampSeconds - latPts[lo - 1].x();
446 const double dCurr = latPts[lo].x() - timestampSeconds;
452 const int lonIdx = std::min(lo,
static_cast<int>(lonPts.size()) - 1);
454 coord[QStringLiteral(
"latitude")] = latPts[lo].y();
455 coord[QStringLiteral(
"longitude")] = lonPts[lonIdx].y();
465 struct CandidatePair {
466 const char *latField;
467 const char *lonField;
468 const char *altField;
469 const char *statusField;
470 double statusMinValue;
473 static const CandidatePair candidates[] = {
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 },
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 },
483 {
"GPS.Lat",
"GPS.Lng",
"GPS.Alt",
"GPS.Status", 3 },
484 {
"GPS2.Lat",
"GPS2.Lng",
"GPS2.Alt",
"GPS2.Status", 3 },
486 {
"POS.Lat",
"POS.Lng",
"POS.Alt",
nullptr, 0 },
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()) {
496 const QVector<QPointF> &latPts = latIt.value();
497 const QVector<QPointF> &lonPts = lonIt.value();
498 if (latPts.isEmpty() || lonPts.isEmpty()) {
503 const QVector<QPointF> *statusPts =
nullptr;
505 const auto statusIt = _fieldSamples.constFind(QLatin1String(c.statusField));
506 if (statusIt != _fieldSamples.cend() && !statusIt.value().isEmpty()) {
507 statusPts = &statusIt.value();
511 qCDebug(LogFileParserLog) <<
"gpsPath: found candidate" << c.latField
512 <<
"samples:" << latPts.size()
513 <<
"first lat:" << latPts.first().y()
514 <<
"first lon:" << lonPts.first().y();
517 const int n = std::min(latPts.size(), lonPts.size());
520 for (
int i = 0; i < n; i++) {
522 if (statusPts && i < statusPts->size() && (*statusPts)[i].y() < c.statusMinValue) {
526 const double lat = latPts[i].y();
527 const double lon = lonPts[i].y();
529 if (lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0
530 || (qFuzzyIsNull(lat) && qFuzzyIsNull(lon))) {
534 coord[QStringLiteral(
"latitude")] = lat;
535 coord[QStringLiteral(
"longitude")] = lon;
539 qCDebug(LogFileParserLog) <<
"gpsPath: valid points after filter:" << path.size();
541 if (!path.isEmpty()) {
542 _gpsLatField = QLatin1String(c.latField);
543 _gpsLonField = QLatin1String(c.lonField);
546 const QLatin1String altField(c.altField);
547 const auto altIt = _fieldSamples.constFind(altField);
548 _gpsAltField = (altIt != _fieldSamples.cend() && !altIt.value().isEmpty()) ? altField : QLatin1String{};
552 qCDebug(LogFileParserLog) <<
"gpsPath: all" << n <<
"points filtered out for candidate" << c.latField;
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());
std::function< void(float)> ProgressCallback
std::shared_ptr< std::atomic< bool > > CancelToken
#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
Q_INVOKABLE QVariantMap fieldMinMax(const QString &fieldName) const
Q_INVOKABLE QVariantList fieldSamples(const QString &fieldName) const
void parseProgressChanged()
Q_INVOKABLE void startParsingAsync(const QString &filePath)
void detectedVehicleTypeChanged()
void sampleCountChanged()
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)
Q_INVOKABLE bool parseFile(const QString &filePath)
Q_INVOKABLE QString modeColor(const QString &modeName) const
LogParseResult parseFile(const QString &filePath, const ProgressCallback &progressCallback, const CancelToken &cancelToken)
LogParseResult parseFile(const QString &filePath, const ProgressCallback &progressCallback, const CancelToken &cancelToken)
QString detectedVehicleType
QVariantList modeSegments
QStringList plottableFields
QStringList availableFields
QHash< QString, QVector< QPointF > > fieldSamples