QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
ULogFullHandler.cc
Go to the documentation of this file.
1#include "ULogFullHandler.h"
2
5
6#include <QtCore/QStringList>
7#include <QtCore/QTimeZone>
8
9#include <algorithm>
10#include <stdexcept>
11
12#include <ulog_cpp/subscription.hpp>
13
14QGC_LOGGING_CATEGORY(ULogFullHandlerLog, "AnalyzeView.ULogFullHandler")
15
16// Used for testing
17//#define QGC_NO_LOG_START_TIME
18
19namespace {
20
21QString _px4NavStateName(int state)
22{
23 switch (state) {
24 // Values from PX4 VehicleStatus.msg NAVIGATION_STATE_* constants
25 case 0: return QStringLiteral("Manual");
26 case 1: return QStringLiteral("Altitude");
27 case 2: return QStringLiteral("Position");
28 case 3: return QStringLiteral("Mission");
29 case 4: return QStringLiteral("Hold");
30 case 5: return QStringLiteral("Return");
31 case 6: return QStringLiteral("Position Slow");
32 case 8: return QStringLiteral("Altitude Cruise");
33 case 10: return QStringLiteral("Acro");
34 case 12: return QStringLiteral("Descend");
35 case 13: return QStringLiteral("Termination");
36 case 14: return QStringLiteral("Offboard");
37 case 15: return QStringLiteral("Stabilized");
38 case 17: return QStringLiteral("Takeoff");
39 case 18: return QStringLiteral("Land");
40 case 19: return QStringLiteral("Follow Target");
41 case 20: return QStringLiteral("Precision Land");
42 case 21: return QStringLiteral("Orbit");
43 case 22: return QStringLiteral("VTOL Takeoff");
44 default: return QStringLiteral("Mode %1").arg(state);
45 }
46}
47
48bool _isNumericBasicType(ulog_cpp::Field::BasicType type)
49{
50 using BT = ulog_cpp::Field::BasicType;
51 switch (type) {
52 case BT::INT8:
53 case BT::UINT8:
54 case BT::INT16:
55 case BT::UINT16:
56 case BT::INT32:
57 case BT::UINT32:
58 case BT::INT64:
59 case BT::UINT64:
60 case BT::FLOAT:
61 case BT::DOUBLE:
62 case BT::BOOL:
63 return true;
64 default:
65 return false;
66 }
67}
68
69} // namespace
70
72 : _result(result)
73{
74}
75
76void ULogFullHandler::error(const std::string &msg, bool is_recoverable)
77{
78 const QString errorMessage = QString::fromStdString(msg);
79 if (!is_recoverable) {
80 _hadFatalError = true;
81 if (_result.errorMessage.isEmpty()) {
82 _result.errorMessage = errorMessage;
83 }
84 }
85 qCWarning(ULogFullHandlerLog) << "ULog parse error:" << errorMessage;
86}
87
88void ULogFullHandler::fileHeader(const ulog_cpp::FileHeader& header)
89{
90 _logStartSecs = static_cast<double>(header.header().timestamp) / 1e6;
91}
92
93void ULogFullHandler::messageFormat(const ulog_cpp::MessageFormat &message_format)
94{
95 _formats[message_format.name()] = std::make_shared<ulog_cpp::MessageFormat>(message_format);
96}
97
98void ULogFullHandler::addLoggedMessage(const ulog_cpp::AddLoggedMessage &add_logged_message)
99{
100 const auto it = _formats.find(add_logged_message.messageName());
101 if (it != _formats.cend()) {
102 _subscriptions[add_logged_message.msgId()] = {
103 it->second,
104 add_logged_message.multiId(),
105 add_logged_message.messageName()
106 };
107 }
108}
109
111{
112 _headerComplete = true;
113 for (auto &[name, fmt] : _formats) {
114 fmt->resolveDefinition(_formats);
115 }
116}
117
118void ULogFullHandler::data(const ulog_cpp::Data &data)
119{
120 if (!_headerComplete) {
121 return;
122 }
123
124 const auto it = _subscriptions.find(data.msgId());
125 if (it == _subscriptions.cend()) {
126 return;
127 }
128
129 const SubscriptionInfo &sub = it->second;
130 if (!sub.format) {
131 return;
132 }
133
134 try {
135 const ulog_cpp::TypedDataView view(data, *sub.format);
136
137 // Extract timestamp (ULog convention: field named "timestamp", unit µs)
138 double timestampSecs = -1.0;
139 if (sub.format->fieldMap().count("timestamp") > 0) {
140 const uint64_t tsUs = view.at("timestamp").as<uint64_t>();
141 timestampSecs = static_cast<double>(tsUs) / 1e6;
142 // The logger writes each topic's last value at log start with its original, older timestamp
143 if (timestampSecs < _logStartSecs) {
144 timestampSecs = _logStartSecs;
145 _staleSampleCount++;
146 }
147 _lastTimestampSecs = timestampSecs;
148 }
149
150 // Extract GPS UTC start time from the first GNSS sample that has one.
151 // Define QGC_NO_LOG_START_TIME at build time to suppress this for UI testing.
152#ifndef QGC_NO_LOG_START_TIME
153 if (_result.startTime.isNull() && timestampSecs >= 0.0) {
154 const auto& fieldMap = sub.format->fieldMap();
155 uint64_t utcUsec = 0;
156 uint64_t utcTimestampUs = 0;
157 if ((sub.topicName == "sensor_gnss" || sub.topicName == "sensor_gps" ||
158 sub.topicName == "vehicle_gps_position") &&
159 fieldMap.count("time_utc_usec") > 0) {
160 utcUsec = view.at("time_utc_usec").as<uint64_t>();
161 utcTimestampUs = view.at("timestamp").as<uint64_t>();
162 } else if (sub.topicName == "vehicle_gnss" && fieldMap.count("receiver") > 0) {
163 // vehicle_gnss nests the receiver's sensor_gnss sample. Its outer timestamp is the later publish
164 // time from the sensors module, so pair the UTC time with the receiver's own timestamp.
165 const auto& receiver = fieldMap.at("receiver");
166 if (receiver->type().type == ulog_cpp::Field::BasicType::NESTED && receiver->definitionResolved() &&
167 receiver->nestedFormat()->fieldMap().count("time_utc_usec") > 0 &&
168 receiver->nestedFormat()->fieldMap().count("timestamp") > 0) {
169 utcUsec = view.at(receiver)["time_utc_usec"].as<uint64_t>();
170 utcTimestampUs = view.at(receiver)["timestamp"].as<uint64_t>();
171 }
172 }
173 if (utcUsec > 0) {
174 if (utcUsec >= utcTimestampUs) {
175 const qint64 startMs = static_cast<qint64>((utcUsec - utcTimestampUs) / 1000);
176 _result.startTime = QDateTime::fromMSecsSinceEpoch(startMs, QTimeZone::utc());
177 }
178 }
179 }
180#endif // QGC_NO_LOG_START_TIME
181
182 // Field name: "topic_name.field" or "topic_name[N].field" for multi-instance
183 const QString prefix = (sub.multiId > 0)
184 ? QStringLiteral("%1[%2].").arg(QString::fromStdString(sub.topicName)).arg(sub.multiId)
185 : QString::fromStdString(sub.topicName) + QLatin1Char('.');
186
187 for (const auto &field : sub.format->fields()) {
188 // Skip padding fields and the timestamp itself
189 if (field->name().rfind("_padding", 0) == 0) {
190 continue;
191 }
192 if (field->name() == "timestamp") {
193 continue;
194 }
195 if (!field->definitionResolved()) {
196 continue;
197 }
198
199 const QString fieldName = prefix + QString::fromStdString(field->name());
200 _collectFieldSamples(fieldName, *field, view.at(field), timestampSecs);
201 }
202
203 _result.sampleCount++;
204
205 if (timestampSecs >= 0.0) {
206 if (_result.minTimestamp < 0.0 || timestampSecs < _result.minTimestamp) {
207 _result.minTimestamp = timestampSecs;
208 }
209 _result.maxTimestamp = std::max(_result.maxTimestamp, timestampSecs);
210 }
211 } catch (const std::exception &e) {
212 qCWarning(ULogFullHandlerLog) << "Failed to decode data message:" << e.what();
213 }
214}
215
216void ULogFullHandler::_collectFieldSamples(const QString& fieldName, const ulog_cpp::Field& field,
217 const ulog_cpp::Value& value, double timestampSecs)
218{
219 if (field.arrayLength() < 0) {
220 _collectElementSamples(fieldName, field, value, timestampSecs);
221 return;
222 }
223
224 // char arrays are strings, not per-element signals
225 if (field.type().type == ulog_cpp::Field::BasicType::CHAR) {
226 _fieldSet.insert(fieldName);
227 return;
228 }
229
230 for (int i = 0; i < field.arrayLength(); i++) {
231 _collectElementSamples(QStringLiteral("%1[%2]").arg(fieldName).arg(i), field, value[static_cast<size_t>(i)],
232 timestampSecs);
233 }
234}
235
236void ULogFullHandler::_collectElementSamples(const QString& fieldName, const ulog_cpp::Field& field,
237 const ulog_cpp::Value& value, double timestampSecs)
238{
239 if (field.type().type == ulog_cpp::Field::BasicType::NESTED) {
240 for (const auto& nestedField : field.nestedFormat()->fields()) {
241 if (nestedField->name().rfind("_padding", 0) == 0) {
242 continue;
243 }
244 if (!nestedField->definitionResolved()) {
245 continue;
246 }
247 const QString nestedFieldName = fieldName + QLatin1Char('.') + QString::fromStdString(nestedField->name());
248 _collectFieldSamples(nestedFieldName, *nestedField, value[*nestedField], timestampSecs);
249 }
250 return;
251 }
252
253 _fieldSet.insert(fieldName);
254
255 if (!_isNumericBasicType(field.type().type) || (timestampSecs < 0.0)) {
256 return;
257 }
258
259 _result.fieldSamples[fieldName].append(QPointF(timestampSecs, value.as<double>()));
260 _plottableFieldSet.insert(fieldName);
261}
262
263void ULogFullHandler::logging(const ulog_cpp::Logging &logging)
264{
265 const double timestampSecs = static_cast<double>(logging.timestamp()) / 1e6;
266 const QString text = QString::fromStdString(logging.message());
267
268 if (text.isEmpty()) {
269 return;
270 }
271
272 QVariantMap msgRow;
273 msgRow[QStringLiteral("time")] = timestampSecs;
274 msgRow[QStringLiteral("text")] = text;
275 _result.messages.append(msgRow);
276
277 using Level = ulog_cpp::Logging::Level;
278 if (logging.logLevel() <= Level::Warning) {
279 const QString eventType = (logging.logLevel() <= Level::Error)
280 ? QStringLiteral("error")
281 : QStringLiteral("warning");
282
283 if (timestampSecs >= 0.0) {
284 QVariantMap eventRow;
285 eventRow[QStringLiteral("time")] = timestampSecs;
286 eventRow[QStringLiteral("type")] = eventType;
287 eventRow[QStringLiteral("description")] = text;
288 _result.events.append(eventRow);
289 }
290 }
291}
292
293void ULogFullHandler::parameter(const ulog_cpp::Parameter &param)
294{
295 const QString name = QString::fromStdString(param.field().name());
296 if (name.isEmpty()) {
297 return;
298 }
299
300 QVariant value;
301 bool isFloat = false;
302 try {
303 // ULog parameters are restricted to int32_t and float per spec.
304 // as<double>() safely static_casts either type.
305 value = param.value().as<double>();
306 isFloat = (param.field().type().type == ulog_cpp::Field::BasicType::FLOAT);
307 } catch (const std::exception &) {
308 value = QVariant();
309 }
310
311 QVariantMap row;
312 row[QStringLiteral("name")] = name;
313 row[QStringLiteral("value")] = value;
314 row[QStringLiteral("isFloat")] = isFloat;
315 // hasDefault / defaultValue / isDefault are filled in by finalize() once all
316 // ParameterDefault messages have been collected.
317 _result.parameters.append(row);
318}
319
320void ULogFullHandler::parameterDefault(const ulog_cpp::ParameterDefault &param_default)
321{
322 const QString name = QString::fromStdString(param_default.field().name());
323 if (name.isEmpty()) {
324 return;
325 }
326 try {
327 const double defaultVal = param_default.value().as<double>();
328 // Only store system defaults (bit 0 set). Configuration defaults (bit 1) are
329 // user-visible overrides and not what we want to compare against.
330 using DT = ulog_cpp::ulog_parameter_default_type_t;
331 if ((static_cast<uint8_t>(param_default.defaultType()) &
332 static_cast<uint8_t>(DT::system)) != 0) {
333 _paramDefaults[name] = defaultVal;
334 }
335 } catch (const std::exception &) {
336 // Ignore unreadable defaults
337 }
338}
339
340void ULogFullHandler::dropout(const ulog_cpp::Dropout &dropout)
341{
342 if (_lastTimestampSecs < 0.0) {
343 return;
344 }
345
346 const double start = _lastTimestampSecs;
347 const double end = start + static_cast<double>(dropout.durationMs()) / 1000.0;
348 QVariantMap row;
349 row[QStringLiteral("start")] = start;
350 row[QStringLiteral("end")] = end;
351 _result.dropouts.append(row);
352}
353
355{
356 if (_staleSampleCount > 0) {
357 qCDebug(ULogFullHandlerLog) << "Moved" << _staleSampleCount << "samples older than log start to"
358 << _logStartSecs << "s";
359 }
360
361 // Detect vehicle type from vehicle_status.vehicle_type
362 // PX4 vehicle_type enum: 0=Unknown, 1=Rotary Wing, 2=Fixed Wing, 3=Rover, 4=Airship
363 const auto vehicleTypeIt = _result.fieldSamples.constFind(QStringLiteral("vehicle_status.vehicle_type"));
364 if (vehicleTypeIt != _result.fieldSamples.cend() && !vehicleTypeIt->isEmpty()) {
365 const int vtype = static_cast<int>(vehicleTypeIt->first().y());
366 switch (vtype) {
367 case 1: _result.detectedVehicleType = QStringLiteral("Multirotor/Helicopter"); break;
368 case 2: _result.detectedVehicleType = QStringLiteral("Fixed Wing"); break;
369 case 3: _result.detectedVehicleType = QStringLiteral("Rover"); break;
370 case 4: _result.detectedVehicleType = QStringLiteral("Airship"); break;
371 default: break; // 0 = Unknown, leave empty so UI shows "Unknown"
372 }
373 }
374
375 // Derive mode segments from vehicle_status.nav_state samples.
376 // nav_state is a uint8_t mapped to the PX4 navigation_state enum.
377 const auto navStateIt = _result.fieldSamples.constFind(QStringLiteral("vehicle_status.nav_state"));
378 if (navStateIt != _result.fieldSamples.cend()) {
379 const QVector<QPointF> &samples = navStateIt.value();
380 int lastNavState = -1;
381 double segmentStart = -1.0;
382 QString segmentMode;
383
384 for (const QPointF &pt : samples) {
385 const int navState = static_cast<int>(pt.y());
386 if (navState != lastNavState) {
387 // Close the previous segment
388 if (lastNavState >= 0 && segmentStart >= 0.0) {
389 QVariantMap seg;
390 seg[QStringLiteral("mode")] = segmentMode;
391 seg[QStringLiteral("start")] = segmentStart;
392 seg[QStringLiteral("end")] = pt.x();
393 _result.modeSegments.append(seg);
394 }
395 lastNavState = navState;
396 segmentStart = pt.x();
397 segmentMode = _px4NavStateName(navState);
398 }
399 }
400
401 // Close the final open segment
402 if (lastNavState >= 0 && segmentStart >= 0.0 && _result.maxTimestamp >= segmentStart) {
403 QVariantMap seg;
404 seg[QStringLiteral("mode")] = segmentMode;
405 seg[QStringLiteral("start")] = segmentStart;
406 seg[QStringLiteral("end")] = _result.maxTimestamp;
407 _result.modeSegments.append(seg);
408 }
409 }
410
411 // Sort field lists for consistent display
412 _result.availableFields = _fieldSet.values();
413 std::sort(_result.availableFields.begin(), _result.availableFields.end());
414 _result.plottableFields = _plottableFieldSet.values();
415 std::sort(_result.plottableFields.begin(), _result.plottableFields.end());
416
417 // Annotate parameter rows with default value info now that all ParameterDefault
418 // messages have been collected.
419 for (int i = 0; i < _result.parameters.size(); i++) {
420 QVariantMap row = _result.parameters[i].toMap();
421 const QString name = row.value(QStringLiteral("name")).toString();
422 const auto it = _paramDefaults.constFind(name);
423 if (it != _paramDefaults.constEnd()) {
424 const double defaultVal = it.value();
425 const QVariant valueVariant = row.value(QStringLiteral("value"));
426 row[QStringLiteral("hasDefault")] = true;
427 row[QStringLiteral("defaultValue")] = defaultVal;
428 // Treat parameters whose value couldn't be read (invalid QVariant from
429 // the catch block in parameter()) as non-default so they are never
430 // hidden by the "Changed only" filter.
431 bool isDefault = false;
432 if (valueVariant.isValid() && valueVariant.canConvert<double>()) {
433 const double currentVal = valueVariant.toDouble();
434 // qFuzzyCompare is undefined when either value is 0.0, so use exact
435 // equality for the zero case and relative comparison otherwise.
436 isDefault = (currentVal == defaultVal)
437 || (!qFuzzyIsNull(defaultVal) && qFuzzyCompare(currentVal, defaultVal));
438 }
439 row[QStringLiteral("isDefault")] = isDefault;
440 } else {
441 row[QStringLiteral("hasDefault")] = false;
442 row[QStringLiteral("defaultValue")] = QVariant();
443 row[QStringLiteral("isDefault")] = false;
444 }
445 _result.parameters[i] = row;
446 }
447
448 _result.sourceType = LogParseResult::SourceType::PX4ULog;
449 _result.ok = true;
450}
std::function< void(float)> ProgressCallback
#define QGC_LOGGING_CATEGORY(name, categoryStr)
void parameter(const ulog_cpp::Parameter &parameter) override
void fileHeader(const ulog_cpp::FileHeader &header) override
ULogFullHandler(LogParseResult &result, const ProgressCallback &progressCallback=nullptr)
void addLoggedMessage(const ulog_cpp::AddLoggedMessage &add_logged_message) override
void error(const std::string &msg, bool is_recoverable) override
void logging(const ulog_cpp::Logging &logging) override
void messageFormat(const ulog_cpp::MessageFormat &message_format) override
void parameterDefault(const ulog_cpp::ParameterDefault &parameter_default) override
void data(const ulog_cpp::Data &data) override
void dropout(const ulog_cpp::Dropout &dropout) override
void headerComplete() override