DebugConsole.cc 31.4 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"
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
    QWidget(parent),
    currLink(NULL),
    holdOn(false),
    convertToAscii(true),
    filterMAVLINK(false),
    autoHold(true),
    bytesToIgnore(0),
    lastByte(-1),
52 53
    escReceived(false),
    escIndex(0),
54 55 56
    sentBytes(),
    holdBuffer(),
    lineBuffer(""),
57
    lastLineBuffer(0),
58 59 60 61 62 63
    lineBufferTimer(),
    snapShotTimer(),
    snapShotInterval(500),
    snapShotBytes(0),
    dataRate(0.0f),
    lowpassDataRate(0.0f),
64
    dataRateThreshold(400),
65 66
    commandIndex(0),
    m_ui(new Ui::DebugConsole)
pixhawk's avatar
pixhawk committed
67 68 69
{
    // Setup basic user interface
    m_ui->setupUi(this);
pixhawk's avatar
pixhawk committed
70 71
    // Hide sent text field - it is only useful after send has been hit
    m_ui->sentText->setVisible(false);
72
    // Hide auto-send checkbox
73
    //m_ui->specialCheckBox->setVisible(false);
pixhawk's avatar
pixhawk committed
74
    // Make text area not editable
lm's avatar
lm committed
75
    m_ui->receiveText->setReadOnly(false);
pixhawk's avatar
pixhawk committed
76 77 78 79
    // Limit to 500 lines
    m_ui->receiveText->setMaximumBlockCount(500);
    // Allow to wrap everywhere
    m_ui->receiveText->setWordWrapMode(QTextOption::WrapAnywhere);
80 81
//    // Set monospace font
//    m_ui->receiveText->setFontFamily("Monospace");
pixhawk's avatar
pixhawk committed
82 83 84 85 86

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

pixhawk's avatar
pixhawk committed
89 90 91 92
    // Enable traffic measurements
    connect(&snapShotTimer, SIGNAL(timeout()), this, SLOT(updateTrafficMeasurements()));
    snapShotTimer.setInterval(snapShotInterval);
    snapShotTimer.start();
93 94
    // Update measurements the first time
    updateTrafficMeasurements();
pixhawk's avatar
pixhawk committed
95

96 97 98 99 100 101
    // 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*)));

pixhawk's avatar
pixhawk committed
102 103
    // Get a list of all existing links
    links = QList<LinkInterface*>();
104
    foreach (LinkInterface* link, LinkManager::instance()->getLinks()) {
pixhawk's avatar
pixhawk committed
105 106 107
        addLink(link);
    }

108 109 110 111 112
    // Get a list of all existing UAS
    foreach (UASInterface* uas, UASManager::instance()->getUASList()) {
        uasCreated(uas);
    }

pixhawk's avatar
pixhawk committed
113 114 115 116 117 118 119 120 121 122
    // 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)));
123 124
    // Connect connect button
    connect(m_ui->connectButton, SIGNAL(clicked()), this, SLOT(handleConnectButton()));
125
    // Connect the special chars combo box
126
    connect(m_ui->addSymbolButton, SIGNAL(clicked()), this, SLOT(appendSpecialSymbol()));
127 128
    // Connect Checkbox
    connect(m_ui->specialComboBox, SIGNAL(highlighted(QString)), this, SLOT(specialSymbolSelected(QString)));
129 130
    // Allow to send via return
    connect(m_ui->sendText, SIGNAL(returnPressed()), this, SLOT(sendBytes()));
pixhawk's avatar
pixhawk committed
131 132
}

133 134 135 136 137 138
void DebugConsole::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    storeSettings();
}

pixhawk's avatar
pixhawk committed
139 140
DebugConsole::~DebugConsole()
{
lm's avatar
lm committed
141
    storeSettings();
pixhawk's avatar
pixhawk committed
142 143 144
    delete m_ui;
}

lm's avatar
lm committed
145 146 147 148 149 150 151 152 153
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());
154 155
    MAVLINKfilterEnabled(settings.value("MAVLINK_FILTER_ENABLED", filterMAVLINK).toBool());
    setAutoHold(settings.value("AUTO_HOLD_ENABLED", autoHold).toBool());
lm's avatar
lm committed
156 157
    settings.endGroup();

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

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());
174 175
    settings.setValue("MAVLINK_FILTER_ENABLED", filterMAVLINK);
    settings.setValue("AUTO_HOLD_ENABLED", autoHold);
lm's avatar
lm committed
176 177 178 179 180
    settings.endGroup();
    settings.sync();
    //qDebug() << "Storing settings!";
}

181 182 183 184 185 186
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
187 188 189
/**
 * Add a link to the debug console output
 */
pixhawk's avatar
pixhawk committed
190 191 192 193
void DebugConsole::addLink(LinkInterface* link)
{
    // Add link to link list
    links.insert(link->getId(), link);
pixhawk's avatar
pixhawk committed
194

pixhawk's avatar
pixhawk committed
195 196 197
    m_ui->linkComboBox->insertItem(link->getId(), link->getName());
    // Set new item as current
    m_ui->linkComboBox->setCurrentIndex(qMax(0, links.size() - 1));
198
    linkSelected(m_ui->linkComboBox->currentIndex());
pixhawk's avatar
pixhawk committed
199 200

    // Register for name changes
201 202
    connect(link, SIGNAL(nameChanged(QString)), this, SLOT(updateLinkName(QString)), Qt::UniqueConnection);
    connect(link, SIGNAL(deleteLink(LinkInterface* const)), this, SLOT(removeLink(LinkInterface* const)), Qt::UniqueConnection);
203 204
}

205
void DebugConsole::removeLink(LinkInterface* const linkInterface)
206
{
207
    //LinkInterface* linkInterface = dynamic_cast<LinkInterface*>(link);
208
    // Add link to link list
209
    if (links.contains(linkInterface)) {
210 211 212 213 214 215
        int linkIndex = links.indexOf(linkInterface);

        links.removeAt(linkIndex);

        m_ui->linkComboBox->removeItem(linkIndex);
    }
216
    if (linkInterface == currLink) currLink = NULL;
pixhawk's avatar
pixhawk committed
217
}
218 219
void DebugConsole::linkStatusUpdate(const QString& name,const QString& text)
{
220
    Q_UNUSED(name);
221 222 223 224
    m_ui->receiveText->appendPlainText(text);
    // Ensure text area scrolls correctly
    m_ui->receiveText->ensureCursorVisible();
}
pixhawk's avatar
pixhawk committed
225 226 227 228

void DebugConsole::linkSelected(int linkId)
{
    // Disconnect
229
    if (currLink) {
pixhawk's avatar
pixhawk committed
230
        disconnect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
231
        disconnect(currLink, SIGNAL(connected(bool)), this, SLOT(setConnectionState(bool)));
232
        disconnect(currLink,SIGNAL(communicationUpdate(QString,QString)),this,SLOT(linkStatusUpdate(QString,QString)));
pixhawk's avatar
pixhawk committed
233 234 235 236 237 238 239
    }
    // Clear data
    m_ui->receiveText->clear();

    // Connect new link
    currLink = links[linkId];
    connect(currLink, SIGNAL(bytesReceived(LinkInterface*,QByteArray)), this, SLOT(receiveBytes(LinkInterface*, QByteArray)));
240
    connect(currLink, SIGNAL(connected(bool)), this, SLOT(setConnectionState(bool)));
241
    connect(currLink,SIGNAL(communicationUpdate(QString,QString)),this,SLOT(linkStatusUpdate(QString,QString)));
242
    setConnectionState(currLink->isConnected());
pixhawk's avatar
pixhawk committed
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)
{
250
	// Set name if signal came from a link
pixhawk's avatar
pixhawk committed
251
    LinkInterface* link = qobject_cast<LinkInterface*>(sender());
252 253 254 255 256 257
	//if (link != NULL) m_ui->linkComboBox->setItemText(link->getId(), name);
	if((link != NULL) && (links.contains(link)))
	{
		const qint16 &linkIndex(links.indexOf(link));
		m_ui->linkComboBox->setItemText(linkIndex,name);
	}
pixhawk's avatar
pixhawk committed
258 259 260 261 262
}

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

    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
282 283 284 285
    // Set new state
    autoHold = hold;
}

286 287 288 289
/**
 * Prints the message in the UAS color
 */
void DebugConsole::receiveTextMessage(int id, int component, int severity, QString text)
290
{
291
    Q_UNUSED(severity);
292 293 294 295 296 297 298 299 300 301 302 303 304
    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
305 306
        case MAV_COMP_ID_MISSIONPLANNER:
            comp = tr("MISSION");
307 308 309 310 311 312 313 314
            break;
        case MAV_COMP_ID_SYSTEM_CONTROL:
            comp = tr("SYS-CONTROL");
            break;
        default:
            comp = QString::number(component);
            break;
        }
pixhawk's avatar
pixhawk committed
315

316
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">(%2:%3) %4</font>\n").arg(UASManager::instance()->getUASForId(id)->getColor().name(), name, comp, text));
317 318
        // Ensure text area scrolls correctly
        m_ui->receiveText->ensureCursorVisible();
319
    }
320 321
}

pixhawk's avatar
pixhawk committed
322 323 324 325 326 327 328
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
329
    if ((lowpassDataRate > dataRateThreshold) && autoHold) {
pixhawk's avatar
pixhawk committed
330 331 332 333 334 335 336 337 338
        // 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);

339
    if (holdOn) {
pixhawk's avatar
pixhawk committed
340 341 342 343 344 345 346 347 348 349
        //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)
{
350
    Q_UNUSED(event);
pixhawk's avatar
pixhawk committed
351
    // Update bandwidth
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
//    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
376 377 378 379 380
}

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

        }
519
        // Plot every 200 ms if windows is visible
520
        if (lineBuffer.length() > 0 && (QGC::groundTimeMilliseconds() - lastLineBuffer) > 200) {
521 522
            if (isVisible())
            {
523 524 525
                m_ui->receiveText->appendPlainText(lineBuffer);
                lineBuffer.clear();
                lastLineBuffer = QGC::groundTimeMilliseconds();
526 527 528
                // Ensure text area scrolls correctly
                m_ui->receiveText->ensureCursorVisible();
            }
529 530 531 532
            if (lineBuffer.size() > 8192)
            {
                lineBuffer.remove(0, 4096);
            }
533
        }
lm's avatar
lm committed
534 535 536
    }
    else if (link == currLink && holdOn)
    {
pixhawk's avatar
pixhawk committed
537
        holdBuffer.append(bytes);
lm's avatar
lm committed
538 539
        if (holdBuffer.size() > 8192)
            holdBuffer.remove(0, 4096); // drop old stuff
pixhawk's avatar
pixhawk committed
540 541 542
    }
}

543 544 545
QByteArray DebugConsole::symbolNameToBytes(const QString& text)
{
    QByteArray b;
546
    if (text.contains("CR+LF")) {
547
        b.append(static_cast<char>(0x0D));
548
        b.append(static_cast<char>(0x0A));
549
    } else if (text.contains("LF")) {
550
        b.append(static_cast<char>(0x0A));
551
    } else if (text.contains("FF")) {
552
        b.append(static_cast<char>(0x0C));
553
    } else if (text.contains("CR")) {
554
        b.append(static_cast<char>(0x0D));
555
    } else if (text.contains("TAB")) {
556
        b.append(static_cast<char>(0x09));
557
    } else if (text.contains("NUL")) {
558
        b.append(static_cast<char>(0x00));
559
    } else if (text.contains("ESC")) {
560
        b.append(static_cast<char>(0x1B));
561
    } else if (text.contains("~")) {
562
        b.append(static_cast<char>(0x7E));
563
    } else if (text.contains("<Space>")) {
564 565 566 567 568
        b.append(static_cast<char>(0x20));
    }
    return b;
}

569 570 571
QString DebugConsole::bytesToSymbolNames(const QByteArray& b)
{
    QString text;
572
    if (b.size() > 1 && b.contains(0x0D) && b.contains(0x0A)) {
573
        text = "<CR+LF>";
574
    } else if (b.contains(0x0A)) {
575
        text = "<LF>";
576
    } else if (b.contains(0x0C)) {
577
        text = "<FF>";
578
    } else if (b.contains(0x0D)) {
579
        text = "<CR>";
580
    } else if (b.contains(0x09)) {
581
        text = "<TAB>";
582
    } else if (b.contains((char)0x00)) {
583
        text = "<NUL>";
584
    } else if (b.contains(0x1B)) {
585
        text = "<ESC>";
586
    } else if (b.contains(0x7E)) {
587
        text = "<~>";
588
    } else if (b.contains(0x20)) {
589
        text = "<Space>";
590
    } else {
591 592 593 594 595
        text.append(b);
    }
    return text;
}

596 597 598
void DebugConsole::specialSymbolSelected(const QString& text)
{
    Q_UNUSED(text);
599
    //m_ui->specialCheckBox->setVisible(true);
600 601
}

602 603 604 605 606
void DebugConsole::appendSpecialSymbol(const QString& text)
{
    QString line = m_ui->sendText->text();
    QByteArray symbols = symbolNameToBytes(text);
    // The text is appended to the enter field
607
    if (convertToAscii) {
608
        line.append(symbols);
609
    } else {
610

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

619 620 621 622 623
void DebugConsole::appendSpecialSymbol()
{
    appendSpecialSymbol(m_ui->specialComboBox->currentText());
}

pixhawk's avatar
pixhawk committed
624 625
void DebugConsole::sendBytes()
{
lm's avatar
lm committed
626 627 628 629 630 631
    // 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
632 633 634 635 636 637
    // 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();

638
    if (!m_ui->sentText->isVisible()) {
pixhawk's avatar
pixhawk committed
639 640 641
        m_ui->sentText->setVisible(true);
    }

642
    if (!currLink->isConnected()) {
643 644 645 646
        m_ui->sentText->setText(tr("Nothing sent. The link %1 is unconnected. Please connect first.").arg(currLink->getName()));
        return;
    }

647 648 649
    QString transmitUnconverted = m_ui->sendText->text();
    QByteArray specialSymbol;

650
    // Append special symbol if checkbox is checked
651
    if (m_ui->specialCheckBox->isChecked()) {
652 653 654 655
        // Get auto-add special symbols
        specialSymbol = symbolNameToBytes(m_ui->specialComboBox->currentText());

        // Convert them if needed
656
        if (!convertToAscii) {
657
            QString specialSymbolConverted;
658
            for (int i = 0; i < specialSymbol.length(); i++) {
659 660 661 662 663 664
                QString add(" 0x%1");
                specialSymbolConverted.append(add.arg(static_cast<char>(specialSymbol.at(i)), 2, 16, QChar('0')));
            }
            specialSymbol.clear();
            specialSymbol.append(specialSymbolConverted);
        }
665 666
    }

pixhawk's avatar
pixhawk committed
667 668 669
    QByteArray transmit;
    QString feedback;
    bool ok = true;
670
    if (convertToAscii) {
pixhawk's avatar
pixhawk committed
671
        // ASCII text is not converted
672 673 674 675 676 677 678
        transmit = transmitUnconverted.toLatin1();
        // Auto-add special symbol handling
        transmit.append(specialSymbol);

        QString translated;

        // Replace every occurence of a special symbol with its text name
679
        for (int i = 0; i < transmit.size(); ++i) {
680 681 682 683 684 685
            QByteArray specialChar;
            specialChar.append(transmit.at(i));
            translated.append(bytesToSymbolNames(specialChar));
        }

        feedback.append(translated);
686
    } else {
pixhawk's avatar
pixhawk committed
687
        // HEX symbols are converted to bytes
688 689
        QString str = transmitUnconverted.toLatin1();
        str.append(specialSymbol);
pixhawk's avatar
pixhawk committed
690 691
        str.remove(' ');
        str.remove("0x");
692
        str = str.simplified();
pixhawk's avatar
pixhawk committed
693
        int bufferIndex = 0;
694 695
        if ((str.size() % 2) == 0) {
            for (int i = 0; i < str.size(); i=i+2) {
pixhawk's avatar
pixhawk committed
696 697 698 699 700 701 702
                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;

703
                if (okByte) {
pixhawk's avatar
pixhawk committed
704 705 706 707 708
                    // Feedback
                    //feedback.append("0x");
                    feedback.append(str.at(i).toUpper());
                    feedback.append(str.at(i+1).toUpper());
                    feedback.append(" ");
709
                } else {
pixhawk's avatar
pixhawk committed
710 711 712
                    feedback = tr("HEX format error near \"") + strBuf + "\"";
                }
            }
713
        } else {
pixhawk's avatar
pixhawk committed
714 715 716 717 718 719
            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
720
    if (ok && m_ui->sendText->text().toLatin1().size() > 0) {
pixhawk's avatar
pixhawk committed
721
        // Transmit only if conversion succeeded
722 723 724 725 726 727 728 729 730 731
        //        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()));
        //        }
732
    } else if (m_ui->sendText->text().toLatin1().size() > 0) {
pixhawk's avatar
pixhawk committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746
        // 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)
{
747
    if (convertToAscii == mode) {
lm's avatar
lm committed
748
        convertToAscii = !mode;
749
        if (m_ui->hexCheckBox->isChecked() != mode) {
lm's avatar
lm committed
750 751 752 753 754 755 756
            m_ui->hexCheckBox->setChecked(mode);
        }
        m_ui->receiveText->clear();
        m_ui->sendText->clear();
        m_ui->sentText->clear();
        commandHistory.clear();
    }
pixhawk's avatar
pixhawk committed
757 758 759 760 761 762 763
}

/**
 * @param filter true to ignore all MAVLINK raw data in output, false, to display all incoming data
 */
void DebugConsole::MAVLINKfilterEnabled(bool filter)
{
764
    if (filterMAVLINK != filter) {
lm's avatar
lm committed
765
        filterMAVLINK = filter;
lm's avatar
lm committed
766
        this->bytesToIgnore = 0;
767
        if (m_ui->mavlinkCheckBox->isChecked() != filter) {
lm's avatar
lm committed
768 769 770
            m_ui->mavlinkCheckBox->setChecked(filter);
        }
    }
pixhawk's avatar
pixhawk committed
771 772 773 774 775 776
}
/**
 * @param hold Freeze the input and thus any scrolling
 */
void DebugConsole::hold(bool hold)
{
777 778 779 780 781 782 783 784
    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
785

786
        this->holdOn = hold;
787

788 789 790 791 792 793 794 795 796
        // 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
797 798
    }
}
pixhawk's avatar
pixhawk committed
799

800 801 802 803 804
/**
 * Sets the connection state the widget shows to this state
 */
void DebugConsole::setConnectionState(bool connected)
{
805
    if(connected) {
806
        m_ui->connectButton->setText(tr("Disconn."));
807
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorGreen.name(), tr("Link %1 is connected.").arg(currLink->getName())));
808
    } else {
809
        m_ui->connectButton->setText(tr("Connect"));
810
        m_ui->receiveText->appendHtml(QString("<font color=\"%1\">%2</font>\n").arg(QGC::colorOrange.name(), tr("Link %1 is unconnected.").arg(currLink->getName())));
811 812 813 814 815 816
    }
}

/** @brief Handle the connect button */
void DebugConsole::handleConnectButton()
{
817 818
    if (currLink) {
        if (currLink->isConnected()) {
819
            currLink->disconnect();
820
        } else {
821
            currLink->connect();
822 823 824 825
        }
    }
}

826 827
void DebugConsole::keyPressEvent(QKeyEvent * event)
{
828
    if (event->key() == Qt::Key_Up) {
829
        cycleCommandHistory(true);
830
    } else if (event->key() == Qt::Key_Down) {
831
        cycleCommandHistory(false);
832
    } else {
833 834 835 836 837 838
        QWidget::keyPressEvent(event);
    }
}

void DebugConsole::cycleCommandHistory(bool up)
{
lm's avatar
lm committed
839
    // Only cycle if there is a history
840
    if (commandHistory.length() > 0) {
lm's avatar
lm committed
841
        // Store current command if we're not in history yet
842
        if (commandIndex == commandHistory.length() && up) {
lm's avatar
lm committed
843 844
            currCommand = m_ui->sendText->text();
        }
845

846
        if (up) {
lm's avatar
lm committed
847 848
            // UP
            commandIndex--;
849
            if (commandIndex >= 0) {
lm's avatar
lm committed
850 851 852 853
                m_ui->sendText->setText(commandHistory.at(commandIndex));
            }

            // If the index
854
        } else {
lm's avatar
lm committed
855 856
            // DOWN
            commandIndex++;
857
            if (commandIndex < commandHistory.length()) {
lm's avatar
lm committed
858 859 860
                m_ui->sendText->setText(commandHistory.at(commandIndex));
            }
            // If the index is at history length, load the last current command
861

lm's avatar
lm committed
862 863 864
        }

        // Restore current command if we went out of history
865
        if (commandIndex == commandHistory.length()) {
lm's avatar
lm committed
866
            m_ui->sendText->setText(currCommand);
867 868
        }

lm's avatar
lm committed
869
        // If we are too far down or too far up, wrap around to current command
870
        if (commandIndex < 0 || commandIndex > commandHistory.length()) {
lm's avatar
lm committed
871 872 873
            commandIndex = commandHistory.length();
            m_ui->sendText->setText(currCommand);
        }
874

lm's avatar
lm committed
875 876 877
        // Bound the index
        if (commandIndex < 0) commandIndex = 0;
        if (commandIndex > commandHistory.length()) commandIndex = commandHistory.length();
878 879 880
    }
}

pixhawk's avatar
pixhawk committed
881 882 883 884 885 886 887 888 889 890 891
void DebugConsole::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}