LinechartWidget.cc 36 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/*=====================================================================

PIXHAWK Micro Air Vehicle Flying Robotics Toolkit

(c) 2009, 2010 PIXHAWK PROJECT  <http://pixhawk.ethz.ch>

This file is part of the PIXHAWK project

    PIXHAWK 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.

    PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Line chart plot widget
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QDebug>
#include <QWidget>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QComboBox>
#include <QToolButton>
38
#include <QSizePolicy>
pixhawk's avatar
pixhawk committed
39 40 41 42 43 44 45
#include <QScrollBar>
#include <QLabel>
#include <QMenu>
#include <QSpinBox>
#include <QColor>
#include <QPalette>
#include <QFileDialog>
46 47
#include <QDesktopServices>
#include <QMessageBox>
pixhawk's avatar
pixhawk committed
48 49 50 51

#include "LinechartWidget.h"
#include "LinechartPlot.h"
#include "LogCompressor.h"
lm's avatar
lm committed
52
#include "MainWindow.h"
lm's avatar
lm committed
53
#include "QGC.h"
pixhawk's avatar
pixhawk committed
54 55 56
#include "MG.h"


57
LinechartWidget::LinechartWidget(int systemid, QWidget *parent) : QWidget(parent),
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    sysid(systemid),
    activePlot(NULL),
    curvesLock(new QReadWriteLock()),
    plotWindowLock(),
    curveListIndex(0),
    curveListCounter(0),
    listedCurves(new QList<QString>()),
    curveLabels(new QMap<QString, QLabel*>()),
    curveMeans(new QMap<QString, QLabel*>()),
    curveMedians(new QMap<QString, QLabel*>()),
    curveVariances(new QMap<QString, QLabel*>()),
    curveMenu(new QMenu(this)),
    logFile(new QFile()),
    logindex(1),
    logging(false),
    logStartTime(0),
lm's avatar
lm committed
74 75
    updateTimer(new QTimer()),
    selectedMAV(-1)
pixhawk's avatar
pixhawk committed
76 77 78
{
    // Add elements defined in Qt Designer
    ui.setupUi(this);
79
    this->setMinimumSize(200, 150);
pixhawk's avatar
pixhawk committed
80 81 82 83

    // Add and customize curve list elements (left side)
    curvesWidget = new QWidget(ui.curveListWidget);
    ui.curveListWidget->setWidget(curvesWidget);
84
    curvesWidgetLayout = new QGridLayout(curvesWidget);
pixhawk's avatar
pixhawk committed
85 86
    curvesWidgetLayout->setMargin(2);
    curvesWidgetLayout->setSpacing(4);
87
    //curvesWidgetLayout->setSizeConstraint(QSizePolicy::Expanding);
88
    curvesWidgetLayout->setAlignment(Qt::AlignTop);
89 90 91 92 93 94 95

    curvesWidgetLayout->setColumnStretch(0, 0);
    curvesWidgetLayout->setColumnStretch(1, 0);
    curvesWidgetLayout->setColumnStretch(2, 80);
    curvesWidgetLayout->setColumnStretch(3, 50);
    curvesWidgetLayout->setColumnStretch(4, 50);
    curvesWidgetLayout->setColumnStretch(5, 50);
96 97
//    horizontalLayout->setColumnStretch(median, 50);
    curvesWidgetLayout->setColumnStretch(6, 50);
98

pixhawk's avatar
pixhawk committed
99 100
    curvesWidget->setLayout(curvesWidgetLayout);

101 102 103 104 105 106
    // Create curve list headings
    QLabel* label;
    QLabel* value;
    QLabel* mean;
    QLabel* variance;

107 108
    connect(ui.recolorButton, SIGNAL(clicked()), this, SLOT(recolor()));
    connect(ui.shortNameCheckBox, SIGNAL(clicked(bool)), this, SLOT(setShortNames(bool)));
109

110 111
    int labelRow = curvesWidgetLayout->rowCount();

112 113 114
    selectAllCheckBox = new QCheckBox("", this);
    connect(selectAllCheckBox, SIGNAL(clicked(bool)), this, SLOT(selectAllCurves(bool)));
    curvesWidgetLayout->addWidget(selectAllCheckBox, labelRow, 0, 1, 2);
115 116

    label = new QLabel(this);
117
    label->setText("Name");
118
    curvesWidgetLayout->addWidget(label, labelRow, 2);
119 120

    // Value
121
    value = new QLabel(this);
122
    value->setText("Val");
123
    curvesWidgetLayout->addWidget(value, labelRow, 3);
124

125
    // Unit
126
    //curvesWidgetLayout->addWidget(new QLabel(tr("Unit")), labelRow, 4);
127

128
    // Mean
129
    mean = new QLabel(this);
130
    mean->setText("Mean");
131
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
132 133

    // Variance
134
    variance = new QLabel(this);
135
    variance->setText("Variance");
136
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
137

pixhawk's avatar
pixhawk committed
138 139
    // Create the layout
    createLayout();
140

pixhawk's avatar
pixhawk committed
141
    // Add the last actions
142 143
    //connect(this, SIGNAL(plotWindowPositionUpdated(int)), scrollbar, SLOT(setValue(int)));
    //connect(scrollbar, SIGNAL(sliderMoved(int)), this, SLOT(setPlotWindowPosition(int)));
144

LM's avatar
LM committed
145
    updateTimer->setInterval(updateInterval);
146
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(refresh()));
147
    connect(ui.uasSelectionBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectActiveSystem(int)));
148
    readSettings();
pixhawk's avatar
pixhawk committed
149 150
}

151 152 153
LinechartWidget::~LinechartWidget()
{
    writeSettings();
pixhawk's avatar
pixhawk committed
154
    stopLogging();
155 156
    if (activePlot) delete activePlot;
    activePlot = NULL;
pixhawk's avatar
pixhawk committed
157 158 159 160
    delete listedCurves;
    listedCurves = NULL;
}

161 162 163 164 165 166 167 168 169 170 171
void LinechartWidget::selectActiveSystem(int mav)
{
    // -1: Unitialized, 0: all
    if (mav != selectedMAV && (selectedMAV != -1))
    {
        // Delete all curves
        // FIXME
    }
    selectedMAV = mav;
}

172 173 174
void LinechartWidget::selectAllCurves(bool all)
{
    QMap<QString, QLabel*>::iterator i;
175
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i) {
176 177 178 179
        activePlot->setVisible(i.key(), all);
    }
}

180 181 182 183
void LinechartWidget::writeSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
184 185
    bool enforceGT = (!autoGroundTimeSet && timeButton->isChecked()) ? true : false;
    if (timeButton) settings.setValue("ENFORCE_GROUNDTIME", enforceGT);
186
    if (ui.showUnitsCheckBox) settings.setValue("SHOW_UNITS", ui.showUnitsCheckBox->isChecked());
187
    if (ui.shortNameCheckBox) settings.setValue("SHORT_NAMES", ui.shortNameCheckBox->isChecked());
188 189 190 191 192 193 194 195 196
    settings.endGroup();
    settings.sync();
}

void LinechartWidget::readSettings()
{
    QSettings settings;
    settings.sync();
    settings.beginGroup("LINECHART");
197
    if (activePlot) {
198 199
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
        activePlot->enforceGroundTime(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
200
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
201
        //userGroundTimeSet = settings.value("USER_GROUNDTIME", timeButton->isChecked()).toBool();
202
    }
203
    if (ui.showUnitsCheckBox) ui.showUnitsCheckBox->setChecked(settings.value("SHOW_UNITS", ui.showUnitsCheckBox->isChecked()).toBool());
204
    if (ui.shortNameCheckBox) ui.shortNameCheckBox->setChecked(settings.value("SHORT_NAMES", ui.shortNameCheckBox->isChecked()).toBool());
205 206 207
    settings.endGroup();
}

pixhawk's avatar
pixhawk committed
208 209 210 211 212 213 214 215 216 217 218 219
void LinechartWidget::createLayout()
{
    // Create actions
    createActions();

    // Setup the plot group box area layout
    QGridLayout* layout = new QGridLayout(ui.diagramGroupBox);
    mainLayout = layout;
    layout->setSpacing(4);
    layout->setMargin(2);

    // Create plot container widget
220 221 222
    activePlot = new LinechartPlot(this, sysid);
    // Activate automatic scrolling
    activePlot->setAutoScroll(true);
pixhawk's avatar
pixhawk committed
223 224 225 226 227

    // TODO Proper Initialization needed
    //    activePlot = getPlot(0);
    //    plotContainer->setPlot(activePlot);

228
    layout->addWidget(activePlot, 0, 0, 1, 6);
pixhawk's avatar
pixhawk committed
229
    layout->setRowStretch(0, 10);
lm's avatar
lm committed
230
    layout->setRowStretch(1, 1);
pixhawk's avatar
pixhawk committed
231 232 233 234 235

    // Linear scaling button
    scalingLinearButton = createButton(this);
    scalingLinearButton->setDefaultAction(setScalingLinear);
    scalingLinearButton->setCheckable(true);
236 237
    scalingLinearButton->setToolTip(tr("Set linear scale for Y axis"));
    scalingLinearButton->setWhatsThis(tr("Set linear scale for Y axis"));
pixhawk's avatar
pixhawk committed
238 239 240 241 242 243 244
    layout->addWidget(scalingLinearButton, 1, 0);
    layout->setColumnStretch(0, 0);

    // Logarithmic scaling button
    scalingLogButton = createButton(this);
    scalingLogButton->setDefaultAction(setScalingLogarithmic);
    scalingLogButton->setCheckable(true);
245 246
    scalingLogButton->setToolTip(tr("Set logarithmic scale for Y axis"));
    scalingLogButton->setWhatsThis(tr("Set logarithmic scale for Y axis"));
pixhawk's avatar
pixhawk committed
247 248 249 250 251
    layout->addWidget(scalingLogButton, 1, 1);
    layout->setColumnStretch(1, 0);

    // Averaging spin box
    averageSpinBox = new QSpinBox(this);
252 253
    averageSpinBox->setToolTip(tr("Sliding window size to calculate mean and variance"));
    averageSpinBox->setWhatsThis(tr("Sliding window size to calculate mean and variance"));
pixhawk's avatar
pixhawk committed
254
    averageSpinBox->setMinimum(2);
255 256
    averageSpinBox->setValue(200);
    setAverageWindow(200);
257
    averageSpinBox->setMaximum(9999);
pixhawk's avatar
pixhawk committed
258 259 260 261 262 263
    layout->addWidget(averageSpinBox, 1, 2);
    layout->setColumnStretch(2, 0);
    connect(averageSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setAverageWindow(int)));

    // Log Button
    logButton = new QToolButton(this);
264 265
    logButton->setToolTip(tr("Start to log curve data into a CSV or TXT file"));
    logButton->setWhatsThis(tr("Start to log curve data into a CSV or TXT file"));
pixhawk's avatar
pixhawk committed
266 267 268 269 270
    logButton->setText(tr("Start Logging"));
    layout->addWidget(logButton, 1, 3);
    layout->setColumnStretch(3, 0);
    connect(logButton, SIGNAL(clicked()), this, SLOT(startLogging()));

271
    // Ground time button
272
    timeButton = new QCheckBox(this);
273
    timeButton->setText(tr("Ground Time"));
274 275
    timeButton->setToolTip(tr("Overwrite timestamp of data from vehicle with ground receive time. Helps if the plots are not visible because of missing or invalid onboard time."));
    timeButton->setWhatsThis(tr("Overwrite timestamp of data from vehicle with ground receive time. Helps if the plots are not visible because of missing or invalid onboard time."));
276 277 278
    layout->addWidget(timeButton, 1, 4);
    layout->setColumnStretch(4, 0);
    connect(timeButton, SIGNAL(clicked(bool)), activePlot, SLOT(enforceGroundTime(bool)));
279
    connect(timeButton, SIGNAL(clicked()), this, SLOT(writeSettings()));
280

281 282 283
    // Initialize the "Show units" checkbox. This is configured in the .ui file, so all
    // we do here is attach the clicked() signal.
    connect(ui.showUnitsCheckBox, SIGNAL(clicked()), this, SLOT(writeSettings()));
pixhawk's avatar
pixhawk committed
284 285

    ui.diagramGroupBox->setLayout(layout);
286 287 288 289 290 291 292 293

    // Add actions
    averageSpinBox->setValue(activePlot->getAverageWindow());

    // Connect notifications from the user interface to the plot
    connect(this, SIGNAL(curveRemoved(QString)), activePlot, SLOT(hideCurve(QString)));

    // Update scrollbar when plot window changes (via translator method setPlotWindowPosition()
294 295
//    connect(activePlot, SIGNAL(windowPositionChanged(quint64)), this, SLOT(setPlotWindowPosition(quint64)));
    connect(activePlot, SIGNAL(curveRemoved(QString)), this, SLOT(removeCurve(QString)));
296 297 298 299 300 301 302

    // Update plot when scrollbar is moved (via translator method setPlotWindowPosition()
    connect(this, SIGNAL(plotWindowPositionUpdated(quint64)), activePlot, SLOT(setWindowPosition(quint64)));

    // Set scaling
    connect(scalingLinearButton, SIGNAL(clicked()), activePlot, SLOT(setLinearScaling()));
    connect(scalingLogButton, SIGNAL(clicked()), activePlot, SLOT(setLogarithmicScaling()));
pixhawk's avatar
pixhawk committed
303 304
}

305
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, qint8 value, quint64 usec)
306
{
307 308
    appendData(uasId, curve, unit, static_cast<qint64>(value), usec);
}
309

310 311 312 313
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, quint8 value, quint64 usec)
{
    appendData(uasId, curve, unit, static_cast<quint64>(value), usec);
}
314

315 316 317
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, qint16 value, quint64 usec)
{
    appendData(uasId, curve, unit, static_cast<qint64>(value), usec);
318 319
}

320 321 322 323
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, quint16 value, quint64 usec)
{
    appendData(uasId, curve, unit, static_cast<quint64>(value), usec);
}
324

325 326 327 328 329 330 331 332 333 334 335
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, qint32 value, quint64 usec)
{
    appendData(uasId, curve, unit, static_cast<qint64>(value), usec);
}

void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, quint32 value, quint64 usec)
{
    appendData(uasId, curve, unit, static_cast<quint64>(value), usec);
}

void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, qint64 value, quint64 usec)
336
{
lm's avatar
lm committed
337 338
    if ((selectedMAV == -1 && isVisible()) || (selectedMAV == uasId && isVisible()))
    {
339 340 341 342 343
        // Order matters here, first append to plot, then update curve list
        activePlot->appendData(curve+unit, usec, value);
        // Store data
        QLabel* label = curveLabels->value(curve+unit, NULL);
        // Make sure the curve will be created if it does not yet exist
lm's avatar
lm committed
344 345
        if(!label)
        {
346
            intData.insert(curve+unit, 0);
347 348
            addCurve(curve, unit);
        }
349 350 351

        // Add int data
        intData.insert(curve+unit, value);
352 353
    }

354 355 356 357 358 359 360 361 362 363 364 365
    if (lastTimestamp == 0 && usec != 0)
    {
        lastTimestamp = usec;
    } else if (usec != 0) {
        // Difference larger than 5 secs, enforce ground time
        if (abs((int)((qint64)usec - (quint64)lastTimestamp)) > 5000)
        {
            autoGroundTimeSet = true;
            if (activePlot) activePlot->groundTime();
        }
    }

366
    // Log data
lm's avatar
lm committed
367 368 369 370
    if (logging)
    {
        if (activePlot->isVisible(curve+unit))
        {
371
            if (usec == 0 || autoGroundTimeSet) usec = QGC::groundTimeMilliseconds();
372 373 374 375
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;

376
            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value) + "\n").toLatin1());
377 378 379 380
        }
    }
}

381
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, quint64 value, quint64 usec)
lm's avatar
lm committed
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
{
    if ((selectedMAV == -1 && isVisible()) || (selectedMAV == uasId && isVisible()))
    {
        // Order matters here, first append to plot, then update curve list
        activePlot->appendData(curve+unit, usec, value);
        // Store data
        QLabel* label = curveLabels->value(curve+unit, NULL);
        // Make sure the curve will be created if it does not yet exist
        if(!label)
        {
            intData.insert(curve+unit, 0);
            addCurve(curve, unit);
        }

        // Add int data
        intData.insert(curve+unit, value);
    }

400 401 402 403 404 405 406 407 408 409 410 411
    if (lastTimestamp == 0 && usec != 0)
    {
        lastTimestamp = usec;
    } else if (usec != 0) {
        // Difference larger than 5 secs, enforce ground time
        if (abs((int)((qint64)usec - (quint64)lastTimestamp)) > 5000)
        {
            autoGroundTimeSet = true;
            if (activePlot) activePlot->groundTime();
        }
    }

lm's avatar
lm committed
412 413 414 415 416
    // Log data
    if (logging)
    {
        if (activePlot->isVisible(curve+unit))
        {
417
            if (usec == 0 || autoGroundTimeSet) usec = QGC::groundTimeMilliseconds();
lm's avatar
lm committed
418 419 420 421 422 423 424 425 426 427
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;

            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value) + "\n").toLatin1());
            logFile->flush();
        }
    }
}

428
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, double value, quint64 usec)
lm's avatar
lm committed
429 430 431
{
    if ((selectedMAV == -1 && isVisible()) || (selectedMAV == uasId && isVisible()))
    {
432
        // Order matters here, first append to plot, then update curve list
433
        activePlot->appendData(curve+unit, usec, value);
434
        // Store data
435
        QLabel* label = curveLabels->value(curve+unit, NULL);
436
        // Make sure the curve will be created if it does not yet exist
lm's avatar
lm committed
437 438
        if(!label)
        {
439
            //qDebug() << "ADDING CURVE IN APPENDDATE DOUBLE";
440
            addCurve(curve, unit);
441
        }
pixhawk's avatar
pixhawk committed
442 443
    }

444 445 446 447 448 449 450 451 452 453 454 455
    if (lastTimestamp == 0 && usec != 0)
    {
        lastTimestamp = usec;
    } else if (usec != 0) {
        // Difference larger than 1 sec, enforce ground time
        if (abs((int)((qint64)usec - (quint64)lastTimestamp)) > 1000)
        {
            autoGroundTimeSet = true;
            if (activePlot) activePlot->groundTime();
        }
    }

pixhawk's avatar
pixhawk committed
456
    // Log data
lm's avatar
lm committed
457 458 459 460
    if (logging)
    {
        if (activePlot->isVisible(curve+unit))
        {
461
            if (usec == 0 || autoGroundTimeSet) usec = QGC::groundTimeMilliseconds();
462 463 464
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;
lm's avatar
lm committed
465

466
            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value,'g',18) + "\n").toLatin1());
pixhawk's avatar
pixhawk committed
467 468 469 470 471
            logFile->flush();
        }
    }
}

472 473
void LinechartWidget::refresh()
{
LM's avatar
LM committed
474
    setUpdatesEnabled(false);
475
    QString str;
476
    // Value
477
    QMap<QString, QLabel*>::iterator i;
478 479
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i) {
        if (intData.contains(i.key())) {
lm's avatar
lm committed
480
            str.sprintf("% 11i", intData.value(i.key()));
481
        } else {
lm's avatar
lm committed
482 483
            double val = activePlot->getCurrentValue(i.key());
            int intval = static_cast<int>(val);
484
            if (intval >= 100000 || intval <= -100000) {
lm's avatar
lm committed
485
                str.sprintf("% 11i", intval);
486
            } else if (intval >= 10000 || intval <= -10000) {
lm's avatar
lm committed
487
                str.sprintf("% 11.2f", val);
488
            } else if (intval >= 1000 || intval <= -1000) {
lm's avatar
lm committed
489
                str.sprintf("% 11.4f", val);
490
            } else {
lm's avatar
lm committed
491 492
                str.sprintf("% 11.6f", val);
            }
493
        }
494 495 496 497 498
        // Value
        i.value()->setText(str);
    }
    // Mean
    QMap<QString, QLabel*>::iterator j;
499
    for (j = curveMeans->begin(); j != curveMeans->end(); ++j) {
500
        double val = activePlot->getMean(j.key());
lm's avatar
lm committed
501
        int intval = static_cast<int>(val);
502
        if (intval >= 100000 || intval <= -100000) {
lm's avatar
lm committed
503
            str.sprintf("% 11i", intval);
504
        } else if (intval >= 10000 || intval <= -10000) {
505
            str.sprintf("% 11.2f", val);
506
        } else if (intval >= 1000 || intval <= -1000) {
lm's avatar
lm committed
507
            str.sprintf("% 11.4f", val);
508
        } else {
509 510
            str.sprintf("% 11.6f", val);
        }
511 512
        j.value()->setText(str);
    }
513 514 515 516 517 518 519
//    QMap<QString, QLabel*>::iterator k;
//    for (k = curveMedians->begin(); k != curveMedians->end(); ++k)
//    {
//        // Median
//        str.sprintf("%+.2f", activePlot->getMedian(k.key()));
//        k.value()->setText(str);
//    }
520
    QMap<QString, QLabel*>::iterator l;
521 522 523 524 525
    for (l = curveVariances->begin(); l != curveVariances->end(); ++l) {
        // Variance
        str.sprintf("% 8.3e", activePlot->getVariance(l.key()));
        l.value()->setText(str);
    }
LM's avatar
LM committed
526
    setUpdatesEnabled(true);
527 528
}

pixhawk's avatar
pixhawk committed
529 530 531 532

void LinechartWidget::startLogging()
{
    // Store reference to file
533 534
    // Append correct file ending if needed
    bool abort = false;
lm's avatar
lm committed
535 536

    // Check if any curve is enabled
537
    if (!activePlot->anyCurveVisible()) {
lm's avatar
lm committed
538 539 540 541 542 543 544 545 546 547 548
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText("No curves selected for logging.");
        msgBox.setInformativeText("Please check all curves you want to log. Currently no data would be logged, aborting the logging.");
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
        return;
    }

    // Let user select the log file name
549
    //QDate date(QDate::currentDate());
lm's avatar
lm committed
550
    // QString("./pixhawk-log-" + date.toString("yyyy-MM-dd") + "-" + QString::number(logindex) + ".log")
lm's avatar
lm committed
551
    QString fileName = QFileDialog::getSaveFileName(this, tr("Specify log file name"), QDesktopServices::storageLocation(QDesktopServices::DesktopLocation), tr("Logfile (*.csv *.txt);;"));
lm's avatar
lm committed
552

553
    while (!(fileName.endsWith(".txt") || fileName.endsWith(".csv")) && !abort && fileName != "") {
554 555 556 557 558 559
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText("Unsuitable file extension for logfile");
        msgBox.setInformativeText("Please choose .txt or .csv as file extension. Click OK to change the file extension, cancel to not start logging.");
        msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Ok);
560 561
        if(msgBox.exec() != QMessageBox::Ok)
        {
562 563 564
            abort = true;
            break;
        }
565
        fileName = QFileDialog::getSaveFileName(this, tr("Specify log file name"), QDesktopServices::storageLocation(QDesktopServices::DesktopLocation), tr("Logfile (*.txt *.csv);;"));
pixhawk's avatar
pixhawk committed
566
    }
567

568 569
    qDebug() << "SAVE FILE" << fileName;

570
    // Check if the user did not abort the file save dialog
571
    if (!abort && fileName != "") {
572
        logFile = new QFile(fileName);
573
        if (logFile->open(QIODevice::WriteOnly | QIODevice::Text)) {
574
            logging = true;
575 576
            logStartTime = 0;
            curvesWidget->setEnabled(false);
577 578 579 580 581
            logindex++;
            logButton->setText(tr("Stop logging"));
            disconnect(logButton, SIGNAL(clicked()), this, SLOT(startLogging()));
            connect(logButton, SIGNAL(clicked()), this, SLOT(stopLogging()));
        }
pixhawk's avatar
pixhawk committed
582 583 584 585 586 587
    }
}

void LinechartWidget::stopLogging()
{
    logging = false;
588
    curvesWidget->setEnabled(true);
589
    if (logFile->isOpen()) {
pixhawk's avatar
pixhawk committed
590 591 592
        logFile->flush();
        logFile->close();
        // Postprocess log file
593
        compressor = new LogCompressor(logFile->fileName(), logFile->fileName());
594
        connect(compressor, SIGNAL(finishedFile(QString)), this, SIGNAL(logfileWritten(QString)));
lm's avatar
lm committed
595
        connect(compressor, SIGNAL(logProcessingStatusChanged(QString)), MainWindow::instance(), SLOT(showStatusMessage(QString)));
596 597 598 599

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Question);
        msgBox.setText(tr("Starting Log Compression"));
600
        msgBox.setInformativeText(tr("Should empty fields (e.g. due to packet drops) be filled with the previous value of the same variable (zero order hold)?"));
601 602 603 604 605 606 607 608 609 610 611 612 613 614
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgBox.setDefaultButton(QMessageBox::No);
        int ret = msgBox.exec();
        bool fill;
        if (ret == QMessageBox::Yes)
        {
            fill = true;
        }
        else
        {
            fill = false;
        }

        compressor->startCompression(fill);
pixhawk's avatar
pixhawk committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    }
    logButton->setText(tr("Start logging"));
    disconnect(logButton, SIGNAL(clicked()), this, SLOT(stopLogging()));
    connect(logButton, SIGNAL(clicked()), this, SLOT(startLogging()));
}

/**
 * The average window size defines the width of the sliding average
 * filter. It also defines the width of the sliding median filter.
 *
 * @param windowSize with (in values) of the sliding average/median filter. Minimum is 2
 */
void LinechartWidget::setAverageWindow(int windowSize)
{
    if (windowSize > 1) activePlot->setAverageWindow(windowSize);
}

void LinechartWidget::createActions()
{
    setScalingLogarithmic = new QAction("LOG", this);
    setScalingLinear = new QAction("LIN", this);
}

/**
 * @brief Add a curve to the curve list
 *
 * @param curve The id-string of the curve
 * @see removeCurve()
 **/
644
void LinechartWidget::addCurve(const QString& curve, const QString& unit)
pixhawk's avatar
pixhawk committed
645
{
646
    LinechartPlot* plot = activePlot;
647
//    QHBoxLayout *horizontalLayout;
pixhawk's avatar
pixhawk committed
648 649 650
    QCheckBox *checkBox;
    QLabel* label;
    QLabel* value;
651
    QLabel* unitLabel;
pixhawk's avatar
pixhawk committed
652
    QLabel* mean;
653
    QLabel* variance;
pixhawk's avatar
pixhawk committed
654

655 656
    curveNames.insert(curve+unit, curve);

657 658 659
    int labelRow = curvesWidgetLayout->rowCount();

    checkBox = new QCheckBox(this);
pixhawk's avatar
pixhawk committed
660
    checkBox->setCheckable(true);
661
    checkBox->setObjectName(curve+unit);
662 663
    checkBox->setToolTip(tr("Enable the curve in the graph window"));
    checkBox->setWhatsThis(tr("Enable the curve in the graph window"));
pixhawk's avatar
pixhawk committed
664

665
    curvesWidgetLayout->addWidget(checkBox, labelRow, 0);
pixhawk's avatar
pixhawk committed
666

667
    QWidget* colorIcon = new QWidget(this);
668
    colorIcons.insert(curve+unit, colorIcon);
pixhawk's avatar
pixhawk committed
669 670 671
    colorIcon->setMinimumSize(QSize(5, 14));
    colorIcon->setMaximumSize(4, 14);

672
    curvesWidgetLayout->addWidget(colorIcon, labelRow, 1);
pixhawk's avatar
pixhawk committed
673

674 675
    label = new QLabel(this);
    curvesWidgetLayout->addWidget(label, labelRow, 2);
pixhawk's avatar
pixhawk committed
676 677

    //checkBox->setText(QString());
678
    label->setText(getCurveName(curve+unit, ui.shortNameCheckBox->isChecked()));
679 680 681 682 683
    QColor color(Qt::gray);// = plot->getColorForCurve(curve+unit);
    QString colorstyle;
    colorstyle = colorstyle.sprintf("QWidget { background-color: #%X%X%X; }", color.red(), color.green(), color.blue());
    colorIcon->setStyleSheet(colorstyle);
    colorIcon->setAutoFillBackground(true);
pixhawk's avatar
pixhawk committed
684

685 686 687
    // Label
    curveNameLabels.insert(curve+unit, label);

pixhawk's avatar
pixhawk committed
688
    // Value
689
    value = new QLabel(this);
pixhawk's avatar
pixhawk committed
690
    value->setNum(0.00);
691
    value->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
692 693
    value->setToolTip(tr("Current value of %1 in %2 units").arg(curve, unit));
    value->setWhatsThis(tr("Current value of %1 in %2 units").arg(curve, unit));
694
    curveLabels->insert(curve+unit, value);
695
    curvesWidgetLayout->addWidget(value, labelRow, 3);
pixhawk's avatar
pixhawk committed
696

697 698 699 700
    // Unit
    unitLabel = new QLabel(this);
    unitLabel->setText(unit);
    unitLabel->setStyleSheet(QString("QLabel {color: %1;}").arg("#AAAAAA"));
701
    //qDebug() << "UNIT" << unit;
702 703 704
    unitLabel->setToolTip(tr("Unit of ") + curve);
    unitLabel->setWhatsThis(tr("Unit of ") + curve);
    curvesWidgetLayout->addWidget(unitLabel, labelRow, 4);
705 706
    unitLabel->setVisible(ui.showUnitsCheckBox->isChecked());
    connect(ui.showUnitsCheckBox, SIGNAL(clicked(bool)), unitLabel, SLOT(setVisible(bool)));
707

pixhawk's avatar
pixhawk committed
708
    // Mean
709
    mean = new QLabel(this);
pixhawk's avatar
pixhawk committed
710
    mean->setNum(0.00);
lm's avatar
lm committed
711
    mean->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
712 713
    mean->setToolTip(tr("Arithmetic mean of %1 in %2 units").arg(curve, unit));
    mean->setWhatsThis(tr("Arithmetic mean of %1 in %2 units").arg(curve, unit));
714 715
    curveMeans->insert(curve+unit, mean);
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
pixhawk's avatar
pixhawk committed
716

717 718 719 720 721
//    // Median
//    median = new QLabel(form);
//    value->setNum(0.00);
//    curveMedians->insert(curve, median);
//    horizontalLayout->addWidget(median);
pixhawk's avatar
pixhawk committed
722

723
    // Variance
724
    variance = new QLabel(this);
725
    variance->setNum(0.00);
lm's avatar
lm committed
726
    variance->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
727 728
    variance->setToolTip(tr("Variance of %1 in (%2)^2 units").arg(curve, unit));
    variance->setWhatsThis(tr("Variance of %1 in (%2)^2 units").arg(curve, unit));
729 730
    curveVariances->insert(curve+unit, variance);
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
731

pixhawk's avatar
pixhawk committed
732 733 734 735 736 737 738 739 740 741 742
    /* Color picker
    QColor color = QColorDialog::getColor(Qt::green, this);
         if (color.isValid()) {
             colorLabel->setText(color.name());
             colorLabel->setPalette(QPalette(color));
             colorLabel->setAutoFillBackground(true);
         }
        */

    // Set stretch factors so that the label gets the whole space

743 744 745 746

    // Load visibility settings
    // TODO

pixhawk's avatar
pixhawk committed
747
    // Connect actions
748
    connect(selectAllCheckBox, SIGNAL(clicked(bool)), checkBox, SLOT(setChecked(bool)));
pixhawk's avatar
pixhawk committed
749 750 751 752 753
    QObject::connect(checkBox, SIGNAL(clicked(bool)), this, SLOT(takeButtonClick(bool)));
    QObject::connect(this, SIGNAL(curveVisible(QString, bool)), plot, SLOT(setVisible(QString, bool)));

    // Set UI components to initial state
    checkBox->setChecked(false);
754
    plot->setVisible(curve+unit, false);
pixhawk's avatar
pixhawk committed
755 756 757 758 759 760 761 762
}

/**
 * @brief Remove the curve from the curve list.
 *
 * @param curve The curve to remove
 * @see addCurve()
 **/
763
void LinechartWidget::removeCurve(QString curve)
pixhawk's avatar
pixhawk committed
764
{
765
    Q_UNUSED(curve)
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806

    QWidget* widget = NULL;
    widget = curveLabels->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveMeans->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveMedians->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveVariances->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
//    widget = colorIcons->take(curve);
//    curvesWidgetLayout->removeWidget(colorIcons->take(curve));
    widget->deleteLater();
//    intData->remove(curve);
}

void LinechartWidget::recolor()
{
    activePlot->shuffleColors();

    foreach (QString key, colorIcons.keys())
    {

        // FIXME
//        if (activePlot)
        QString colorstyle;
        QColor color = activePlot->getColorForCurve(key);
        colorstyle = colorstyle.sprintf("QWidget { background-color: #%X%X%X; }", color.red(), color.green(), color.blue());
        QWidget* colorIcon = colorIcons.value(key, 0);
        if (colorIcon)
        {
            colorIcon->setStyleSheet(colorstyle);
            colorIcon->setAutoFillBackground(true);
        }
    }
}

807
QString LinechartWidget::getCurveName(const QString& key, bool shortEnabled)
808
{
809
    if (shortEnabled)
810 811
    {
        QString name;
812 813
        QStringList parts = curveNames.value(key).split(".");
        if (parts.length() > 1)
814
        {
815 816 817 818 819 820
            name = parts.at(1);
        }
        else
        {
            name = parts.at(0);
        }
821

822
        const int sizeLimit = 20;
823

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
        // Replace known words with abbreviations
        if (name.length() > sizeLimit)
        {
            name.replace("gyroscope", "gyro");
            name.replace("accelerometer", "acc");
            name.replace("magnetometer", "mag");
            name.replace("distance", "dist");
            name.replace("ailerons", "ail");
            name.replace("altitude", "alt");
            name.replace("waypoint", "wp");
            name.replace("throttle", "thr");
            name.replace("elevator", "elev");
            name.replace("rudder", "rud");
            name.replace("error", "err");
            name.replace("version", "ver");
            name.replace("message", "msg");
            name.replace("count", "cnt");
            name.replace("value", "val");
            name.replace("source", "src");
            name.replace("index", "idx");
            name.replace("type", "typ");
            name.replace("mode", "mod");
846
        }
847 848 849

        // Check if sub-part is still exceeding N chars
        if (name.length() > sizeLimit)
850
        {
851 852 853 854 855
            name.replace("a", "");
            name.replace("e", "");
            name.replace("i", "");
            name.replace("o", "");
            name.replace("u", "");
856
        }
857 858 859 860 861 862 863 864 865 866 867 868 869 870

        return name;
    }
    else
    {
        return curveNames.value(key);
    }
}

void LinechartWidget::setShortNames(bool enable)
{
    foreach (QString key, curveNames.keys())
    {
        curveNameLabels.value(key)->setText(getCurveName(key, enable));
871
    }
872
}
pixhawk's avatar
pixhawk committed
873

874 875 876
void LinechartWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
877 878 879 880 881 882 883
    setActive(true);
}

void LinechartWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    setActive(false);
884 885
}

886 887
void LinechartWidget::setActive(bool active)
{
888
    if (activePlot) {
889 890
        activePlot->setActive(active);
    }
891
    if (active) {
892
        updateTimer->start(updateInterval);
893
    } else {
894
        updateTimer->stop();
pixhawk's avatar
pixhawk committed
895 896 897 898 899 900 901 902 903 904 905
    }
}

/**
 * @brief Set the position of the plot window.
 * The plot covers only a portion of the complete time series. The scrollbar
 * allows to select a window of the time series. The right edge of the window is
 * defined proportional to the position of the scrollbar.
 *
 * @param scrollBarValue The value of the scrollbar, in the range from MIN_TIME_SCROLLBAR_VALUE to MAX_TIME_SCROLLBAR_VALUE
 **/
906 907
void LinechartWidget::setPlotWindowPosition(int scrollBarValue)
{
pixhawk's avatar
pixhawk committed
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    plotWindowLock.lockForWrite();
    // Disable automatic scrolling immediately
    int scrollBarRange = (MAX_TIME_SCROLLBAR_VALUE - MIN_TIME_SCROLLBAR_VALUE);
    double position = (static_cast<double>(scrollBarValue) - MIN_TIME_SCROLLBAR_VALUE) / scrollBarRange;
    quint64 scrollInterval;

    // Activate automatic scrolling if scrollbar is at the right edge
    if(scrollBarValue > MAX_TIME_SCROLLBAR_VALUE - (MAX_TIME_SCROLLBAR_VALUE - MIN_TIME_SCROLLBAR_VALUE) * 0.01f) {
        activePlot->setAutoScroll(true);
    } else {
        activePlot->setAutoScroll(false);
        quint64 rightPosition;
        /* If the data exceeds the plot window, choose the position according to the scrollbar position */
        if(activePlot->getDataInterval() > activePlot->getPlotInterval()) {
            scrollInterval = activePlot->getDataInterval() - activePlot->getPlotInterval();
            rightPosition = activePlot->getMinTime() + activePlot->getPlotInterval() + (scrollInterval * position);
        } else {
            /* If the data interval is smaller as the plot interval, clamp the scrollbar to the right */
            rightPosition = activePlot->getMinTime() + activePlot->getPlotInterval();
        }
        emit plotWindowPositionUpdated(rightPosition);
    }


    // The slider position must be mapped onto an interval of datainterval - plotinterval,
    // because the slider position defines the right edge of the plot window. The leftmost
    // slider position must therefore map to the start of the data interval + plot interval
    // to ensure that the plot is not empty

    //  start> |-- plot interval --||-- (data interval - plotinterval) --| <end

    //@TODO Add notification of scrollbar here
    //plot->setWindowPosition(rightPosition);

    plotWindowLock.unlock();
}

/**
 * @brief Receive an updated plot window position.
 * The plot window can be changed by the arrival of new data or by
 * other user interaction. The scrollbar and other UI components
 * can be notified by calling this method.
 *
 * @param position The absolute position of the right edge of the plot window, in milliseconds
 **/
953 954
void LinechartWidget::setPlotWindowPosition(quint64 position)
{
pixhawk's avatar
pixhawk committed
955 956 957 958 959 960 961
    plotWindowLock.lockForWrite();
    // Calculate the relative position
    double pos;

    // A relative position makes only sense if the plot is filled
    if(activePlot->getDataInterval() > activePlot->getPlotInterval()) {
        //TODO @todo Implement the scrollbar enabling in a more elegant way
962
        //scrollbar->setDisabled(false);
pixhawk's avatar
pixhawk committed
963 964 965 966 967 968
        quint64 scrollInterval = position - activePlot->getMinTime() - activePlot->getPlotInterval();



        pos = (static_cast<double>(scrollInterval) / (activePlot->getDataInterval() - activePlot->getPlotInterval()));
    } else {
969
        //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
        pos = 1;
    }
    plotWindowLock.unlock();

    emit plotWindowPositionUpdated(static_cast<int>(pos * (MAX_TIME_SCROLLBAR_VALUE - MIN_TIME_SCROLLBAR_VALUE)));
}

/**
 * @brief Set the time interval the plot displays.
 * The time interval of the plot can be adjusted by this method. If the
 * data covers less time than the interval, the plot will be filled from
 * the right to left
 *
 * @param interval The time interval to plot
 **/
985 986
void LinechartWidget::setPlotInterval(quint64 interval)
{
pixhawk's avatar
pixhawk committed
987 988 989 990 991 992 993 994 995 996
    activePlot->setPlotInterval(interval);
}

/**
 * @brief Take the click of a curve activation / deactivation button.
 * This method allows to map a button to a plot curve.The text of the
 * button must equal the curve name to activate / deactivate.
 *
 * @param checked The visibility of the curve: true to display the curve, false otherwise
 **/
997 998
void LinechartWidget::takeButtonClick(bool checked)
{
pixhawk's avatar
pixhawk committed
999 1000 1001

    QCheckBox* button = qobject_cast<QCheckBox*>(QObject::sender());

1002 1003
    if(button != NULL)
    {
pixhawk's avatar
pixhawk committed
1004
        activePlot->setVisible(button->objectName(), checked);
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

        QColor color = activePlot->getColorForCurve(button->objectName());
        if(color.isValid())
        {
            QString colorstyle;
            colorstyle = colorstyle.sprintf("QWidget { background-color: #%X%X%X; }", color.red(), color.green(), color.blue());
            QWidget* colorIcon = colorIcons.value(button->objectName(), 0);
            if (colorIcon)
            {
                colorIcon->setStyleSheet(colorstyle);
                colorIcon->setAutoFillBackground(true);
            }
        }
pixhawk's avatar
pixhawk committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    }
}

/**
 * @brief Factory method to create a new button.
 *
 * @param imagename The name of the image (should be placed at the standard icon location)
 * @param text The button text
 * @param parent The parent object (to ensure that the memory is freed after the deletion of the button)
 **/
1028 1029
QToolButton* LinechartWidget::createButton(QWidget* parent)
{
pixhawk's avatar
pixhawk committed
1030 1031 1032 1033 1034 1035
    QToolButton* button = new QToolButton(parent);
    button->setMinimumSize(QSize(20, 20));
    button->setMaximumSize(60, 20);
    button->setGeometry(button->x(), button->y(), 20, 20);
    return button;
}