DebugConsole.cc 18.2 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2
/*=====================================================================

lm's avatar
lm committed
3
QGroundControl Open Source Ground Control Station
pixhawk's avatar
pixhawk committed
4

lm's avatar
lm committed
5
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
pixhawk's avatar
pixhawk committed
6

lm's avatar
lm committed
7
This file is part of the QGROUNDCONTROL project
pixhawk's avatar
pixhawk committed
8

lm's avatar
lm committed
9
    QGROUNDCONTROL is free software: you can redistribute it and/or modify
pixhawk's avatar
pixhawk committed
10 11 12 13
    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.

lm's avatar
lm committed
14
    QGROUNDCONTROL is distributed in the hope that it will be useful,
pixhawk's avatar
pixhawk committed
15 16 17 18 19
    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
lm's avatar
lm committed
20
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
pixhawk's avatar
pixhawk committed
21 22 23 24 25

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

/**
 * @file
lm's avatar
lm committed
26
 *   @brief Implementation of DebugConsole
pixhawk's avatar
pixhawk committed
27 28 29 30 31 32 33 34 35
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */
#include <QPainter>

#include "DebugConsole.h"
#include "ui_DebugConsole.h"
#include "LinkManager.h"
36
#include "UASManager.h"
pixhawk's avatar
pixhawk committed
37
#include "protocol.h"
38
#include "QGC.h"
pixhawk's avatar
pixhawk committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

#include <QDebug>

DebugConsole::DebugConsole(QWidget *parent) :
        QWidget(parent),
        currLink(NULL),
        holdOn(false),
        convertToAscii(true),
        filterMAVLINK(false),
        bytesToIgnore(0),
        lastByte(-1),
        sentBytes(),
        holdBuffer(),
        lineBuffer(""),
        lineBufferTimer(),
        snapShotTimer(),
        snapShotInterval(500),
        snapShotBytes(0),
        dataRate(0.0f),
        lowpassDataRate(0.0f),
        dataRateThreshold(500),
        autoHold(true),
        m_ui(new Ui::DebugConsole)
{
    // Setup basic user interface
    m_ui->setupUi(this);
pixhawk's avatar
pixhawk committed
65 66
    // Hide sent text field - it is only useful after send has been hit
    m_ui->sentText->setVisible(false);
67 68
    // Hide auto-send checkbox
    m_ui->specialCheckBox->setVisible(false);
pixhawk's avatar
pixhawk committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    // Make text area not editable
    m_ui->receiveText->setReadOnly(true);
    // Limit to 500 lines
    m_ui->receiveText->setMaximumBlockCount(500);
    // Allow to wrap everywhere
    m_ui->receiveText->setWordWrapMode(QTextOption::WrapAnywhere);

    // Enable 10 Hz output
    //connect(&lineBufferTimer, SIGNAL(timeout()), this, SLOT(showData()));
    //lineBufferTimer.setInterval(100); // 100 Hz
    //lineBufferTimer.start();

    // Enable traffic measurements
    connect(&snapShotTimer, SIGNAL(timeout()), this, SLOT(updateTrafficMeasurements()));
    snapShotTimer.setInterval(snapShotInterval);
    snapShotTimer.start();

    // Set hex checkbox checked
    m_ui->hexCheckBox->setChecked(!convertToAscii);
    m_ui->mavlinkCheckBox->setChecked(filterMAVLINK);
    m_ui->holdCheckBox->setChecked(autoHold);

    // Get a list of all existing links
    links = QList<LinkInterface*>();
    foreach (LinkInterface* link, LinkManager::instance()->getLinks())
    {
        addLink(link);
    }

    // Connect to link manager to get notified about new links
    connect(LinkManager::instance(), SIGNAL(newLink(LinkInterface*)), this, SLOT(addLink(LinkInterface*)));
    // Connect link combo box
    connect(m_ui->linkComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(linkSelected(int)));
    // Connect send button
    connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(sendBytes()));
    // Connect HEX conversion and MAVLINK filter checkboxes
    connect(m_ui->mavlinkCheckBox, SIGNAL(clicked(bool)), this, SLOT(MAVLINKfilterEnabled(bool)));
    connect(m_ui->hexCheckBox, SIGNAL(clicked(bool)), this, SLOT(hexModeEnabled(bool)));
    connect(m_ui->holdCheckBox, SIGNAL(clicked(bool)), this, SLOT(setAutoHold(bool)));
    // Connect hold button
    connect(m_ui->holdButton, SIGNAL(toggled(bool)), this, SLOT(hold(bool)));
110 111
    // Connect connect button
    connect(m_ui->connectButton, SIGNAL(clicked()), this, SLOT(handleConnectButton()));
112
    // Connect the special chars combo box
113
    connect(m_ui->addSymbolButton, SIGNAL(clicked()), this, SLOT(appendSpecialSymbol()));
114 115
    // Connect Checkbox
    connect(m_ui->specialComboBox, SIGNAL(highlighted(QString)), this, SLOT(specialSymbolSelected(QString)));
116 117

    hold(false);
118 119

    this->setVisible(false);
pixhawk's avatar
pixhawk committed
120 121 122 123 124 125 126
}

DebugConsole::~DebugConsole()
{
    delete m_ui;
}

pixhawk's avatar
pixhawk committed
127 128 129
/**
 * Add a link to the debug console output
 */
pixhawk's avatar
pixhawk committed
130 131 132 133
void DebugConsole::addLink(LinkInterface* link)
{
    // Add link to link list
    links.insert(link->getId(), link);
pixhawk's avatar
pixhawk committed
134

pixhawk's avatar
pixhawk committed
135 136 137
    m_ui->linkComboBox->insertItem(link->getId(), link->getName());
    // Set new item as current
    m_ui->linkComboBox->setCurrentIndex(qMax(0, links.size() - 1));
138
    linkSelected(m_ui->linkComboBox->currentIndex());
pixhawk's avatar
pixhawk committed
139 140 141

    // Register for name changes
    connect(link, SIGNAL(nameChanged(QString)), this, SLOT(updateLinkName(QString)));
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    connect(link, SIGNAL(destroyed(QObject*)), this, SLOT(removeLink(QObject*)));
}

void DebugConsole::removeLink(QObject* link)
{
    LinkInterface* linkInterface = dynamic_cast<LinkInterface*>(link);
    // Add link to link list
    if (links.contains(linkInterface))
    {
        int linkIndex = links.indexOf(linkInterface);

        links.removeAt(linkIndex);

        m_ui->linkComboBox->removeItem(linkIndex);
    }
    if (link == currLink) currLink = NULL;
pixhawk's avatar
pixhawk committed
158 159 160 161 162
}

void DebugConsole::linkSelected(int linkId)
{
    // Disconnect
163
    if (currLink)
pixhawk's avatar
pixhawk committed
164 165
    {
        disconnect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
166
        disconnect(currLink, SIGNAL(connected(bool)), this, SLOT(setConnectionState(bool)));
pixhawk's avatar
pixhawk committed
167 168 169 170 171 172 173
    }
    // Clear data
    m_ui->receiveText->clear();

    // Connect new link
    currLink = links[linkId];
    connect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
174 175
    connect(currLink, SIGNAL(connected(bool)), this, SLOT(setConnectionState(bool)));
    setConnectionState(currLink->isConnected());
pixhawk's avatar
pixhawk committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
}

/**
 * @param name new name for this link - the link is determined to the sender to this slot by QObject::sender()
 */
void DebugConsole::updateLinkName(QString name)
{
    // Set name if signal came from a link
    LinkInterface* link = qobject_cast<LinkInterface*>(sender());
    if (link != NULL) m_ui->linkComboBox->setItemText(link->getId(), name);
}

void DebugConsole::setAutoHold(bool hold)
{
    // Disable current hold if hold had been enabled
    if (autoHold && holdOn && !hold)
    {
        this->hold(false);
        m_ui->holdButton->setChecked(false);
    }
    // Set new state
    autoHold = hold;
}

200 201 202 203
/**
 * Prints the message in the UAS color
 */
void DebugConsole::receiveTextMessage(int id, int component, int severity, QString text)
204
{
205 206
    Q_UNUSED(severity);
    m_ui->receiveText->appendHtml(QString("<font color=\"%1\">(MAV%2:%3) %4</font>").arg(UASManager::instance()->getUASForId(id)->getColor().name(), QString::number(id), QString::number(component), text));
207 208
}

pixhawk's avatar
pixhawk committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
void DebugConsole::updateTrafficMeasurements()
{
    lowpassDataRate = lowpassDataRate * 0.9f + (0.1f * ((float)snapShotBytes / (float)snapShotInterval) * 1000.0f);
    dataRate = ((float)snapShotBytes / (float)snapShotInterval) * 1000.0f;
    snapShotBytes = 0;

    // Check if limit has been exceeded
    if ((lowpassDataRate > dataRateThreshold) && autoHold)
    {
        // Enable auto-old
        m_ui->holdButton->setChecked(true);
        hold(true);
    }

    QString speed;
    speed = speed.sprintf("%04.1f kB/s", dataRate/1000.0f);
    m_ui->speedLabel->setText(speed);

    if (holdOn)
    {
        //repaint();
    }
}

//QPainter painter(m_ui->receiveText);
//painter.setRenderHint(QPainter::HighQualityAntialiasing);
//painter.translate((this->vwidth/2.0+xCenterOffset)*scalingFactor, (this->vheight/2.0+yCenterOffset)*scalingFactor);

void DebugConsole::paintEvent(QPaintEvent *event)
{
239
    Q_UNUSED(event);
pixhawk's avatar
pixhawk committed
240
    // Update bandwidth
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
//    if (holdOn)
//    {
//        //qDebug() << "Data rate:" << dataRate/1000.0f << "kB/s";
//        QString rate("data rate: %1");
//        rate.arg(dataRate);
//        QPainter painter(this);
//        painter.setRenderHint(QPainter::HighQualityAntialiasing);
//        painter.translate(width()/5.0f, height()/5.0f);



//        //QFont font("Bitstream Vera Sans");
//        QFont font = painter.font();
//        font.setPixelSize((int)(60.0f));

//        QFontMetrics metrics = QFontMetrics(font);
//        int border = qMax(4, metrics.leading());
//        QRect rect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
//                                          Qt::AlignLeft | Qt::TextWordWrap, rate);
//        painter.setPen(QColor(255, 50, 50));
//        painter.setRenderHint(QPainter::TextAntialiasing);
//        painter.drawText(QRect(QPoint(static_cast<int>(width()/5.0f), static_cast<int>(height()/5.0f)), QPoint(static_cast<int>(width() - width()/5.0f), static_cast<int>(height() - height()/5.0f))), rate);
//        //Qt::AlignRight | Qt::TextWordWrap
//    }
pixhawk's avatar
pixhawk committed
265 266 267 268 269
}

void DebugConsole::receiveBytes(LinkInterface* link, QByteArray bytes)
{
    snapShotBytes += bytes.size();
270
    // Only add data from current link
pixhawk's avatar
pixhawk committed
271 272 273 274 275 276
    if (link == currLink && !holdOn)
    {
        // Parse all bytes
        for (int j = 0; j < bytes.size(); j++)
        {
            unsigned char byte = bytes.at(j);
277
            // Filter MAVLink (http://pixhawk.ethz.ch/wiki/mavlink/) messages out of the stream.
pixhawk's avatar
pixhawk committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
            if (filterMAVLINK && bytes.size() > 1)
            {
                // Filtering is done by setting an ignore counter based on the MAVLINK packet length
                if (static_cast<unsigned char>(bytes[0]) == MAVLINK_STX) bytesToIgnore = static_cast<unsigned int>(bytes[1]) + MAVLINK_NUM_NON_PAYLOAD_BYTES; // Payload plus header
            }

            if (bytesToIgnore <= 0)
            {
                QString str;
                // Convert to ASCII for readability
                if (convertToAscii)
                {
                    if ((byte < 32) || (byte > 126))
                    {
                        switch (byte)
                        {
                            // Catch line feed
295 296 297 298 299 300 301
//                        case (unsigned char)'\n':
//                            m_ui->receiveText->appendPlainText(str);
//                            str = "";
//                            break;
                            // Catch carriage return and line feed
                        case (unsigned char)0xD:
                        case (unsigned char)0xA:
pixhawk's avatar
pixhawk committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
                            // Ignore
                            break;
                        default:
                            str.append(QChar(QChar::ReplacementCharacter));
                            break;
                        }// Append replacement character (box) if char is not ASCII
                    }
                    else
                    {
                        // Append original character
                        str.append(byte);
                    }
                }
                else
                {
                    QString str2;
                    str2.sprintf("%02x ", byte);
                    str.append(str2);
                }
                lineBuffer.append(str);
            }
            else
            {
                if (filterMAVLINK) bytesToIgnore--;
                // Constrain bytes to positive range
                bytesToIgnore = qMax(0, bytesToIgnore);
            }

        }
331
        if (lineBuffer.length() > 0) m_ui->receiveText->appendPlainText(lineBuffer);
pixhawk's avatar
pixhawk committed
332 333 334 335 336 337 338 339 340
        lineBuffer.clear();

    }
    else if (link == currLink && holdOn)
    {
        holdBuffer.append(bytes);
    }
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
QByteArray DebugConsole::symbolNameToBytes(const QString& text)
{
    QByteArray b;
    if (text == "LF")
    {
        b.append(static_cast<char>(0x0A));
    }
    else if (text == "FF")
    {
        b.append(static_cast<char>(0x0C));
    }
    else if (text == "CR")
    {
        b.append(static_cast<char>(0x0D));
    }
    else if (text == "CR+LF")
    {
        b.append(static_cast<char>(0x0D));
        b.append(static_cast<char>(0x0A));
    }
    else if (text == "TAB")
    {
        b.append(static_cast<char>(0x09));
    }
    else if (text == "NUL")
    {
        b.append(static_cast<char>(0x00));
    }
    else if (text == "ESC")
    {
        b.append(static_cast<char>(0x1B));
    }
    else if (text == "~")
    {
        b.append(static_cast<char>(0x7E));
    }
    else if (text == "<Space>")
    {
        b.append(static_cast<char>(0x20));
    }
    return b;
}

384 385 386 387 388 389
void DebugConsole::specialSymbolSelected(const QString& text)
{
    Q_UNUSED(text);
    m_ui->specialCheckBox->setVisible(true);
}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
void DebugConsole::appendSpecialSymbol(const QString& text)
{
    QString line = m_ui->sendText->text();
    QByteArray symbols = symbolNameToBytes(text);
    // The text is appended to the enter field
    if (convertToAscii)
    {
        line.append(symbols);
    }
    else
    {

        for (int i = 0; i < symbols.size(); i++)
        {
            QString add(" 0x%1");
            line.append(add.arg(static_cast<char>(symbols.at(i)), 2, 16, QChar('0')));
        }
    }
    m_ui->sendText->setText(line);
}

411 412 413 414 415
void DebugConsole::appendSpecialSymbol()
{
    appendSpecialSymbol(m_ui->specialComboBox->currentText());
}

pixhawk's avatar
pixhawk committed
416 417
void DebugConsole::sendBytes()
{
pixhawk's avatar
pixhawk committed
418 419 420 421 422
    if (!m_ui->sentText->isVisible())
    {
        m_ui->sentText->setVisible(true);
    }

423 424 425 426 427 428
    if (!currLink->isConnected())
    {
        m_ui->sentText->setText(tr("Nothing sent. The link %1 is unconnected. Please connect first.").arg(currLink->getName()));
        return;
    }

429 430 431 432 433 434
    // Append special symbol if checkbox is checked
    if (m_ui->specialCheckBox->isChecked())
    {
        appendSpecialSymbol(m_ui->specialComboBox->currentText());
    }

pixhawk's avatar
pixhawk committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    QByteArray transmit;
    QString feedback;
    bool ok = true;
    if (convertToAscii)
    {
        // ASCII text is not converted
        transmit = m_ui->sendText->text().toLatin1();
        feedback = transmit;
    }
    else
    {
        // HEX symbols are converted to bytes
        QString str = m_ui->sendText->text().toLatin1();
        str.remove(' ');
        str.remove("0x");
        str.simplified();
        int bufferIndex = 0;
        if ((str.size() % 2) == 0)
        {
            for (int i = 0; i < str.size(); i=i+2)
            {
                bool okByte;
                QString strBuf = QString(str.at(i));
                strBuf.append(str.at(i+1));
                unsigned char hex = strBuf.toInt(&okByte, 16);
                ok = (ok && okByte);
                transmit[bufferIndex++] = hex;

                if (okByte)
                {
                    // Feedback
                    //feedback.append("0x");
                    feedback.append(str.at(i).toUpper());
                    feedback.append(str.at(i+1).toUpper());
                    feedback.append(" ");
                }
                else
                {
                    feedback = tr("HEX format error near \"") + strBuf + "\"";
                }
            }
        }
        else
        {
            ok = false;
            feedback = tr("HEX values have to be in pairs, e.g. AA or AA 05");
        }
    }

    // Transmit ASCII or HEX formatted text, only if more than one symbol
    if (ok && m_ui->sendText->text().toLatin1().size() > 0)
    {
        // Transmit only if conversion succeeded
488 489 490 491 492 493 494 495 496 497
//        int transmitted =
                currLink->writeBytes(transmit, transmit.size());
//        if (transmit.size() == transmitted)
//        {
            m_ui->sentText->setText(tr("Sent: ") + feedback);
//        }
//        else
//        {
//            m_ui->sentText->setText(tr("Error during sending: Transmitted only %1 bytes instead of %2.").arg(transmitted, transmit.size()));
//        }
pixhawk's avatar
pixhawk committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    }
    else if (m_ui->sendText->text().toLatin1().size() > 0)
    {
        // Conversion failed, display error message
        m_ui->sentText->setText(tr("Not sent: ") + feedback);
    }

    // Select text to easy follow-up input from user
    m_ui->sendText->selectAll();
    m_ui->sendText->setFocus(Qt::OtherFocusReason);
}

/**
 * @param mode true to convert all in and output to/from HEX, false to send and receive ASCII values
 */
void DebugConsole::hexModeEnabled(bool mode)
{
    convertToAscii = !mode;
    m_ui->receiveText->clear();
517 518
    m_ui->sendText->clear();
    m_ui->sentText->clear();
pixhawk's avatar
pixhawk committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
}

/**
 * @param filter true to ignore all MAVLINK raw data in output, false, to display all incoming data
 */
void DebugConsole::MAVLINKfilterEnabled(bool filter)
{
    filterMAVLINK = filter;
    bytesToIgnore = 0;
}
/**
 * @param hold Freeze the input and thus any scrolling
 */
void DebugConsole::hold(bool hold)
{
    // Check if we need to append bytes from the hold buffer
    if (this->holdOn && !hold)
    {
537
        // TODO No conversion is done to the bytes in the hold buffer
pixhawk's avatar
pixhawk committed
538 539 540 541 542 543
        m_ui->receiveText->appendPlainText(QString(holdBuffer));
        holdBuffer.clear();
        lowpassDataRate = 0.0f;
    }

    this->holdOn = hold;
544 545 546 547 548 549 550 551 552 553

    // Change text interaction mode
    if (hold)
    {
        m_ui->receiveText->setTextInteractionFlags(Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse | Qt::LinksAccessibleByKeyboard | Qt::LinksAccessibleByMouse);
    }
    else
    {
        m_ui->receiveText->setTextInteractionFlags(Qt::NoTextInteraction);
    }
pixhawk's avatar
pixhawk committed
554 555
}

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
/**
 * Sets the connection state the widget shows to this state
 */
void DebugConsole::setConnectionState(bool connected)
{
    if(connected)
    {
        m_ui->connectButton->setText(tr("Disconn."));
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>").arg(QGC::colorGreen.name(), tr("Link %1 is connected.").arg(currLink->getName())));
    }
    else
    {
        m_ui->connectButton->setText(tr("Connect"));
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>").arg(QGC::colorYellow.name(), tr("Link %1 is unconnected.").arg(currLink->getName())));
    }
}

/** @brief Handle the connect button */
void DebugConsole::handleConnectButton()
{
    if (currLink)
    {
        if (currLink->isConnected())
        {
            currLink->disconnect();
        }
        else
        {
584
            currLink->connect();
585 586 587 588
        }
    }
}

pixhawk's avatar
pixhawk committed
589 590 591 592 593 594 595 596 597 598 599
void DebugConsole::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}