Commit 27776288 authored by Don Gagne's avatar Don Gagne
Browse files

Convert Log Replay to Link

parent a48b1192
......@@ -161,6 +161,7 @@ FORMS += \
src/QGCQmlWidgetHolder.ui \
src/ui/HDDisplay.ui \
src/ui/Linechart.ui \
src/ui/LogReplayLinkConfigurationWidget.ui \
src/ui/MainWindow.ui \
src/ui/map/QGCMapTool.ui \
src/ui/map/QGCMapToolBar.ui \
......@@ -228,6 +229,7 @@ HEADERS += \
src/comm/LinkConfiguration.h \
src/comm/LinkInterface.h \
src/comm/LinkManager.h \
src/comm/LogReplayLink.h \
src/comm/MAVLinkProtocol.h \
src/comm/MockLink.h \
src/comm/MockLinkFileServer.h \
......@@ -276,6 +278,7 @@ HEADERS += \
src/ui/linechart/LinechartWidget.h \
src/ui/linechart/Scrollbar.h \
src/ui/linechart/ScrollZoomer.h \
src/ui/LogReplayLinkConfigurationWidget.h \
src/ui/MainWindow.h \
src/ui/map/MAV2DIcon.h \
src/ui/map/QGCMapTool.h \
......@@ -365,6 +368,7 @@ SOURCES += \
src/CmdLineOptParser.cc \
src/comm/LinkConfiguration.cc \
src/comm/LinkManager.cc \
src/comm/LogReplayLink.cc \
src/comm/MAVLinkProtocol.cc \
src/comm/MockLink.cc \
src/comm/MockLinkFileServer.cc \
......@@ -405,6 +409,7 @@ SOURCES += \
src/ui/linechart/LinechartWidget.cc \
src/ui/linechart/Scrollbar.cc \
src/ui/linechart/ScrollZoomer.cc \
src/ui/LogReplayLinkConfigurationWidget.cc \
src/ui/MainWindow.cc \
src/ui/map/MAV2DIcon.cc \
src/ui/map/QGCMapTool.cc \
......
......@@ -33,6 +33,7 @@ This file is part of the QGROUNDCONTROL project
#endif
#include "UDPLink.h"
#include "TCPLink.h"
#include "LogReplayLink.h"
#ifdef QT_DEBUG
#include "MockLink.h"
......@@ -95,6 +96,9 @@ LinkConfiguration* LinkConfiguration::createSettings(int type, const QString& na
case LinkConfiguration::TypeTcp:
config = new TCPConfiguration(name);
break;
case LinkConfiguration::TypeLogReplay:
config = new LogReplayLinkConfiguration(name);
break;
#ifdef QT_DEBUG
case LinkConfiguration::TypeMock:
config = new MockConfiguration(name);
......@@ -123,6 +127,9 @@ LinkConfiguration* LinkConfiguration::duplicateSettings(LinkConfiguration* sourc
case TypeTcp:
dupe = new TCPConfiguration(dynamic_cast<TCPConfiguration*>(source));
break;
case TypeLogReplay:
dupe = new LogReplayLinkConfiguration(dynamic_cast<LogReplayLinkConfiguration*>(source));
break;
#ifdef QT_DEBUG
case TypeMock:
dupe = new MockConfiguration(dynamic_cast<MockConfiguration*>(source));
......
......@@ -44,13 +44,14 @@ public:
#endif
TypeUdp, ///< UDP Link
TypeTcp, ///< TCP Link
// TODO Below is not yet implemented
#if 0
// TODO Below is not yet implemented
TypeForwarding, ///< Forwarding Link
TypeXbee, ///< XBee Proprietary Link
TypeOpal, ///< Opal-RT Link
#endif
TypeMock, ///< Mock Link for Unitesting
TypeLogReplay,
TypeLast // Last type value (type >= TypeLast == invalid)
};
......
......@@ -91,6 +91,9 @@ public:
* @return The nominal data rate of the interface in bit per second, 0 if unknown
**/
virtual qint64 getConnectionSpeed() const = 0;
/// @return true: This link is replaying a log file, false: Normal two-way communication link
virtual bool isLogReplay(void) { return false; }
/**
* @Brief Get the current incoming data rate.
......
......@@ -96,6 +96,9 @@ LinkInterface* LinkManager::createConnectedLink(LinkConfiguration* config)
case LinkConfiguration::TypeTcp:
pLink = new TCPLink(dynamic_cast<TCPConfiguration*>(config));
break;
case LinkConfiguration::TypeLogReplay:
pLink = new LogReplayLink(dynamic_cast<LogReplayLinkConfiguration*>(config));
break;
#ifdef QT_DEBUG
case LinkConfiguration::TypeMock:
pLink = new MockLink(dynamic_cast<MockConfiguration*>(config));
......@@ -394,6 +397,10 @@ void LinkManager::loadLinkConfigurationList()
pLink = (LinkConfiguration*)new TCPConfiguration(name);
pLink->setPreferred(preferred);
break;
case LinkConfiguration::TypeLogReplay:
pLink = (LinkConfiguration*)new LogReplayLinkConfiguration(name);
pLink->setPreferred(preferred);
break;
#ifdef QT_DEBUG
case LinkConfiguration::TypeMock:
pLink = (LinkConfiguration*)new MockConfiguration(name);
......
......@@ -41,6 +41,7 @@ This file is part of the PIXHAWK project
#endif
#include "UDPLink.h"
#include "TCPLink.h"
#include "LogReplayLink.h"
#ifdef QT_DEBUG
#include "MockLink.h"
......@@ -110,6 +111,7 @@ public:
void setConnectionsAllowed(void) { _connectionsSuspended = false; }
/// Creates, connects (and adds) a link based on the given configuration instance.
/// Link takes ownership of config.
LinkInterface* createConnectedLink(LinkConfiguration* config);
/// Creates, connects (and adds) a link based on the given configuration name.
......
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include "LogReplayLink.h"
#include "LinkManager.h"
#include <QFileInfo>
const char* LogReplayLinkConfiguration::_logFilenameKey = "logFilename";
const char* LogReplayLink::_errorTitle = "Log Replay Error";
LogReplayLinkConfiguration::LogReplayLinkConfiguration(const QString& name) :
LinkConfiguration(name)
{
}
LogReplayLinkConfiguration::LogReplayLinkConfiguration(LogReplayLinkConfiguration* copy) :
LinkConfiguration(copy)
{
_logFilename = copy->logFilename();
}
void LogReplayLinkConfiguration::copyFrom(LinkConfiguration *source)
{
LinkConfiguration::copyFrom(source);
LogReplayLinkConfiguration* ssource = dynamic_cast<LogReplayLinkConfiguration*>(source);
Q_ASSERT(ssource != NULL);
_logFilename = ssource->logFilename();
}
void LogReplayLinkConfiguration::saveSettings(QSettings& settings, const QString& root)
{
settings.beginGroup(root);
settings.setValue(_logFilenameKey, _logFilename);
settings.endGroup();
}
void LogReplayLinkConfiguration::loadSettings(QSettings& settings, const QString& root)
{
settings.beginGroup(root);
_logFilename = settings.value(_logFilenameKey, "").toString();
settings.endGroup();
}
void LogReplayLinkConfiguration::updateSettings(void)
{
// Doesn't support changing filename on the fly is already connected
}
QString LogReplayLinkConfiguration::logFilenameShort(void)
{
QFileInfo fi(_logFilename);
return fi.fileName();
}
LogReplayLink::LogReplayLink(LogReplayLinkConfiguration* config) :
_connected(false),
_replayAccelerationFactor(1.0f)
{
Q_ASSERT(config);
_config = config;
_readTickTimer.moveToThread(this);
QObject::connect(&_readTickTimer, &QTimer::timeout, this, &LogReplayLink::_readNextLogEntry);
QObject::connect(this, &LogReplayLink::_playOnThread, this, &LogReplayLink::_play);
QObject::connect(this, &LogReplayLink::_pauseOnThread, this, &LogReplayLink::_pause);
QObject::connect(this, &LogReplayLink::_setAccelerationFactorOnThread, this, &LogReplayLink::_setAccelerationFactor);
moveToThread(this);
}
LogReplayLink::~LogReplayLink(void)
{
_disconnect();
}
bool LogReplayLink::_connect(void)
{
// Disallow replay when any links are connected
if (LinkManager::instance()->anyConnectedLinks()) {
emit communicationError(_errorTitle, "You must close all connections prior to replaying a log.");
return false;
}
if (isRunning()) {
quit();
wait();
}
start(HighPriority);
return true;
}
bool LogReplayLink::_disconnect(void)
{
if (_connected) {
quit();
wait();
_connected = false;
emit disconnected();
}
return true;
}
void LogReplayLink::run(void)
{
// Load the log file
if (!_loadLogFile()) {
return;
}
_connected = true;
emit connected();
// Start playback
_play();
// Run normal event loop until exit
exec();
}
void LogReplayLink::_replayError(const QString& errorMsg)
{
qDebug() << _errorTitle << errorMsg;
emit communicationError(_errorTitle, errorMsg);
}
void LogReplayLink::readBytes(void)
{
// FIXME: This is a bad virtual from LinkInterface?
}
/// Since this is log replay, we just drops writes on the floor
void LogReplayLink::writeBytes(const char* bytes, qint64 cBytes)
{
Q_UNUSED(bytes);
Q_UNUSED(cBytes);
}
/// Parses a BigEndian quint64 timestamp
/// @return A Unix timestamp in microseconds UTC for found message or 0 if parsing failed
quint64 LogReplayLink::_parseTimestamp(const QByteArray& bytes)
{
quint64 timestamp = qFromBigEndian(*((quint64*)(bytes.constData())));
quint64 currentTimestamp = ((quint64)QDateTime::currentMSecsSinceEpoch()) * 1000;
// Now if the parsed timestamp is in the future, it must be an old file where the timestamp was stored as
// little endian, so switch it.
if (timestamp > currentTimestamp) {
timestamp = qbswap(timestamp);
}
return timestamp;
}
/// Seeks to the beginning of the next successully parsed mavlink message in the log file.
/// @param nextMsg[output] Parsed next message that was found
/// @return A Unix timestamp in microseconds UTC for found message or 0 if parsing failed
quint64 LogReplayLink::_seekToNextMavlinkMessage(mavlink_message_t* nextMsg)
{
char nextByte;
mavlink_status_t comm;
while (_logFile.getChar(&nextByte)) { // Loop over every byte
bool messageFound = mavlink_parse_char(getMavlinkChannel(), nextByte, nextMsg, &comm);
// If we've found a message, jump back to the start of the message, grab the timestamp,
// and go back to the end of this file.
if (messageFound) {
_logFile.seek(_logFile.pos() - (nextMsg->len + MAVLINK_NUM_NON_PAYLOAD_BYTES + cbTimestamp));
QByteArray rawTime = _logFile.read(cbTimestamp);
return _parseTimestamp(rawTime);
}
}
return 0;
}
bool LogReplayLink::_loadLogFile(void)
{
QString errorMsg;
QString logFilename = _config->logFilename();
QFileInfo logFileInfo;
int logDurationSecondsTotal;
if (_logFile.isOpen()) {
errorMsg = "Attempt to load new log while log being played";
goto Error;
}
_logFile.setFileName(logFilename);
if (!_logFile.open(QFile::ReadOnly)) {
errorMsg = QString("Unable to open log file: '%1', error: %2").arg(logFilename).arg(_logFile.errorString());
goto Error;
}
logFileInfo.setFile(logFilename);
_logFileSize = logFileInfo.size();
_logTimestamped = logFilename.endsWith(".mavlink");
if (_logTimestamped) {
// Get the first timestamp from the log
// This should be a big-endian uint64.
QByteArray timestamp = _logFile.read(cbTimestamp);
quint64 startTimeUSecs = _parseTimestamp(timestamp);
// Now find the last timestamp by scanning for the last MAVLink packet and
// find the timestamp before it. To do this we start searchin a little before
// the end of the file, specifically the maximum MAVLink packet size + the
// timestamp size. This guarantees that we will hit a MAVLink packet before
// the end of the file. Unfortunately, it basically guarantees that we will
// hit more than one. This is why we have to search for a bit.
qint64 fileLoc = _logFile.size() - MAVLINK_MAX_PACKET_LEN - cbTimestamp;
_logFile.seek(fileLoc);
quint64 endTimeUSecs = startTimeUSecs; // Set a sane default for the endtime
mavlink_message_t msg;
quint64 messageTimeUSecs;
while ((messageTimeUSecs = _seekToNextMavlinkMessage(&msg)) > endTimeUSecs) {
endTimeUSecs = messageTimeUSecs;
}
if (endTimeUSecs == startTimeUSecs) {
errorMsg = QString("The log file '%1' is corrupt. No valid timestamps were found at the end of the file.").arg(logFilename);
goto Error;
}
// Remember the start and end time so we can move around this _logFile with the slider.
_logEndTimeUSecs = endTimeUSecs;
_logStartTimeUSecs = startTimeUSecs;
_logDurationUSecs = endTimeUSecs - startTimeUSecs;
_logCurrentTimeUSecs = startTimeUSecs;
// Reset our log file so when we go to read it for the first time, we start at the beginning.
_logFile.reset();
logDurationSecondsTotal = (_logDurationUSecs) / 1000000;
} else {
// Load in binary mode. In this mode, files should be have a filename postfix
// of the baud rate they were recorded at, like `test_run_115200.bin`. Then on
// playback, the datarate is equal to set to this value.
// Set baud rate if any present. Otherwise we default to 57600.
QStringList parts = logFileInfo.baseName().split("_");
_binaryBaudRate = _defaultBinaryBaudRate;
if (parts.count() > 1)
{
bool ok;
int rate = parts.last().toInt(&ok);
// 9600 baud to 100 MBit
if (ok && (rate > 9600 && rate < 100000000))
{
// Accept this as valid baudrate
_binaryBaudRate = rate;
}
}
logDurationSecondsTotal = logFileInfo.size() / (_binaryBaudRate / 10);
}
emit logFileStats(_logTimestamped, logDurationSecondsTotal, _binaryBaudRate);
return true;
Error:
if (_logFile.isOpen()) {
_logFile.close();
}
_replayError(errorMsg);
return false;
}
/// This function will read the next available log entry. It will then start
/// the _readTickTimer timer to read the new log entry at the appropriate time.
/// It might not perfectly match the timing of the log file, but it will never
/// induce a static drift into the log file replay.
void LogReplayLink::_readNextLogEntry(void)
{
// If we have a file with timestamps, try and pace this out following the time differences
// between the timestamps and the current playback speed.
if (_logTimestamped) {
// Now parse MAVLink messages, grabbing their timestamps as we go. We stop once we
// have at least 3ms until the next one.
// We track what the next execution time should be in milliseconds, which we use to set
// the next timer interrupt.
int timeToNextExecutionMSecs = 0;
// We use the `_seekToNextMavlinkMessage()` function to scan ahead for MAVLink messages. This
// is necessary because we don't know how big each MAVLink message is until we finish parsing
// one, and since we only output arrays of bytes, we need to know the size of that array.
mavlink_message_t msg;
_seekToNextMavlinkMessage(&msg);
while (timeToNextExecutionMSecs < 3) {
// Now we're sitting at the start of a MAVLink message, so read it all into a byte array for feeding to our parser.
QByteArray message = _logFile.read(msg.len + MAVLINK_NUM_NON_PAYLOAD_BYTES);
emit bytesReceived(this, message);
emit playbackPercentCompleteChanged(((float)(_logCurrentTimeUSecs - _logStartTimeUSecs) / (float)_logDurationUSecs) * 100);
// If we've reached the end of the of the file, make sure we handle that well
if (_logFile.atEnd()) {
_finishPlayback();
return;
}
// Run our parser to find the next timestamp and leave us at the start of the next MAVLink message.
_logCurrentTimeUSecs = _seekToNextMavlinkMessage(&msg);
// Calculate how long we should wait in real time until parsing this message.
// We pace ourselves relative to the start time of playback to fix any drift (initially set in play())
qint64 timeDiffMSecs = ((_logCurrentTimeUSecs - _logStartTimeUSecs) / 1000) / _replayAccelerationFactor;
quint64 desiredPacedTimeMSecs = _playbackStartTimeMSecs + timeDiffMSecs;
quint64 currentTimeMSecs = (quint64)QDateTime::currentMSecsSinceEpoch();
timeToNextExecutionMSecs = desiredPacedTimeMSecs - currentTimeMSecs;
}
// And schedule the next execution of this function.
_readTickTimer.start(timeToNextExecutionMSecs);
}
else
{
// Binary format - read at fixed rate
const int len = 100;
QByteArray chunk = _logFile.read(len);
emit bytesReceived(this, chunk);
emit playbackPercentCompleteChanged(((float)_logFile.pos() / (float)_logFileSize) * 100);
// Check if reached end of file before reading next timestamp
if (chunk.length() < len || _logFile.atEnd())
{
_finishPlayback();
return;
}
}
}
void LogReplayLink::_play(void)
{
// FIXME: With move to link I don't think this is needed any more? Except for the replay widget handling multi-uas?
LinkManager::instance()->setConnectionsSuspended(tr("Connect not allowed during Flight Data replay."));
MAVLinkProtocol::instance()->suspendLogForReplay(true);
// Make sure we aren't at the end of the file, if we are, reset to the beginning and play from there.
if (_logFile.atEnd()) {
_resetPlaybackToBeginning();
}
// Always correct the current start time such that the next message will play immediately at playback.
// We do this by subtracting the current file playback offset from now()
_playbackStartTimeMSecs = (quint64)QDateTime::currentMSecsSinceEpoch() - ((_logCurrentTimeUSecs - _logStartTimeUSecs) / 1000);
// Start timer
if (_logTimestamped) {
_readTickTimer.start(1);
} else {
// Read len bytes at a time
int len = 100;
// Calculate the number of times to read 100 bytes per second
// to guarantee the baud rate, then divide 1000 by the number of read
// operations to obtain the interval in milliseconds
int interval = 1000 / ((_binaryBaudRate / 10) / len);
_readTickTimer.start(interval / _replayAccelerationFactor);
}
emit playbackStarted();
}
void LogReplayLink::_pause(void)
{
LinkManager::instance()->setConnectionsAllowed();
MAVLinkProtocol::instance()->suspendLogForReplay(false);
_readTickTimer.stop();
emit playbackPaused();
}
void LogReplayLink::_resetPlaybackToBeginning(void)
{
if (_logFile.isOpen()) {
_logFile.reset();
}
// And since we haven't starting playback, clear the time of initial playback and the current timestamp.
_playbackStartTimeMSecs = 0;
_logCurrentTimeUSecs = _logStartTimeUSecs;
}
void LogReplayLink::movePlayhead(int percentComplete)
{
if (isPlaying()) {
qWarning() << "Should not move playhead while playing, pause first";
return;
}
if (percentComplete < 0 || percentComplete > 100) {
qWarning() << "Bad percentage value" << percentComplete;
return;
}
float floatPercentComplete = (float)percentComplete / 100.0f;
if (_logTimestamped) {
// But if we have a timestamped MAVLink log, then actually aim to hit that percentage in terms of
// time through the file.
qint64 newFilePos = (qint64)(floatPercentComplete * (float)_logFile.size());
// Now seek to the appropriate position, failing gracefully if we can't.
if (!_logFile.seek(newFilePos)) {
_replayError("Unable to seek to new position");
return;
}
// But we do align to the next MAVLink message for consistency.
mavlink_message_t dummy;
_logCurrentTimeUSecs = _seekToNextMavlinkMessage(&dummy);
// Now calculate the current file location based on time.
float newRelativeTimeUSecs = (float)(_logCurrentTimeUSecs - _logStartTimeUSecs);
// Calculate the effective baud rate of the file in bytes/s.
float baudRate = _logFile.size() / (float)_logDurationUSecs / 1e6;
// And the desired time is:
float desiredTimeUSecs = floatPercentComplete * _logDurationUSecs;
// And now jump the necessary number of bytes in the proper direction
qint64 offset = (newRelativeTimeUSecs - desiredTimeUSecs) * baudRate;
if (!_logFile.seek(_logFile.pos() + offset)) {
_replayError("Unable to seek to new position");
return;
}
// And scan until we reach the start of a MAVLink message. We make sure to record this timestamp for
// smooth jumping around the file.
_logCurrentTimeUSecs = _seekToNextMavlinkMessage(&dummy);
// Now update the UI with our actual final position.
newRelativeTimeUSecs = (float)(_logCurrentTimeUSecs - _logStartTimeUSecs);
percentComplete = (newRelativeTimeUSecs / _logDurationUSecs) * 100;
emit playbackPercentCompleteChanged(percentComplete);
} else {
// If we're working with a non-timestamped file, we just jump to that percentage of the file,
// align to the next MAVLink message and roll with it. No reason to do anything more complicated.
qint64 newFilePos = (qint64)(floatPercentComplete * (float)_logFile.size());
// Now seek to the appropriate position, failing gracefully if we can't.
if (!_logFile.seek(newFilePos)) {
_replayError("Unable to seek to new position");
return;
}
// But we do align to the next MAVLink message for consistency.
mavlink_message_t dummy;
_seekToNextMavlinkMessage(&dummy);
}
}
void LogReplayLink::_setAccelerationFactor(int factor)
{
// factor: -100: 0.01X, 0: 1.0X, 100: 100.0X
if (factor < 0) {
_replayAccelerationFactor = 0.01f;
factor -= -100;
if (factor > 0) {
_replayAccelerationFactor *= (float)factor;
}
} else if (factor > 0) {
_replayAccelerationFactor = 1.0f * (float)factor;
} else {
_replayAccelerationFactor = 1.0f;
}
// Update timer interval
if (!_logTimestamped) {
// Read len bytes at a time
int len = 100;
// Calculate the number of times to read 100 bytes per second
// to guarantee the baud rate, then divide 1000 by the number of read
// operations to obtain the interval in milliseconds
int interval = 1000 / ((_binaryBaudRate / 10) / len);
_readTickTimer.stop();
_readTickTimer.start(interval / _replayAccelerationFactor);
}
}
/// @brief Called when playback is complete
void LogReplayLink::_finishPlayback(void)
{
_pause();
emit playbackAtEnd();
}
/// @brief Called when an error occurs during playback to reset playback system state.
void LogReplayLink::_playbackError(void)
{
_pause();
_logFile.close();
emit playbackError();
}
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#ifndef LogReplayLink_H
#define LogReplayLink_H
#include "LinkInterface.h"
#include "LinkConfiguration.h"
#include "MAVLinkProtocol.h"
#include <QTimer>
#include <QFile>
class LogReplayLinkConfiguration : public LinkConfiguration
{
public:
LogReplayLinkConfiguration(const QString& name);
LogReplayLinkConfiguration(LogReplayLinkConfiguration* copy);
QString logFilename(void) { return _logFilename; }
void setLogFilename(const QString& logFilename) { _logFilename = logFilename; }
QString logFilenameShort(void);
// Virtuals from LinkConfiguration
virtual int type() { return LinkConfiguration::TypeLogReplay; }
virtual void copyFrom(LinkConfiguration* source);
virtual void loadSettings(QSettings& settings, const QString& root);
virtual void saveSettings(QSettings& settings, const QString& root);
virtual void updateSettings();
private:
static const char* _logFilenameKey;
QString _logFilename;
};
class LogReplayLink : public LinkInterface
{
Q_OBJECT
friend class LinkManager;
public:
/// @return true: log is currently playing, false: log playback is paused
bool isPlaying(void) { return _readTickTimer.isActive(); }
/// Start replay at current position
void play(void) { emit _playOnThread(); }
/// Pause replay
void pause(void) { emit _pauseOnThread(); }
/// Move the playhead to the specified percent complete
void movePlayhead(int percentComplete);
/// Sets the acceleration factor: -100: 0.01X, 0: 1.0X, 100: 100.0X
void setAccelerationFactor(int factor) { emit _setAccelerationFactorOnThread(factor); }
// Virtuals from LinkInterface
virtual QString getName(void) const { return _config->name(); }
virtual void requestReset(void){ }
virtual bool isConnected(void) const { return _connected; }
virtual qint64 getConnectionSpeed(void) const { return 100000000; }
virtual qint64 bytesAvailable(void) { return 0; }
virtual bool isLogReplay(void) { return true; }
// These are left unimplemented in order to cause linker errors which indicate incorrect usage of
// connect/disconnect on link directly. All connect/disconnect calls should be made through LinkManager.
bool connect(void);
bool disconnect(void);
public slots:
virtual void writeBytes(const char *bytes, qint64 cBytes);
signals:
void logFileStats(bool logTimestamped, int logDurationSecs, int binaryBaudRate);
void playbackStarted(void);
void playbackPaused(void);
void playbackAtEnd(void);
void playbackError(void);
void playbackPercentCompleteChanged(int percentComplete);
// Internal signals
void _playOnThread(void);
void _pauseOnThread(void);
void _setAccelerationFactorOnThread(int factor);
protected slots:
// FIXME: This should not be part of LinkInterface. It is an internal link implementation detail.
virtual void readBytes(void);
private slots:
void _readNextLogEntry(void);
void _play(void);
void _pause(void);
void _setAccelerationFactor(int factor);
private:
// Links are only created/destroyed by LinkManager so constructor/destructor is not public
LogReplayLink(LogReplayLinkConfiguration* config);
~LogReplayLink();
void _replayError(const QString& errorMsg);
quint64 _parseTimestamp(const QByteArray& bytes);
quint64 _seekToNextMavlinkMessage(mavlink_message_t* nextMsg);
bool _loadLogFile(void);
void _finishPlayback(void);
void _playbackError(void);
void _resetPlaybackToBeginning(void);
// Virtuals from LinkInterface
virtual bool _connect(void);
virtual bool _disconnect(void);
// Virtuals from QThread
virtual void run(void);
LogReplayLinkConfiguration* _config;
bool _connected;
QTimer _readTickTimer; ///< Timer which signals a read of next log record
static const char* _errorTitle; ///< Title for communicatorError signals
quint64 _logCurrentTimeUSecs; ///< The timestamp of the next message in the log file.
quint64 _logStartTimeUSecs; ///< The first timestamp in the current log file.
quint64 _logEndTimeUSecs; ///< The last timestamp in the current log file.
quint64 _logDurationUSecs;
static const int _defaultBinaryBaudRate = 57600;
int _binaryBaudRate; ///< Playback rate for binary log format
float _replayAccelerationFactor; ///< Factor to apply to playback rate
quint64 _playbackStartTimeMSecs; ///< The time when the logfile was first played back. This is used to pace out replaying the messages to fix long-term drift/skew. 0 indicates that the player hasn't initiated playback of this log file.
MAVLinkProtocol* _mavlink;
QFile _logFile;
quint64 _logFileSize;
bool _logTimestamped; ///< true: Timestamped log format, false: no timestamps
static const int cbTimestamp = sizeof(quint64);
};
#endif
......@@ -353,17 +353,12 @@ qint64 SerialLink::getConnectionSpeed() const
void SerialLink::_resetConfiguration()
{
bool somethingChanged = false;
if (_port) {
somethingChanged = _port->setBaudRate (_config->baud());
somethingChanged |= _port->setDataBits (static_cast<QSerialPort::DataBits> (_config->dataBits()));
somethingChanged |= _port->setFlowControl (static_cast<QSerialPort::FlowControl> (_config->flowControl()));
somethingChanged |= _port->setStopBits (static_cast<QSerialPort::StopBits> (_config->stopBits()));
somethingChanged |= _port->setParity (static_cast<QSerialPort::Parity> (_config->parity()));
}
if(somethingChanged) {
qCDebug(SerialLinkLog) << "Reconfiguring port";
emit updateLink(this);
_port->setBaudRate (_config->baud());
_port->setDataBits (static_cast<QSerialPort::DataBits> (_config->dataBits()));
_port->setFlowControl (static_cast<QSerialPort::FlowControl> (_config->flowControl()));
_port->setStopBits (static_cast<QSerialPort::StopBits> (_config->stopBits()));
_port->setParity (static_cast<QSerialPort::Parity> (_config->parity()));
}
}
......
......@@ -119,14 +119,12 @@ public:
void requestReset();
bool isConnected() const;
qint64 getConnectionSpeed() const;
// These are left unimplemented in order to cause linker errors which indicate incorrect usage of
// connect/disconnect on link directly. All connect/disconnect calls should be made through LinkManager.
bool connect(void);
bool disconnect(void);
signals: //[TODO] Refactor to Linkinterface
void updateLink(LinkInterface*);
public slots:
void readBytes();
......
......@@ -3414,3 +3414,14 @@ bool UAS::_containsLink(LinkInterface* link)
return false;
}
bool UAS::isLogReplay(void)
{
QList<LinkInterface*> links = getLinks();
if (links.count() == 1) {
return links[0]->isLogReplay();
} else {
return false;
}
}
......@@ -93,6 +93,7 @@ public:
float filterVoltage(float value) const;
/** @brief Get the links associated with this robot */
QList<LinkInterface*> getLinks();
bool isLogReplay(void);
Q_PROPERTY(double localX READ getLocalX WRITE setLocalX NOTIFY localXChanged)
Q_PROPERTY(double localY READ getLocalY WRITE setLocalY NOTIFY localYChanged)
......
......@@ -166,6 +166,9 @@ public:
* interface. The LinkInterface can support multiple protocols.
**/
virtual QList<LinkInterface*> getLinks() = 0;
/// @returns true: UAS is connected to log replay link
virtual bool isLogReplay(void) = 0;
/**
* @brief Get the color for this UAS
......
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include "LogReplayLinkConfigurationWidget.h"
#include "QGCFileDialog.h"
#include "QGCApplication.h"
LogReplayLinkConfigurationWidget::LogReplayLinkConfigurationWidget(LogReplayLinkConfiguration *config, QWidget *parent, Qt::WindowFlags flags) :
QWidget(parent, flags)
{
_ui.setupUi(this);
Q_ASSERT(config != NULL);
_config = config;
_ui.logFilename->setText(_config->logFilename());
connect(_ui.selectLogFileButton, &QPushButton::clicked, this, &LogReplayLinkConfigurationWidget::_selectLogFile);
}
void LogReplayLinkConfigurationWidget::_selectLogFile(bool checked)
{
Q_UNUSED(checked);
QString logFile = QGCFileDialog::getOpenFileName(this,
"Select log file to replay",
qgcApp()->mavlinkLogFilesLocation(),
"MAVLink Log Files (*.mavlink);;All Files (*)");
if (!logFile.isEmpty()) {
_ui.logFilename->setText(logFile);
_config->setLogFilename(logFile);
}
}
\ No newline at end of file
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#ifndef _LogReplayLinkConfigurationWidget_H_
#define _LogReplayLinkConfigurationWidget_H_
#include <QWidget>
#include "LogReplayLink.h"
#include "ui_LogReplayLinkConfigurationWidget.h"
class LogReplayLinkConfigurationWidget : public QWidget
{
Q_OBJECT
public:
LogReplayLinkConfigurationWidget(LogReplayLinkConfiguration* config, QWidget *parent = 0, Qt::WindowFlags flags = Qt::Sheet);
private slots:
void _selectLogFile(bool checked);
private:
Ui::LogReplayLinkConfigurationWidget _ui;
LogReplayLinkConfiguration* _config;
};
#endif
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LogReplayLinkConfigurationWidget</class>
<widget class="QWidget" name="LogReplayLinkConfigurationWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>325</width>
<height>347</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_7" stretch="0">
<item>
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Log File:</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="logFilename">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>60</height>
</size>
</property>
<property name="text">
<string/>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="selectLogFileButton">
<property name="text">
<string>Select Log File</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_8"/>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
<action name="actionDelete">
<property name="text">
<string>Delete</string>
</property>
<property name="toolTip">
<string>Delete this link</string>
</property>
<property name="statusTip">
<string>Delete this link</string>
</property>
<property name="whatsThis">
<string>Link delete button</string>
</property>
</action>
<action name="actionConnect">
<property name="text">
<string>Connect</string>
</property>
<property name="toolTip">
<string>Connect this link</string>
</property>
<property name="statusTip">
<string>Connect this link</string>
</property>
<property name="whatsThis">
<string>Connect this link</string>
</property>
</action>
<action name="actionClose">
<property name="text">
<string>Close</string>
</property>
<property name="toolTip">
<string>Close the configuration window</string>
</property>
<property name="statusTip">
<string>Close the configuration window</string>
</property>
<property name="whatsThis">
<string>Close the configuration window</string>
</property>
</action>
</widget>
<resources/>
<connections>
<connection>
<sender>actionClose</sender>
<signal>triggered()</signal>
<receiver>LogReplayLinkConfigurationWidget</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>224</x>
<y>195</y>
</hint>
</hints>
</connection>
</connections>
</ui>
......@@ -36,6 +36,7 @@ This file is part of the QGROUNDCONTROL project
#endif
#include "QGCUDPLinkConfiguration.h"
#include "QGCTCPLinkConfiguration.h"
#include "LogReplayLinkConfigurationWidget.h"
#include "QGCCommConfiguration.h"
#include "ui_QGCCommConfiguration.h"
......@@ -52,6 +53,7 @@ QGCCommConfiguration::QGCCommConfiguration(QWidget *parent, LinkConfiguration *c
#endif
_ui->typeCombo->addItem(tr("UDP"), LinkConfiguration::TypeUdp);
_ui->typeCombo->addItem(tr("TCP"), LinkConfiguration::TypeTcp);
_ui->typeCombo->addItem(tr("Log replay"), LinkConfiguration::TypeLogReplay);
#ifdef QT_DEBUG
_ui->typeCombo->addItem(tr("Mock"), LinkConfiguration::TypeMock);
#endif
......@@ -140,6 +142,13 @@ void QGCCommConfiguration::_loadTypeConfigWidget(int type)
_ui->typeCombo->setCurrentIndex(_ui->typeCombo->findData(LinkConfiguration::TypeTcp));
}
break;
case LinkConfiguration::TypeLogReplay: {
QWidget* conf = new LogReplayLinkConfigurationWidget((LogReplayLinkConfiguration*)_config, this);
_ui->linkScrollArea->setWidget(conf);
_ui->linkGroupBox->setTitle("Log Replay");
_ui->typeCombo->setCurrentIndex(_ui->typeCombo->findData(LinkConfiguration::TypeLogReplay));
}
break;
#ifdef QT_DEBUG
case LinkConfiguration::TypeMock: {
_ui->linkScrollArea->setWidget(NULL);
......
......@@ -160,6 +160,13 @@ void QGCLinkConfiguration::_fixUnnamed(LinkConfiguration* config)
}
}
break;
case LinkConfiguration::TypeLogReplay: {
LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
if(tconfig) {
config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
}
}
break;
#ifdef QT_DEBUG
case LinkConfiguration::TypeMock:
config->setName(
......
This diff is collapsed.
......@@ -6,7 +6,7 @@
#include "MAVLinkProtocol.h"
#include "LinkInterface.h"
#include "MockLink.h"
#include "LogReplayLink.h"
namespace Ui
{
......@@ -27,97 +27,29 @@ class QGCMAVLinkLogPlayer : public QWidget
public:
explicit QGCMAVLinkLogPlayer(MAVLinkProtocol* mavlink, QWidget *parent = 0);
~QGCMAVLinkLogPlayer();
bool isPlayingLogFile()
{
return isPlaying;
}
bool isLogFileSelected()
{
return logFile.isOpen();
}
public slots:
/** @brief Toggle between play and pause */
void playPauseToggle();
/** @brief Replay the logfile */
void play();
/** @brief Pause the log player. */
void pause();
/** @brief Reset the internal log player state, including the UI */
void reset();
/** @brief Load log file */
bool loadLogFile(const QString& file);
/** @brief Jump to a position in the logfile */
void jumpToSliderVal(int slidervalue);
/** @brief The logging mainloop */
void logLoop();
/** @brief Set acceleration factor in percent */
void setAccelerationFactorInt(int factor);
signals:
/** @brief Send ready bytes */
void bytesReady(LinkInterface* link, const QByteArray& bytes);
void logFileEndReached();
protected:
quint64 playbackStartTime; ///< The time when the logfile was first played back. This is used to pace out replaying the messages to fix long-term drift/skew. 0 indicates that the player hasn't initiated playback of this log file. In units of milliseconds since epoch UTC.
quint64 logCurrentTime; ///< The timestamp of the next message in the log file. In units of microseconds since epoch UTC.
quint64 logStartTime; ///< The first timestamp in the current log file. In units of microseconds since epoch UTC.
quint64 logEndTime; ///< The last timestamp in the current log file. In units of microseconds since epoch UTC.
float accelerationFactor;
MAVLinkProtocol* mavlink;
MockLink* logLink;
QFile logFile;
QTimer loopTimer;
int loopCounter;
bool mavlinkLogFormat; ///< If the logfile is stored in the timestamped MAVLink log format
int binaryBaudRate;
static const int defaultBinaryBaudRate = 57600;
bool isPlaying;
unsigned int currPacketCount;
static const int packetLen = MAVLINK_MAX_PACKET_LEN;
static const int timeLen = sizeof(quint64);
void changeEvent(QEvent *e);
private slots:
void _selectLogFileForPlayback(void);
void _playPauseToggle(void);
void _pause(void);
void _setPlayheadFromSlider(int value);
void _setAccelerationFromSlider(int value);
void _logFileStats(bool logTimestamped, int logDurationSeconds, int binaryBaudRate);
void _playbackStarted(void);
void _playbackPaused(void);
void _playbackPercentCompleteChanged(int percentComplete);
void _playbackError(void);
void _replayLinkDisconnected(void);
private:
Ui::QGCMAVLinkLogPlayer *ui;
virtual void paintEvent(QPaintEvent *);
/** @brief Parse out a quint64 timestamp in microseconds in the proper endianness. */
quint64 parseTimestamp(const QByteArray &data);
/**
* This function parses out the next MAVLink message and its corresponding timestamp.
*
* It makes no assumptions about where in the file we currently are. It leaves the file right
* at the beginning of the successfully parsed message. Note that this function will not attempt to
* correct for any MAVLink parsing failures, so it always returns the next successfully-parsed
* message.
*
* @param msg[output] Where the final parsed message output will go.
* @return A Unix timestamp in microseconds UTC or 0 if parsing failed
*/
quint64 findNextMavlinkMessage(mavlink_message_t *msg);
/**
* Updates the QSlider UI to be at the given percentage.
* @param percent A percentage value between 0.0% and 100.0%.
*/
void updatePositionSliderUi(float percent);
void _finishPlayback(void);
QString _secondsToHMS(int seconds);
void _enablePlaybackControls(bool enabled);
/**
* Jumps to a new position in the current playback file as a percentage.
* @param percentage The position of the file to jump to as a percentage.
* @return True if the new file position was successfully jumped to, false otherwise
*/
bool jumpToPlaybackLocation(float percentage);
LogReplayLink* _replayLink;
int _logDurationSeconds;
void _finishPlayback(void);
void _playbackError(void);
Ui::QGCMAVLinkLogPlayer* _ui;
};
#endif // QGCMAVLINKLOGPLAYER_H
#endif
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment