DebugConsole.cc 30.5 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
26
 *   @brief This file implements the Debug Console, a serial console built-in to QGC. 
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>
Lorenz Meier's avatar
Lorenz Meier committed
33
#include <QScrollBar>
34
#include <QDebug>
pixhawk's avatar
pixhawk committed
35 36 37 38

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

Don Gagne's avatar
Don Gagne committed
43 44
const float DebugConsole::inDataRateThreshold = 0.4f;

pixhawk's avatar
pixhawk committed
45
DebugConsole::DebugConsole(QWidget *parent) :
46 47 48 49
    QWidget(parent),
    currLink(NULL),
    holdOn(false),
    convertToAscii(true),
50
    filterMAVLINK(true),
51 52 53
    autoHold(true),
    bytesToIgnore(0),
    lastByte(-1),
54 55
    escReceived(false),
    escIndex(0),
56 57 58
    sentBytes(),
    holdBuffer(),
    lineBuffer(""),
59
    lastLineBuffer(0),
60 61
    lineBufferTimer(),
    snapShotTimer(),
62 63
    lowpassInDataRate(0.0f),
    lowpassOutDataRate(0.0f),
64 65
    commandIndex(0),
    m_ui(new Ui::DebugConsole)
pixhawk's avatar
pixhawk committed
66 67 68
{
    // Setup basic user interface
    m_ui->setupUi(this);
pixhawk's avatar
pixhawk committed
69 70
    // Hide sent text field - it is only useful after send has been hit
    m_ui->sentText->setVisible(false);
71
    // Hide auto-send checkbox
72
    //m_ui->specialCheckBox->setVisible(false);
pixhawk's avatar
pixhawk committed
73
    // Make text area not editable
lm's avatar
lm committed
74
    m_ui->receiveText->setReadOnly(false);
pixhawk's avatar
pixhawk committed
75 76 77 78 79
    // Limit to 500 lines
    m_ui->receiveText->setMaximumBlockCount(500);
    // Allow to wrap everywhere
    m_ui->receiveText->setWordWrapMode(QTextOption::WrapAnywhere);

80
    // Load settings for this widget
81 82
    loadSettings();

83 84
    // Enable traffic measurements. We only start/stop the timer as our links change, as
    // these calculations are dependent on the specific link.
pixhawk's avatar
pixhawk committed
85 86 87
    connect(&snapShotTimer, SIGNAL(timeout()), this, SLOT(updateTrafficMeasurements()));
    snapShotTimer.setInterval(snapShotInterval);

88 89 90 91 92 93
    // First connect management slots, then make sure to add all existing objects
    // Connect to link manager to get notified about new links
    connect(LinkManager::instance(), SIGNAL(newLink(LinkInterface*)), this, SLOT(addLink(LinkInterface*)));
    // Connect to UAS manager to get notified about new UAS
    connect(UASManager::instance(), SIGNAL(UASCreated(UASInterface*)), this, SLOT(uasCreated(UASInterface*)));

94
    // Add all existing links
95
    foreach (LinkInterface* link, LinkManager::instance()->getLinks()) {
pixhawk's avatar
pixhawk committed
96 97 98
        addLink(link);
    }

99 100 101 102 103
    // Get a list of all existing UAS
    foreach (UASInterface* uas, UASManager::instance()->getUASList()) {
        uasCreated(uas);
    }

pixhawk's avatar
pixhawk committed
104 105 106 107 108 109 110 111 112 113
    // 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)));
114 115
    // Connect connect button
    connect(m_ui->connectButton, SIGNAL(clicked()), this, SLOT(handleConnectButton()));
116
    // Connect the special chars combo box
117
    connect(m_ui->addSymbolButton, SIGNAL(clicked()), this, SLOT(appendSpecialSymbol()));
118 119
    // Connect Checkbox
    connect(m_ui->specialComboBox, SIGNAL(highlighted(QString)), this, SLOT(specialSymbolSelected(QString)));
120 121
    // Allow to send via return
    connect(m_ui->sendText, SIGNAL(returnPressed()), this, SLOT(sendBytes()));
pixhawk's avatar
pixhawk committed
122 123
}

124 125 126 127 128 129
void DebugConsole::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    storeSettings();
}

pixhawk's avatar
pixhawk committed
130 131
DebugConsole::~DebugConsole()
{
lm's avatar
lm committed
132
    storeSettings();
pixhawk's avatar
pixhawk committed
133 134 135
    delete m_ui;
}

lm's avatar
lm committed
136 137 138 139 140 141 142 143
void DebugConsole::loadSettings()
{
    // Load defaults from settings
    QSettings settings;
    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());
144 145
    MAVLINKfilterEnabled(settings.value("MAVLINK_FILTER_ENABLED", filterMAVLINK).toBool());
    setAutoHold(settings.value("AUTO_HOLD_ENABLED", autoHold).toBool());
lm's avatar
lm committed
146 147 148 149 150 151 152 153 154 155 156
    settings.endGroup();
}

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());
157 158
    settings.setValue("MAVLINK_FILTER_ENABLED", filterMAVLINK);
    settings.setValue("AUTO_HOLD_ENABLED", autoHold);
lm's avatar
lm committed
159 160 161
    settings.endGroup();
}

162 163 164 165 166 167
void DebugConsole::uasCreated(UASInterface* uas)
{
    connect(uas, SIGNAL(textMessageReceived(int,int,int,QString)),
            this, SLOT(receiveTextMessage(int,int,int,QString)), Qt::UniqueConnection);
}

pixhawk's avatar
pixhawk committed
168 169 170
/**
 * Add a link to the debug console output
 */
pixhawk's avatar
pixhawk committed
171 172
void DebugConsole::addLink(LinkInterface* link)
{
173 174 175 176 177 178
    // Add link to list
    
    foreach (SharedLinkInterface sharedLink, _links) {
        Q_ASSERT(sharedLink.data() != link);
    }
    _links.append(LinkManager::instance()->sharedPointerForLink(link));
pixhawk's avatar
pixhawk committed
179

180
    m_ui->linkComboBox->insertItem(link->getMavlinkChannel(), link->getName());
pixhawk's avatar
pixhawk committed
181
    // Set new item as current
182
    m_ui->linkComboBox->setCurrentIndex(qMax(0, _links.size() - 1));
183
    linkSelected(m_ui->linkComboBox->currentIndex());
pixhawk's avatar
pixhawk committed
184 185

    // Register for name changes
186
    connect(link, SIGNAL(nameChanged(QString)), this, SLOT(updateLinkName(QString)), Qt::UniqueConnection);
187
    connect(LinkManager::instance(), &LinkManager::linkDisconnected, this, &DebugConsole::removeLink, Qt::UniqueConnection);
188 189
}

190
void DebugConsole::removeLink(LinkInterface* const link)
191
{
192 193 194 195 196 197 198 199 200 201 202 203 204
    // Now if this was the current link, clean up some stuff.
    if (link == currLink)
    {
        disconnect(currLink, &LinkInterface::bytesReceived, this, &DebugConsole::receiveBytes);
        disconnect(currLink, &LinkInterface::connected, this, &DebugConsole::_linkConnected);
        disconnect(currLink, &LinkInterface::communicationUpdate, this, &DebugConsole::linkStatusUpdate);
        
        // Like disable the update time for the UI.
        snapShotTimer.stop();
        
        currLink = NULL;
    }
    
205 206 207 208 209 210 211 212
    bool found = false;
    int linkIndex;
    for (linkIndex=0; linkIndex<_links.count(); linkIndex++) {
        if (_links[linkIndex].data() == link) {
            found = true;
            _links.removeAt(linkIndex);
            break;
        }
213
    }
214 215 216 217 218
    Q_UNUSED(found);
    Q_ASSERT(found);
    
    m_ui->linkComboBox->removeItem(linkIndex);
    
pixhawk's avatar
pixhawk committed
219
}
220 221
void DebugConsole::linkStatusUpdate(const QString& name,const QString& text)
{
222
    Q_UNUSED(name);
223 224 225 226
    m_ui->receiveText->appendPlainText(text);
    // Ensure text area scrolls correctly
    m_ui->receiveText->ensureCursorVisible();
}
pixhawk's avatar
pixhawk committed
227

228
void DebugConsole::linkSelected(int linkIndex)
pixhawk's avatar
pixhawk committed
229 230 231 232 233
{
    // Clear data
    m_ui->receiveText->clear();

    // Connect new link
234 235
    if (linkIndex != -1) {
        currLink = _links[linkIndex].data();
236
        connect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
237
        disconnect(currLink, &LinkInterface::connected, this, &DebugConsole::_linkConnected);
238
        connect(currLink,SIGNAL(communicationUpdate(QString,QString)),this,SLOT(linkStatusUpdate(QString,QString)));
239
        _setConnectionState(currLink->isConnected());
240 241
        snapShotTimer.start();
    }
pixhawk's avatar
pixhawk committed
242 243 244 245 246 247 248 249
}

/**
 * @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)
{
    LinkInterface* link = qobject_cast<LinkInterface*>(sender());
250 251 252 253 254 255 256 257 258 259 260 261 262 263
    if (link != NULL) {
        bool found = false;
        int linkIndex;
        for (linkIndex=0; linkIndex<_links.count(); linkIndex++) {
            if (_links[linkIndex].data() == link) {
                found = true;
                break;
            }
        }
        
        if (found) {
            m_ui->linkComboBox->setItemText(linkIndex, name);
        }
    }
pixhawk's avatar
pixhawk committed
264 265 266 267 268
}

void DebugConsole::setAutoHold(bool hold)
{
    // Disable current hold if hold had been enabled
269
    if (autoHold && holdOn && !hold) {
pixhawk's avatar
pixhawk committed
270 271 272
        this->hold(false);
        m_ui->holdButton->setChecked(false);
    }
273
    // Set auto hold checkbox
274
    if (m_ui->holdCheckBox->isChecked() != hold) {
275 276
        m_ui->holdCheckBox->setChecked(hold);
    }
277 278 279 280 281 282 283 284 285 286 287

    if (!hold)
    {
        // Warn user about not activated hold
        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 if 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.")));
    }
    else
    {
        m_ui->receiveText->clear();
    }

pixhawk's avatar
pixhawk committed
288 289 290 291
    // Set new state
    autoHold = hold;
}

292 293 294 295
/**
 * Prints the message in the UAS color
 */
void DebugConsole::receiveTextMessage(int id, int component, int severity, QString text)
296
{
297
    Q_UNUSED(severity);
298 299 300 301 302 303 304 305 306 307 308 309 310
    if (isVisible())
    {
        QString name = UASManager::instance()->getUASForId(id)->getUASName();
        QString comp;
        // Get a human readable name if possible
        switch (component) {
            // TODO: To be completed
        case MAV_COMP_ID_IMU:
            comp = tr("IMU");
            break;
        case MAV_COMP_ID_MAPPER:
            comp = tr("MAPPER");
            break;
lm's avatar
lm committed
311 312
        case MAV_COMP_ID_MISSIONPLANNER:
            comp = tr("MISSION");
313 314 315 316 317 318 319 320
            break;
        case MAV_COMP_ID_SYSTEM_CONTROL:
            comp = tr("SYS-CONTROL");
            break;
        default:
            comp = QString::number(component);
            break;
        }
pixhawk's avatar
pixhawk committed
321

Lorenz Meier's avatar
Lorenz Meier committed
322 323 324 325
        //turn off updates while we're appending content to avoid breaking the autoscroll behavior
        m_ui->receiveText->setUpdatesEnabled(false);
        QScrollBar *scroller = m_ui->receiveText->verticalScrollBar();

326
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">(%2:%3) %4</font>\n").arg(UASManager::instance()->getUASForId(id)->getColor().name(), name, comp, text));
Lorenz Meier's avatar
Lorenz Meier committed
327

328
        // Ensure text area scrolls correctly
Lorenz Meier's avatar
Lorenz Meier committed
329 330
        scroller->setValue(scroller->maximum());
        m_ui->receiveText->setUpdatesEnabled(true);
331
    }
332 333
}

334 335 336 337
/**
 * This function updates the speed indicator text in the GUI.
 * Additionally, if this speed is too high, the display of incoming characters is disabled.
 */
pixhawk's avatar
pixhawk committed
338 339
void DebugConsole::updateTrafficMeasurements()
{
340 341 342 343 344 345 346 347 348 349
    // Calculate the rate of incoming data, converting to
    // kilobytes per second from the received bits per second.
    qint64 inDataRate = currLink->getCurrentInDataRate() / 1000.0f;
    lowpassInDataRate = lowpassInDataRate * 0.9f + (0.1f * inDataRate / 8.0f);

    // If the incoming data rate is faster than our threshold, don't display the data.
    // We don't use the low-passed data rate as we want the true data rate. The low-passed data
    // is just for displaying to the user to remove jitter.
    if ((inDataRate > inDataRateThreshold) && autoHold) {
        // Enable auto-hold
pixhawk's avatar
pixhawk committed
350 351 352 353
        m_ui->holdButton->setChecked(true);
        hold(true);
    }

354 355 356 357 358 359 360 361 362
    // Update the incoming data rate label.
    m_ui->downSpeedLabel->setText(tr("%L1 kB/s").arg(lowpassInDataRate, 4, 'f', 1, '0'));

    // Calculate the rate of outgoing data, converting to
    // kilobytes per second from the received bits per second.
    lowpassOutDataRate = lowpassOutDataRate * 0.9f + (0.1f * currLink->getCurrentOutDataRate() / 8.0f / 1000.0f);
   
    // Update the outoing data rate label.
    m_ui->upSpeedLabel->setText(tr("%L1 kB/s").arg(lowpassOutDataRate, 4, 'f', 1, '0'));
pixhawk's avatar
pixhawk committed
363 364 365 366
}

void DebugConsole::paintEvent(QPaintEvent *event)
{
367
    Q_UNUSED(event);
pixhawk's avatar
pixhawk committed
368 369 370 371
}

void DebugConsole::receiveBytes(LinkInterface* link, QByteArray bytes)
{
lm's avatar
lm committed
372 373 374
    int len = bytes.size();
    int lastSpace = 0;
    if ((this->bytesToIgnore > 260) || (this->bytesToIgnore < -2)) this->bytesToIgnore = 0;
375
    // Only add data from current link
lm's avatar
lm committed
376 377
    if (link == currLink && !holdOn)
    {
pixhawk's avatar
pixhawk committed
378
        // Parse all bytes
lm's avatar
lm committed
379 380
        for (int j = 0; j < len; j++)
        {
pixhawk's avatar
pixhawk committed
381
            unsigned char byte = bytes.at(j);
lm's avatar
lm committed
382
            // Filter MAVLink (http://qgroundcontrol.org/mavlink/) messages out of the stream.
lm's avatar
lm committed
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
            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
400
                // Filtering is done by setting an ignore counter based on the MAVLINK packet length
lm's avatar
lm committed
401 402 403 404 405 406 407 408 409
                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
410 411
                QString str;
                // Convert to ASCII for readability
lm's avatar
lm committed
412 413
                if (convertToAscii)
                {
414 415
                    if (escReceived)
                    {
416
                        if (escIndex < static_cast<int>(sizeof(escBytes)))
417 418 419 420 421 422 423 424 425
                        {
                            escBytes[escIndex] = byte;
                            if (/*escIndex == 1 && */escBytes[escIndex] == 0x48)
                            {
                                // Handle sequence
                                // for this one, clear all text
                                m_ui->receiveText->clear();
                                escReceived = false;
                            }
426
                            else if (escBytes[escIndex] == 0x4b)
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
                            {
                                // Handle sequence
                                // for this one, do nothing
                                escReceived = false;
                            }
                            else if (byte == 0x5b)
                            {
                                // Do nothing, this is still a valid escape sequence
                            }
                            else
                            {
                                escReceived = false;
                            }
                         }
                        else
                        {
                            // Obviously something went wrong, reset
                            escReceived = false;
                            escIndex = 0;
                        }
                    }
                    else if ((byte <= 32) || (byte > 126))
lm's avatar
lm committed
449 450 451 452
                    {
                        switch (byte)
                        {
                            case (unsigned char)'\n':   // Accept line feed
453
                                if (lastByte != '\r')   // Do not break line again for LF+CR
lm's avatar
lm committed
454
                                    str.append(byte);   // only break line for single LF or CR bytes
455
                            break;
lm's avatar
lm committed
456 457 458
                            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
459 460
                                if (lastByte != '\n')   // Do not break line again for CR+LF
                                str.append(byte);       // only break line for single LF or CR bytes
lm's avatar
lm committed
461
                                lastSpace = 1;
pixhawk's avatar
pixhawk committed
462
                            break;
463 464 465 466 467 468 469 470 471
                            /* VT100 emulation (partially */
                            case 0x1b:                  // ESC received
                                escReceived = true;
                                escIndex = 0;
                                //qDebug() << "GOT ESC";
                                break;
                            case 0x08:                  // BS (backspace) received
                                // Do nothing for now
                                break;
lm's avatar
lm committed
472 473 474 475 476 477 478
                            default:                    // Append replacement character (box) if char is not ASCII
                                QString str2;
                                if ( lastSpace == 1)
                                    str2.sprintf("0x%02x ", byte);
                                else str2.sprintf(" 0x%02x ", byte);
                                str.append(str2);
                                lastSpace = 1;
479
                                escReceived = false;
pixhawk's avatar
pixhawk committed
480
                            break;
lm's avatar
lm committed
481
                        }
pixhawk's avatar
pixhawk committed
482
                    }
lm's avatar
lm committed
483 484
                    else
                    {
485 486 487
                        // Ignore carriage return, because that
                        // is auto-added with '\n'
                        if (byte != '\r') str.append(byte);           // Append original character
lm's avatar
lm committed
488 489 490 491 492
                        lastSpace = 0;
                    }
                }
                else
                {
pixhawk's avatar
pixhawk committed
493 494 495 496 497
                    QString str2;
                    str2.sprintf("%02x ", byte);
                    str.append(str2);
                }
                lineBuffer.append(str);
498
                lastByte = byte;
lm's avatar
lm committed
499 500 501 502
            }
            else
            {
                if (filterMAVLINK) this->bytesToIgnore--;
pixhawk's avatar
pixhawk committed
503 504 505
            }

        }
506
        // Plot every 200 ms if windows is visible
507
        if (lineBuffer.length() > 0 && (QGC::groundTimeMilliseconds() - lastLineBuffer) > 200) {
508 509
            if (isVisible())
            {
510 511 512
                m_ui->receiveText->appendPlainText(lineBuffer);
                lineBuffer.clear();
                lastLineBuffer = QGC::groundTimeMilliseconds();
513 514 515
                // Ensure text area scrolls correctly
                m_ui->receiveText->ensureCursorVisible();
            }
516 517 518 519
            if (lineBuffer.size() > 8192)
            {
                lineBuffer.remove(0, 4096);
            }
520
        }
lm's avatar
lm committed
521 522 523
    }
    else if (link == currLink && holdOn)
    {
pixhawk's avatar
pixhawk committed
524
        holdBuffer.append(bytes);
lm's avatar
lm committed
525 526
        if (holdBuffer.size() > 8192)
            holdBuffer.remove(0, 4096); // drop old stuff
pixhawk's avatar
pixhawk committed
527 528 529
    }
}

530 531 532
QByteArray DebugConsole::symbolNameToBytes(const QString& text)
{
    QByteArray b;
533
    if (text.contains("CR+LF")) {
534
        b.append(static_cast<char>(0x0D));
535
        b.append(static_cast<char>(0x0A));
536
    } else if (text.contains("LF")) {
537
        b.append(static_cast<char>(0x0A));
538
    } else if (text.contains("FF")) {
539
        b.append(static_cast<char>(0x0C));
540
    } else if (text.contains("CR")) {
541
        b.append(static_cast<char>(0x0D));
542
    } else if (text.contains("TAB")) {
543
        b.append(static_cast<char>(0x09));
544
    } else if (text.contains("NUL")) {
545
        b.append(static_cast<char>(0x00));
546
    } else if (text.contains("ESC")) {
547
        b.append(static_cast<char>(0x1B));
548
    } else if (text.contains("~")) {
549
        b.append(static_cast<char>(0x7E));
550
    } else if (text.contains("<Space>")) {
551 552 553 554 555
        b.append(static_cast<char>(0x20));
    }
    return b;
}

556 557 558
QString DebugConsole::bytesToSymbolNames(const QByteArray& b)
{
    QString text;
559
    if (b.size() > 1 && b.contains(0x0D) && b.contains(0x0A)) {
560
        text = "<CR+LF>";
561
    } else if (b.contains(0x0A)) {
562
        text = "<LF>";
563
    } else if (b.contains(0x0C)) {
564
        text = "<FF>";
565
    } else if (b.contains(0x0D)) {
566
        text = "<CR>";
567
    } else if (b.contains(0x09)) {
568
        text = "<TAB>";
569
    } else if (b.contains((char)0x00)) {
570
        text = "<NUL>";
571
    } else if (b.contains(0x1B)) {
572
        text = "<ESC>";
573
    } else if (b.contains(0x7E)) {
574
        text = "<~>";
575
    } else if (b.contains(0x20)) {
576
        text = "<Space>";
577
    } else {
578 579 580 581 582
        text.append(b);
    }
    return text;
}

583 584 585 586 587
void DebugConsole::specialSymbolSelected(const QString& text)
{
    Q_UNUSED(text);
}

588 589 590 591 592
void DebugConsole::appendSpecialSymbol(const QString& text)
{
    QString line = m_ui->sendText->text();
    QByteArray symbols = symbolNameToBytes(text);
    // The text is appended to the enter field
593
    if (convertToAscii) {
594
        line.append(symbols);
595
    } else {
596

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

605 606 607 608 609
void DebugConsole::appendSpecialSymbol()
{
    appendSpecialSymbol(m_ui->specialComboBox->currentText());
}

pixhawk's avatar
pixhawk committed
610 611
void DebugConsole::sendBytes()
{
lm's avatar
lm committed
612 613 614 615 616 617
    // 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
618 619 620 621 622 623
    // 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();

624
    if (!m_ui->sentText->isVisible()) {
pixhawk's avatar
pixhawk committed
625 626 627
        m_ui->sentText->setVisible(true);
    }

628
    if (!currLink->isConnected()) {
629 630 631 632
        m_ui->sentText->setText(tr("Nothing sent. The link %1 is unconnected. Please connect first.").arg(currLink->getName()));
        return;
    }

633 634 635
    QString transmitUnconverted = m_ui->sendText->text();
    QByteArray specialSymbol;

636
    // Append special symbol if checkbox is checked
637
    if (m_ui->specialCheckBox->isChecked()) {
638 639 640 641
        // Get auto-add special symbols
        specialSymbol = symbolNameToBytes(m_ui->specialComboBox->currentText());

        // Convert them if needed
642
        if (!convertToAscii) {
643
            QString specialSymbolConverted;
644
            for (int i = 0; i < specialSymbol.length(); i++) {
645 646 647 648 649 650
                QString add(" 0x%1");
                specialSymbolConverted.append(add.arg(static_cast<char>(specialSymbol.at(i)), 2, 16, QChar('0')));
            }
            specialSymbol.clear();
            specialSymbol.append(specialSymbolConverted);
        }
651 652
    }

pixhawk's avatar
pixhawk committed
653 654 655
    QByteArray transmit;
    QString feedback;
    bool ok = true;
656
    if (convertToAscii) {
pixhawk's avatar
pixhawk committed
657
        // ASCII text is not converted
658 659 660 661 662 663 664
        transmit = transmitUnconverted.toLatin1();
        // Auto-add special symbol handling
        transmit.append(specialSymbol);

        QString translated;

        // Replace every occurence of a special symbol with its text name
665
        for (int i = 0; i < transmit.size(); ++i) {
666 667 668 669 670 671
            QByteArray specialChar;
            specialChar.append(transmit.at(i));
            translated.append(bytesToSymbolNames(specialChar));
        }

        feedback.append(translated);
672
    } else {
pixhawk's avatar
pixhawk committed
673
        // HEX symbols are converted to bytes
674 675
        QString str = transmitUnconverted.toLatin1();
        str.append(specialSymbol);
pixhawk's avatar
pixhawk committed
676 677
        str.remove(' ');
        str.remove("0x");
678
        str = str.simplified();
pixhawk's avatar
pixhawk committed
679
        int bufferIndex = 0;
680 681
        if ((str.size() % 2) == 0) {
            for (int i = 0; i < str.size(); i=i+2) {
pixhawk's avatar
pixhawk committed
682 683 684 685 686 687 688
                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;

689
                if (okByte) {
pixhawk's avatar
pixhawk committed
690 691 692 693
                    // Feedback
                    feedback.append(str.at(i).toUpper());
                    feedback.append(str.at(i+1).toUpper());
                    feedback.append(" ");
694
                } else {
pixhawk's avatar
pixhawk committed
695 696 697
                    feedback = tr("HEX format error near \"") + strBuf + "\"";
                }
            }
698
        } else {
pixhawk's avatar
pixhawk committed
699 700 701 702 703 704
            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
705
    if (ok && m_ui->sendText->text().toLatin1().size() > 0) {
pixhawk's avatar
pixhawk committed
706
        // Transmit only if conversion succeeded
707 708
        currLink->writeBytes(transmit, transmit.size());
        m_ui->sentText->setText(tr("Sent: ") + feedback);
709
    } else if (m_ui->sendText->text().toLatin1().size() > 0) {
pixhawk's avatar
pixhawk committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723
        // 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)
{
724
    if (convertToAscii == mode) {
lm's avatar
lm committed
725
        convertToAscii = !mode;
726
        if (m_ui->hexCheckBox->isChecked() != mode) {
lm's avatar
lm committed
727 728 729 730 731 732 733
            m_ui->hexCheckBox->setChecked(mode);
        }
        m_ui->receiveText->clear();
        m_ui->sendText->clear();
        m_ui->sentText->clear();
        commandHistory.clear();
    }
pixhawk's avatar
pixhawk committed
734 735 736 737 738 739 740
}

/**
 * @param filter true to ignore all MAVLINK raw data in output, false, to display all incoming data
 */
void DebugConsole::MAVLINKfilterEnabled(bool filter)
{
741
    if (filterMAVLINK != filter) {
lm's avatar
lm committed
742
        filterMAVLINK = filter;
lm's avatar
lm committed
743
        this->bytesToIgnore = 0;
744
        if (m_ui->mavlinkCheckBox->isChecked() != filter) {
lm's avatar
lm committed
745 746 747
            m_ui->mavlinkCheckBox->setChecked(filter);
        }
    }
pixhawk's avatar
pixhawk committed
748 749 750 751 752 753
}
/**
 * @param hold Freeze the input and thus any scrolling
 */
void DebugConsole::hold(bool hold)
{
754 755 756 757 758 759
    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();
760
            lowpassInDataRate = 0.0f;
761
        }
pixhawk's avatar
pixhawk committed
762

763
        this->holdOn = hold;
764

765 766 767 768 769 770 771 772 773
        // 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
774 775
    }
}
pixhawk's avatar
pixhawk committed
776

777 778 779 780 781 782 783 784 785 786
void DebugConsole::_linkConnected(void)
{
    _setConnectionState(true);
}

void DebugConsole::_linkDisconnected(void)
{
    _setConnectionState(false);
}

787 788 789
/**
 * Sets the connection state the widget shows to this state
 */
790
void DebugConsole::_setConnectionState(bool connected)
791
{
792
    if(connected) {
793
        m_ui->connectButton->setText(tr("Disconn."));
794
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorGreen.name(), tr("Link %1 is connected.").arg(currLink->getName())));
795
    } else {
796
        m_ui->connectButton->setText(tr("Connect"));
797
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorOrange.name(), tr("Link %1 is unconnected.").arg(currLink->getName())));
798 799 800 801 802 803
    }
}

/** @brief Handle the connect button */
void DebugConsole::handleConnectButton()
{
804 805
    if (currLink) {
        if (currLink->isConnected()) {
806
            LinkManager::instance()->disconnect(currLink);
807
        } else {
808
            LinkManager::instance()->connectLink(currLink);
809 810 811 812
        }
    }
}

813 814
void DebugConsole::keyPressEvent(QKeyEvent * event)
{
815
    if (event->key() == Qt::Key_Up) {
816
        cycleCommandHistory(true);
817
    } else if (event->key() == Qt::Key_Down) {
818
        cycleCommandHistory(false);
819
    } else {
820 821 822 823 824 825
        QWidget::keyPressEvent(event);
    }
}

void DebugConsole::cycleCommandHistory(bool up)
{
lm's avatar
lm committed
826
    // Only cycle if there is a history
827
    if (commandHistory.length() > 0) {
lm's avatar
lm committed
828
        // Store current command if we're not in history yet
829
        if (commandIndex == commandHistory.length() && up) {
lm's avatar
lm committed
830 831
            currCommand = m_ui->sendText->text();
        }
832

833
        if (up) {
lm's avatar
lm committed
834 835
            // UP
            commandIndex--;
836
            if (commandIndex >= 0) {
lm's avatar
lm committed
837 838 839 840
                m_ui->sendText->setText(commandHistory.at(commandIndex));
            }

            // If the index
841
        } else {
lm's avatar
lm committed
842 843
            // DOWN
            commandIndex++;
844
            if (commandIndex < commandHistory.length()) {
lm's avatar
lm committed
845 846 847
                m_ui->sendText->setText(commandHistory.at(commandIndex));
            }
            // If the index is at history length, load the last current command
848

lm's avatar
lm committed
849 850 851
        }

        // Restore current command if we went out of history
852
        if (commandIndex == commandHistory.length()) {
lm's avatar
lm committed
853
            m_ui->sendText->setText(currCommand);
854 855
        }

lm's avatar
lm committed
856
        // If we are too far down or too far up, wrap around to current command
857
        if (commandIndex < 0 || commandIndex > commandHistory.length()) {
lm's avatar
lm committed
858 859 860
            commandIndex = commandHistory.length();
            m_ui->sendText->setText(currCommand);
        }
861

lm's avatar
lm committed
862 863 864
        // Bound the index
        if (commandIndex < 0) commandIndex = 0;
        if (commandIndex > commandHistory.length()) commandIndex = commandHistory.length();
865 866 867
    }
}

pixhawk's avatar
pixhawk committed
868 869 870 871 872 873 874 875 876 877 878
void DebugConsole::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}