DebugConsole.cc 27.3 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
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */
#include <QPainter>
lm's avatar
lm committed
32
#include <QSettings>
pixhawk's avatar
pixhawk committed
33 34 35 36

#include "DebugConsole.h"
#include "ui_DebugConsole.h"
#include "LinkManager.h"
37
#include "UASManager.h"
pixhawk's avatar
pixhawk committed
38
#include "protocol.h"
39
#include "QGC.h"
pixhawk's avatar
pixhawk committed
40 41 42 43

#include <QDebug>

DebugConsole::DebugConsole(QWidget *parent) :
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    QWidget(parent),
    currLink(NULL),
    holdOn(false),
    convertToAscii(true),
    filterMAVLINK(false),
    autoHold(true),
    bytesToIgnore(0),
    lastByte(-1),
    sentBytes(),
    holdBuffer(),
    lineBuffer(""),
    lineBufferTimer(),
    snapShotTimer(),
    snapShotInterval(500),
    snapShotBytes(0),
    dataRate(0.0f),
    lowpassDataRate(0.0f),
    dataRateThreshold(500),
    commandIndex(0),
    m_ui(new Ui::DebugConsole)
pixhawk's avatar
pixhawk committed
64 65 66
{
    // Setup basic user interface
    m_ui->setupUi(this);
pixhawk's avatar
pixhawk committed
67 68
    // Hide sent text field - it is only useful after send has been hit
    m_ui->sentText->setVisible(false);
69
    // Hide auto-send checkbox
70
    //m_ui->specialCheckBox->setVisible(false);
pixhawk's avatar
pixhawk committed
71
    // Make text area not editable
lm's avatar
lm committed
72
    m_ui->receiveText->setReadOnly(false);
pixhawk's avatar
pixhawk committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    // 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();

88 89 90 91
//    // Set hex checkbox checked
//    m_ui->hexCheckBox->setChecked(!convertToAscii);
//    m_ui->mavlinkCheckBox->setChecked(filterMAVLINK);
//    m_ui->holdCheckBox->setChecked(autoHold);
pixhawk's avatar
pixhawk committed
92 93 94

    // Get a list of all existing links
    links = QList<LinkInterface*>();
95
    foreach (LinkInterface* link, LinkManager::instance()->getLinks()) {
pixhawk's avatar
pixhawk committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        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)));
111 112
    // Connect connect button
    connect(m_ui->connectButton, SIGNAL(clicked()), this, SLOT(handleConnectButton()));
113
    // Connect the special chars combo box
114
    connect(m_ui->addSymbolButton, SIGNAL(clicked()), this, SLOT(appendSpecialSymbol()));
115 116
    // Connect Checkbox
    connect(m_ui->specialComboBox, SIGNAL(highlighted(QString)), this, SLOT(specialSymbolSelected(QString)));
117
    // Set add button invisible if auto add checkbox is checked
118
    //connect(m_ui->specialCheckBox, SIGNAL(clicked(bool)), m_ui->addSymbolButton, SLOT(setHidden(bool)));
119 120
    // Allow to send via return
    connect(m_ui->sendText, SIGNAL(returnPressed()), this, SLOT(sendBytes()));
121

lm's avatar
lm committed
122 123 124
    loadSettings();

    // Warn user about not activated hold
125
    if (!m_ui->holdCheckBox->isChecked()) {
lm's avatar
lm committed
126 127
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QColor(Qt::red).name(), tr("WARNING: You have NOT enabled auto-hold (stops updating the console is huge amounts of serial data arrive). Updating the console consumes significant CPU load, so if you receive more than about 5 KB/s of serial data, make sure to enable auto-hold if not using the console.")));
    }
pixhawk's avatar
pixhawk committed
128 129
}

130 131 132 133 134 135
void DebugConsole::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    storeSettings();
}

pixhawk's avatar
pixhawk committed
136 137
DebugConsole::~DebugConsole()
{
lm's avatar
lm committed
138
    storeSettings();
pixhawk's avatar
pixhawk committed
139 140 141
    delete m_ui;
}

lm's avatar
lm committed
142 143 144 145 146 147 148 149 150
void DebugConsole::loadSettings()
{
    // Load defaults from settings
    QSettings settings;
    settings.sync();
    settings.beginGroup("QGC_DEBUG_CONSOLE");
    m_ui->specialComboBox->setCurrentIndex(settings.value("SPECIAL_SYMBOL", m_ui->specialComboBox->currentIndex()).toInt());
    m_ui->specialCheckBox->setChecked(settings.value("SPECIAL_SYMBOL_CHECKBOX_STATE", m_ui->specialCheckBox->isChecked()).toBool());
    hexModeEnabled(settings.value("HEX_MODE_ENABLED", m_ui->hexCheckBox->isChecked()).toBool());
151 152
    MAVLINKfilterEnabled(settings.value("MAVLINK_FILTER_ENABLED", filterMAVLINK).toBool());
    setAutoHold(settings.value("AUTO_HOLD_ENABLED", autoHold).toBool());
lm's avatar
lm committed
153 154
    settings.endGroup();

155 156 157 158 159 160
//    // Update visibility settings
//    if (m_ui->specialCheckBox->isChecked())
//    {
//        m_ui->specialCheckBox->setVisible(true);
//        m_ui->addSymbolButton->setVisible(false);
//    }
lm's avatar
lm committed
161 162 163 164 165 166 167 168 169 170
}

void DebugConsole::storeSettings()
{
    // Store settings
    QSettings settings;
    settings.beginGroup("QGC_DEBUG_CONSOLE");
    settings.setValue("SPECIAL_SYMBOL", m_ui->specialComboBox->currentIndex());
    settings.setValue("SPECIAL_SYMBOL_CHECKBOX_STATE", m_ui->specialCheckBox->isChecked());
    settings.setValue("HEX_MODE_ENABLED", m_ui->hexCheckBox->isChecked());
171 172
    settings.setValue("MAVLINK_FILTER_ENABLED", filterMAVLINK);
    settings.setValue("AUTO_HOLD_ENABLED", autoHold);
lm's avatar
lm committed
173 174 175 176 177
    settings.endGroup();
    settings.sync();
    //qDebug() << "Storing settings!";
}

pixhawk's avatar
pixhawk committed
178 179 180
/**
 * Add a link to the debug console output
 */
pixhawk's avatar
pixhawk committed
181 182 183 184
void DebugConsole::addLink(LinkInterface* link)
{
    // Add link to link list
    links.insert(link->getId(), link);
pixhawk's avatar
pixhawk committed
185

pixhawk's avatar
pixhawk committed
186 187 188
    m_ui->linkComboBox->insertItem(link->getId(), link->getName());
    // Set new item as current
    m_ui->linkComboBox->setCurrentIndex(qMax(0, links.size() - 1));
189
    linkSelected(m_ui->linkComboBox->currentIndex());
pixhawk's avatar
pixhawk committed
190 191 192

    // Register for name changes
    connect(link, SIGNAL(nameChanged(QString)), this, SLOT(updateLinkName(QString)));
193 194 195 196 197 198 199
    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
200
    if (links.contains(linkInterface)) {
201 202 203 204 205 206 207
        int linkIndex = links.indexOf(linkInterface);

        links.removeAt(linkIndex);

        m_ui->linkComboBox->removeItem(linkIndex);
    }
    if (link == currLink) currLink = NULL;
pixhawk's avatar
pixhawk committed
208 209 210 211 212
}

void DebugConsole::linkSelected(int linkId)
{
    // Disconnect
213
    if (currLink) {
pixhawk's avatar
pixhawk committed
214
        disconnect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
215
        disconnect(currLink, SIGNAL(connected(bool)), this, SLOT(setConnectionState(bool)));
pixhawk's avatar
pixhawk committed
216 217 218 219 220 221 222
    }
    // Clear data
    m_ui->receiveText->clear();

    // Connect new link
    currLink = links[linkId];
    connect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
223 224
    connect(currLink, SIGNAL(connected(bool)), this, SLOT(setConnectionState(bool)));
    setConnectionState(currLink->isConnected());
pixhawk's avatar
pixhawk committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
}

/**
 * @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
240
    if (autoHold && holdOn && !hold) {
pixhawk's avatar
pixhawk committed
241 242 243
        this->hold(false);
        m_ui->holdButton->setChecked(false);
    }
244
    // Set auto hold checkbox
245
    if (m_ui->holdCheckBox->isChecked() != hold) {
246 247
        m_ui->holdCheckBox->setChecked(hold);
    }
pixhawk's avatar
pixhawk committed
248 249 250 251
    // Set new state
    autoHold = hold;
}

252 253 254 255
/**
 * Prints the message in the UAS color
 */
void DebugConsole::receiveTextMessage(int id, int component, int severity, QString text)
256
{
257
    Q_UNUSED(severity);
pixhawk's avatar
pixhawk committed
258 259 260
    QString name = UASManager::instance()->getUASForId(id)->getUASName();
    QString comp;
    // Get a human readable name if possible
261
    switch (component) {
pixhawk's avatar
pixhawk committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        // TODO: To be completed
    case MAV_COMP_ID_IMU:
        comp = tr("IMU");
        break;
    case MAV_COMP_ID_MAPPER:
        comp = tr("MAPPER");
        break;
    case MAV_COMP_ID_WAYPOINTPLANNER:
        comp = tr("WP-PLANNER");
        break;
    case MAV_COMP_ID_AIRSLAM:
        comp = tr("AIRSLAM");
        break;
    default:
        comp = QString::number(component);
        break;
    }

    m_ui->receiveText->appendHtml(QString("<font color=\"%1\">(%2:%3) %4</font>\n").arg(UASManager::instance()->getUASForId(id)->getColor().name(), name, comp, text));
281
    //m_ui->receiveText->appendPlainText("");
282 283
}

pixhawk's avatar
pixhawk committed
284 285 286 287 288 289 290
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
291
    if ((lowpassDataRate > dataRateThreshold) && autoHold) {
pixhawk's avatar
pixhawk committed
292 293 294 295 296 297 298 299 300
        // 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);

301
    if (holdOn) {
pixhawk's avatar
pixhawk committed
302 303 304 305 306 307 308 309 310 311
        //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)
{
312
    Q_UNUSED(event);
pixhawk's avatar
pixhawk committed
313
    // Update bandwidth
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
//    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
338 339 340 341 342
}

void DebugConsole::receiveBytes(LinkInterface* link, QByteArray bytes)
{
    snapShotBytes += bytes.size();
lm's avatar
lm committed
343 344 345
    int len = bytes.size();
    int lastSpace = 0;
    if ((this->bytesToIgnore > 260) || (this->bytesToIgnore < -2)) this->bytesToIgnore = 0;
346
    // Only add data from current link
lm's avatar
lm committed
347 348
    if (link == currLink && !holdOn)
    {
pixhawk's avatar
pixhawk committed
349
        // Parse all bytes
lm's avatar
lm committed
350 351
        for (int j = 0; j < len; j++)
        {
pixhawk's avatar
pixhawk committed
352
            unsigned char byte = bytes.at(j);
353
            // Filter MAVLink (http://pixhawk.ethz.ch/wiki/mavlink/) messages out of the stream.
lm's avatar
lm committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
            if (filterMAVLINK)
            {
                if (this->bytesToIgnore > 0)
                {
                    if ( (j + this->bytesToIgnore) < len )
                        j += this->bytesToIgnore - 1, this->bytesToIgnore = 1;
                    else
                        this->bytesToIgnore -= (len - j - 1), j = len - 1;
                } else
                if (this->bytesToIgnore == -2)
                {   // Payload plus header - but we got STX already
                    this->bytesToIgnore = static_cast<unsigned int>(byte) + MAVLINK_NUM_NON_PAYLOAD_BYTES - 1;
                    if ( (j + this->bytesToIgnore) < len )
                        j += this->bytesToIgnore - 1, this->bytesToIgnore = 1;
                    else
                        this->bytesToIgnore -= (len - j - 1), j = len - 1;
                } else
pixhawk's avatar
pixhawk committed
371
                // Filtering is done by setting an ignore counter based on the MAVLINK packet length
lm's avatar
lm committed
372 373 374 375 376 377 378 379 380
                if (static_cast<unsigned char>(byte) == MAVLINK_STX)
                {
                    this->bytesToIgnore = -1;
                } else
                    this->bytesToIgnore = 0;
            } else this->bytesToIgnore = 0;

            if ( (this->bytesToIgnore <= 0) && (this->bytesToIgnore != -1) )
            {
pixhawk's avatar
pixhawk committed
381 382
                QString str;
                // Convert to ASCII for readability
lm's avatar
lm committed
383 384 385 386 387 388 389 390 391 392
                if (convertToAscii)
                {
                    if ((byte <= 32) || (byte > 126))
                    {
                        switch (byte)
                        {
                            case (unsigned char)'\n':   // Accept line feed
                                if (lastByte != '\r')   // Do not break line again for CR+LF
                                    str.append(byte);   // only break line for single LF or CR bytes
                                else ;
393
                            break;
lm's avatar
lm committed
394 395 396 397 398
                            case (unsigned char)' ':    // space of any type means don't add another on hex output
                            case (unsigned char)'\t':   // Accept tab
                            case (unsigned char)'\r':   // Catch and carriage return
                                str.append(byte);
                                lastSpace = 1;
pixhawk's avatar
pixhawk committed
399
                            break;
lm's avatar
lm committed
400 401 402 403 404 405 406 407
                            default:                    // Append replacement character (box) if char is not ASCII
//                                str.append(QChar(QChar::ReplacementCharacter));
                                QString str2;
                                if ( lastSpace == 1)
                                    str2.sprintf("0x%02x ", byte);
                                else str2.sprintf(" 0x%02x ", byte);
                                str.append(str2);
                                lastSpace = 1;
pixhawk's avatar
pixhawk committed
408
                            break;
lm's avatar
lm committed
409
                        }
pixhawk's avatar
pixhawk committed
410
                    }
lm's avatar
lm committed
411 412 413 414 415 416 417 418
                    else
                    {
                        str.append(byte);           // Append original character
                        lastSpace = 0;
                    }
                }
                else
                {
pixhawk's avatar
pixhawk committed
419 420 421 422 423
                    QString str2;
                    str2.sprintf("%02x ", byte);
                    str.append(str2);
                }
                lineBuffer.append(str);
424
                lastByte = byte;
lm's avatar
lm committed
425 426 427 428
            }
            else
            {
                if (filterMAVLINK) this->bytesToIgnore--;
pixhawk's avatar
pixhawk committed
429
                // Constrain bytes to positive range
lm's avatar
lm committed
430
//                bytesToIgnore = qMax(0, bytesToIgnore);
pixhawk's avatar
pixhawk committed
431 432 433
            }

        }
lm's avatar
lm committed
434 435
        if (lineBuffer.length() > 0)
        {
436 437 438 439 440
            m_ui->receiveText->insertPlainText(lineBuffer);
            // Ensure text area scrolls correctly
            m_ui->receiveText->ensureCursorVisible();
            lineBuffer.clear();
        }
lm's avatar
lm committed
441 442 443
    }
    else if (link == currLink && holdOn)
    {
pixhawk's avatar
pixhawk committed
444
        holdBuffer.append(bytes);
lm's avatar
lm committed
445 446
        if (holdBuffer.size() > 8192)
            holdBuffer.remove(0, 4096); // drop old stuff
pixhawk's avatar
pixhawk committed
447 448 449
    }
}

450 451 452
QByteArray DebugConsole::symbolNameToBytes(const QString& text)
{
    QByteArray b;
453
    if (text.contains("CR+LF")) {
454
        b.append(static_cast<char>(0x0D));
455
        b.append(static_cast<char>(0x0A));
456
    } else if (text.contains("LF")) {
457
        b.append(static_cast<char>(0x0A));
458
    } else if (text.contains("FF")) {
459
        b.append(static_cast<char>(0x0C));
460
    } else if (text.contains("CR")) {
461
        b.append(static_cast<char>(0x0D));
462
    } else if (text.contains("TAB")) {
463
        b.append(static_cast<char>(0x09));
464
    } else if (text.contains("NUL")) {
465
        b.append(static_cast<char>(0x00));
466
    } else if (text.contains("ESC")) {
467
        b.append(static_cast<char>(0x1B));
468
    } else if (text.contains("~")) {
469
        b.append(static_cast<char>(0x7E));
470
    } else if (text.contains("<Space>")) {
471 472 473 474 475
        b.append(static_cast<char>(0x20));
    }
    return b;
}

476 477 478
QString DebugConsole::bytesToSymbolNames(const QByteArray& b)
{
    QString text;
479
    if (b.size() > 1 && b.contains(0x0D) && b.contains(0x0A)) {
480
        text = "<CR+LF>";
481
    } else if (b.contains(0x0A)) {
482
        text = "<LF>";
483
    } else if (b.contains(0x0C)) {
484
        text = "<FF>";
485
    } else if (b.contains(0x0D)) {
486
        text = "<CR>";
487
    } else if (b.contains(0x09)) {
488
        text = "<TAB>";
489
    } else if (b.contains((char)0x00)) {
490
        text == "<NUL>";
491
    } else if (b.contains(0x1B)) {
492
        text = "<ESC>";
493
    } else if (b.contains(0x7E)) {
494
        text = "<~>";
495
    } else if (b.contains(0x20)) {
496
        text = "<Space>";
497
    } else {
498 499 500 501 502
        text.append(b);
    }
    return text;
}

503 504 505
void DebugConsole::specialSymbolSelected(const QString& text)
{
    Q_UNUSED(text);
506
    //m_ui->specialCheckBox->setVisible(true);
507 508
}

509 510 511 512 513
void DebugConsole::appendSpecialSymbol(const QString& text)
{
    QString line = m_ui->sendText->text();
    QByteArray symbols = symbolNameToBytes(text);
    // The text is appended to the enter field
514
    if (convertToAscii) {
515
        line.append(symbols);
516
    } else {
517

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

526 527 528 529 530
void DebugConsole::appendSpecialSymbol()
{
    appendSpecialSymbol(m_ui->specialComboBox->currentText());
}

pixhawk's avatar
pixhawk committed
531 532
void DebugConsole::sendBytes()
{
lm's avatar
lm committed
533 534 535 536 537 538
    // FIXME This store settings should be removed
    // once all threading issues have been resolved
    // since its called in the destructor, which
    // is absolutely sufficient
    storeSettings();

lm's avatar
lm committed
539 540 541 542 543 544
    // Store command history
    commandHistory.append(m_ui->sendText->text());
    // Since text was just sent, we're at position commandHistory.length()
    // which is the current text
    commandIndex = commandHistory.length();

545
    if (!m_ui->sentText->isVisible()) {
pixhawk's avatar
pixhawk committed
546 547 548
        m_ui->sentText->setVisible(true);
    }

549
    if (!currLink->isConnected()) {
550 551 552 553
        m_ui->sentText->setText(tr("Nothing sent. The link %1 is unconnected. Please connect first.").arg(currLink->getName()));
        return;
    }

554 555 556
    QString transmitUnconverted = m_ui->sendText->text();
    QByteArray specialSymbol;

557
    // Append special symbol if checkbox is checked
558
    if (m_ui->specialCheckBox->isChecked()) {
559 560 561 562
        // Get auto-add special symbols
        specialSymbol = symbolNameToBytes(m_ui->specialComboBox->currentText());

        // Convert them if needed
563
        if (!convertToAscii) {
564
            QString specialSymbolConverted;
565
            for (int i = 0; i < specialSymbol.length(); i++) {
566 567 568 569 570 571
                QString add(" 0x%1");
                specialSymbolConverted.append(add.arg(static_cast<char>(specialSymbol.at(i)), 2, 16, QChar('0')));
            }
            specialSymbol.clear();
            specialSymbol.append(specialSymbolConverted);
        }
572 573
    }

pixhawk's avatar
pixhawk committed
574 575 576
    QByteArray transmit;
    QString feedback;
    bool ok = true;
577
    if (convertToAscii) {
pixhawk's avatar
pixhawk committed
578
        // ASCII text is not converted
579 580 581 582 583 584 585
        transmit = transmitUnconverted.toLatin1();
        // Auto-add special symbol handling
        transmit.append(specialSymbol);

        QString translated;

        // Replace every occurence of a special symbol with its text name
586
        for (int i = 0; i < transmit.size(); ++i) {
587 588 589 590 591 592
            QByteArray specialChar;
            specialChar.append(transmit.at(i));
            translated.append(bytesToSymbolNames(specialChar));
        }

        feedback.append(translated);
593
    } else {
pixhawk's avatar
pixhawk committed
594
        // HEX symbols are converted to bytes
595 596
        QString str = transmitUnconverted.toLatin1();
        str.append(specialSymbol);
pixhawk's avatar
pixhawk committed
597 598 599 600
        str.remove(' ');
        str.remove("0x");
        str.simplified();
        int bufferIndex = 0;
601 602
        if ((str.size() % 2) == 0) {
            for (int i = 0; i < str.size(); i=i+2) {
pixhawk's avatar
pixhawk committed
603 604 605 606 607 608 609
                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;

610
                if (okByte) {
pixhawk's avatar
pixhawk committed
611 612 613 614 615
                    // Feedback
                    //feedback.append("0x");
                    feedback.append(str.at(i).toUpper());
                    feedback.append(str.at(i+1).toUpper());
                    feedback.append(" ");
616
                } else {
pixhawk's avatar
pixhawk committed
617 618 619
                    feedback = tr("HEX format error near \"") + strBuf + "\"";
                }
            }
620
        } else {
pixhawk's avatar
pixhawk committed
621 622 623 624 625 626
            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
627
    if (ok && m_ui->sendText->text().toLatin1().size() > 0) {
pixhawk's avatar
pixhawk committed
628
        // Transmit only if conversion succeeded
629 630 631 632 633 634 635 636 637 638
        //        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()));
        //        }
639
    } else if (m_ui->sendText->text().toLatin1().size() > 0) {
pixhawk's avatar
pixhawk committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653
        // 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)
{
654
    if (convertToAscii == mode) {
lm's avatar
lm committed
655
        convertToAscii = !mode;
656
        if (m_ui->hexCheckBox->isChecked() != mode) {
lm's avatar
lm committed
657 658 659 660 661 662 663
            m_ui->hexCheckBox->setChecked(mode);
        }
        m_ui->receiveText->clear();
        m_ui->sendText->clear();
        m_ui->sentText->clear();
        commandHistory.clear();
    }
pixhawk's avatar
pixhawk committed
664 665 666 667 668 669 670
}

/**
 * @param filter true to ignore all MAVLINK raw data in output, false, to display all incoming data
 */
void DebugConsole::MAVLINKfilterEnabled(bool filter)
{
671
    if (filterMAVLINK != filter) {
lm's avatar
lm committed
672
        filterMAVLINK = filter;
lm's avatar
lm committed
673
        this->bytesToIgnore = 0;
674
        if (m_ui->mavlinkCheckBox->isChecked() != filter) {
lm's avatar
lm committed
675 676 677
            m_ui->mavlinkCheckBox->setChecked(filter);
        }
    }
pixhawk's avatar
pixhawk committed
678 679 680 681 682 683
}
/**
 * @param hold Freeze the input and thus any scrolling
 */
void DebugConsole::hold(bool hold)
{
684 685 686 687 688 689 690 691
    if (holdOn != hold) {
        // Check if we need to append bytes from the hold buffer
        if (this->holdOn && !hold) {
            // TODO No conversion is done to the bytes in the hold buffer
            m_ui->receiveText->appendPlainText(QString(holdBuffer));
            holdBuffer.clear();
            lowpassDataRate = 0.0f;
        }
pixhawk's avatar
pixhawk committed
692

693
        this->holdOn = hold;
694

695 696 697 698 699 700 701 702 703
        // 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);
        }
        if (m_ui->holdCheckBox->isChecked() != hold) {
            m_ui->holdCheckBox->setChecked(hold);
        }
lm's avatar
lm committed
704 705
    }
}
pixhawk's avatar
pixhawk committed
706

707 708 709 710 711
/**
 * Sets the connection state the widget shows to this state
 */
void DebugConsole::setConnectionState(bool connected)
{
712
    if(connected) {
713
        m_ui->connectButton->setText(tr("Disconn."));
714
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorGreen.name(), tr("Link %1 is connected.").arg(currLink->getName())));
715
    } else {
716
        m_ui->connectButton->setText(tr("Connect"));
717
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorOrange.name(), tr("Link %1 is unconnected.").arg(currLink->getName())));
718 719 720 721 722 723
    }
}

/** @brief Handle the connect button */
void DebugConsole::handleConnectButton()
{
724 725
    if (currLink) {
        if (currLink->isConnected()) {
726
            currLink->disconnect();
727
        } else {
728
            currLink->connect();
729 730 731 732
        }
    }
}

733 734
void DebugConsole::keyPressEvent(QKeyEvent * event)
{
735
    if (event->key() == Qt::Key_Up) {
736
        cycleCommandHistory(true);
737
    } else if (event->key() == Qt::Key_Down) {
738
        cycleCommandHistory(false);
739
    } else {
740 741 742 743 744 745
        QWidget::keyPressEvent(event);
    }
}

void DebugConsole::cycleCommandHistory(bool up)
{
lm's avatar
lm committed
746
    // Only cycle if there is a history
747
    if (commandHistory.length() > 0) {
lm's avatar
lm committed
748
        // Store current command if we're not in history yet
749
        if (commandIndex == commandHistory.length() && up) {
lm's avatar
lm committed
750 751
            currCommand = m_ui->sendText->text();
        }
752

753
        if (up) {
lm's avatar
lm committed
754 755
            // UP
            commandIndex--;
756
            if (commandIndex >= 0) {
lm's avatar
lm committed
757 758 759 760
                m_ui->sendText->setText(commandHistory.at(commandIndex));
            }

            // If the index
761
        } else {
lm's avatar
lm committed
762 763
            // DOWN
            commandIndex++;
764
            if (commandIndex < commandHistory.length()) {
lm's avatar
lm committed
765 766 767
                m_ui->sendText->setText(commandHistory.at(commandIndex));
            }
            // If the index is at history length, load the last current command
768

lm's avatar
lm committed
769 770 771
        }

        // Restore current command if we went out of history
772
        if (commandIndex == commandHistory.length()) {
lm's avatar
lm committed
773
            m_ui->sendText->setText(currCommand);
774 775
        }

lm's avatar
lm committed
776
        // If we are too far down or too far up, wrap around to current command
777
        if (commandIndex < 0 || commandIndex > commandHistory.length()) {
lm's avatar
lm committed
778 779 780
            commandIndex = commandHistory.length();
            m_ui->sendText->setText(currCommand);
        }
781

lm's avatar
lm committed
782 783 784
        // Bound the index
        if (commandIndex < 0) commandIndex = 0;
        if (commandIndex > commandHistory.length()) commandIndex = commandHistory.length();
785 786 787
    }
}

pixhawk's avatar
pixhawk committed
788 789 790 791 792 793 794 795 796 797 798
void DebugConsole::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}