MockLink.cc 37.7 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
9

10 11

#include "MockLink.h"
12
#include "QGCLoggingCategory.h"
13
#include "QGCApplication.h"
14 15 16 17 18 19 20

#include <QTimer>
#include <QDebug>
#include <QFile>

#include <string.h>

Daniel Agar's avatar
Daniel Agar committed
21 22
#include "px4_custom_mode.h"

23
QGC_LOGGING_CATEGORY(MockLinkLog, "MockLinkLog")
Don Gagne's avatar
Don Gagne committed
24
QGC_LOGGING_CATEGORY(MockLinkVerboseLog, "MockLinkVerboseLog")
25

26 27 28 29 30
/// @file
///     @brief Mock implementation of a Link.
///
///     @author Don Gagne <don@thegagnes.com>

Don Gagne's avatar
Don Gagne committed
31 32 33 34 35
float           MockLink::_vehicleLatitude =        47.633033f;
float           MockLink::_vehicleLongitude =       -122.08794f;
float           MockLink::_vehicleAltitude =        3.5f;
int             MockLink::_nextVehicleSystemId =    128;
const char*     MockLink::_failParam =              "COM_FLTMODE6";
Don Gagne's avatar
Don Gagne committed
36

37
const char* MockConfiguration::_firmwareTypeKey =   "FirmwareType";
38
const char* MockConfiguration::_vehicleTypeKey =    "VehicleType";
39
const char* MockConfiguration::_sendStatusTextKey = "SendStatusText";
Don Gagne's avatar
Don Gagne committed
40
const char* MockConfiguration::_failureModeKey =    "FailureMode";
41

42
MockLink::MockLink(MockConfiguration* config)
43
    : _missionItemHandler(this, qgcApp()->toolbox()->mavlinkProtocol())
44 45
    , _name("MockLink")
    , _connected(false)
46 47
    , _vehicleSystemId(_nextVehicleSystemId++)
    , _vehicleComponentId(200)
48
    , _inNSH(false)
Don Gagne's avatar
Don Gagne committed
49
    , _mavlinkStarted(true)
50 51
    , _mavBaseMode(MAV_MODE_FLAG_MANUAL_INPUT_ENABLED | MAV_MODE_FLAG_CUSTOM_MODE_ENABLED)
    , _mavState(MAV_STATE_STANDBY)
Don Gagne's avatar
Don Gagne committed
52
    , _firmwareType(MAV_AUTOPILOT_PX4)
53
    , _vehicleType(MAV_TYPE_QUADROTOR)
54
    , _fileServer(NULL)
55
    , _sendStatusText(false)
Don Gagne's avatar
Don Gagne committed
56
    , _apmSendHomePositionOnEmptyList(false)
Don Gagne's avatar
Don Gagne committed
57
    , _failureMode(MockConfiguration::FailNone)
58 59
    , _sendHomePositionDelayCount(10)   // No home position for 4 seconds
    , _sendGPSPositionDelayCount(100)   // No gps lock for 5 seconds
Don Gagne's avatar
Don Gagne committed
60 61
    , _currentParamRequestListComponentIndex(-1)
    , _currentParamRequestListParamIndex(-1)
62
{
63
    _config = config;
64
    if (_config) {
Don Gagne's avatar
Don Gagne committed
65
        _firmwareType = config->firmwareType();
66
        _vehicleType = config->vehicleType();
67
        _sendStatusText = config->sendStatusText();
Don Gagne's avatar
Don Gagne committed
68
        _failureMode = config->failureMode();
Don Gagne's avatar
Don Gagne committed
69
        _config->setLink(this);
70 71
    }

Don Gagne's avatar
Don Gagne committed
72 73 74 75 76 77
    union px4_custom_mode   px4_cm;

    px4_cm.data = 0;
    px4_cm.main_mode = PX4_CUSTOM_MAIN_MODE_MANUAL;
    _mavCustomMode = px4_cm.data;

78 79
    _fileServer = new MockLinkFileServer(_vehicleSystemId, _vehicleComponentId, this);
    Q_CHECK_PTR(_fileServer);
dogmaphobic's avatar
dogmaphobic committed
80

81
    moveToThread(this);
dogmaphobic's avatar
dogmaphobic committed
82

83 84 85 86 87
    _loadParams();
}

MockLink::~MockLink(void)
{
88
    _disconnect();
89 90
}

91
bool MockLink::_connect(void)
92
{
93 94 95 96 97
    if (!_connected) {
        _connected = true;
        start();
        emit connected();
    }
98

99 100 101
    return true;
}

Don Gagne's avatar
Don Gagne committed
102
void MockLink::_disconnect(void)
103
{
104 105
    if (_connected) {
        _connected = false;
Daniel Agar's avatar
Daniel Agar committed
106 107
        quit();
        wait();
108 109
        emit disconnected();
    }
110 111 112 113
}

void MockLink::run(void)
{
Don Gagne's avatar
Don Gagne committed
114 115 116
    QTimer  timer1HzTasks;
    QTimer  timer10HzTasks;
    QTimer  timer500HzTasks;
117

Don Gagne's avatar
Don Gagne committed
118 119 120
    QObject::connect(&timer1HzTasks,  &QTimer::timeout, this, &MockLink::_run1HzTasks);
    QObject::connect(&timer10HzTasks, &QTimer::timeout, this, &MockLink::_run10HzTasks);
    QObject::connect(&timer500HzTasks, &QTimer::timeout, this, &MockLink::_run500HzTasks);
121

Don Gagne's avatar
Don Gagne committed
122 123 124
    timer1HzTasks.start(1000);
    timer10HzTasks.start(100);
    timer500HzTasks.start(2);
125

126
    exec();
127

Don Gagne's avatar
Don Gagne committed
128 129 130
    QObject::disconnect(&timer1HzTasks,  &QTimer::timeout, this, &MockLink::_run1HzTasks);
    QObject::disconnect(&timer10HzTasks, &QTimer::timeout, this, &MockLink::_run10HzTasks);
    QObject::disconnect(&timer500HzTasks, &QTimer::timeout, this, &MockLink::_run500HzTasks);
dogmaphobic's avatar
dogmaphobic committed
131

132
    _missionItemHandler.shutdown();
133 134 135 136
}

void MockLink::_run1HzTasks(void)
{
137
    if (_mavlinkStarted && _connected) {
138
        _sendHeartBeat();
Don Gagne's avatar
Don Gagne committed
139
        _sendVibration();
140 141 142 143
        if (!qgcApp()->runningUnitTests()) {
            // Sending RC Channels during unit test breaks RC tests which does it's own RC simulation
            _sendRCChannels();
        }
144
        if (_sendHomePositionDelayCount > 0) {
145
            // We delay home position for better testing
146 147 148 149
            _sendHomePositionDelayCount--;
        } else {
            _sendHomePosition();
        }
150 151 152 153
        if (_sendStatusText) {
            _sendStatusText = false;
            _sendStatusTextMessages();
        }
154 155 156 157 158
    }
}

void MockLink::_run10HzTasks(void)
{
159
    if (_mavlinkStarted && _connected) {
160 161 162 163 164 165
        if (_sendGPSPositionDelayCount > 0) {
            // We delay gps position for better testing
            _sendGPSPositionDelayCount--;
        } else {
            _sendGpsRawInt();
        }
166 167 168
    }
}

Don Gagne's avatar
Don Gagne committed
169
void MockLink::_run500HzTasks(void)
170
{
171
    if (_mavlinkStarted && _connected) {
Don Gagne's avatar
Don Gagne committed
172
        _paramRequestListWorker();
173 174 175 176 177
    }
}

void MockLink::_loadParams(void)
{
178 179 180 181 182 183 184 185 186 187 188 189
    QFile paramFile;

    if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
        if (_vehicleType == MAV_TYPE_FIXED_WING) {
            paramFile.setFileName(":/unittest/APMArduPlaneMockLink.params");
        } else {
            paramFile.setFileName(":/unittest/APMArduCopterMockLink.params");
        }
    } else {
        paramFile.setFileName(":/unittest/PX4MockLink.params");
    }

190

191 192 193
    bool success = paramFile.open(QFile::ReadOnly);
    Q_UNUSED(success);
    Q_ASSERT(success);
194

195
    QTextStream paramStream(&paramFile);
196

197 198
    while (!paramStream.atEnd()) {
        QString line = paramStream.readLine();
199

200 201 202
        if (line.startsWith("#")) {
            continue;
        }
203

204 205
        QStringList paramData = line.split("\t");
        Q_ASSERT(paramData.count() == 5);
206

207
        int componentId = paramData.at(1).toInt();
208 209 210
        QString paramName = paramData.at(2);
        QString valStr = paramData.at(3);
        uint paramType = paramData.at(4).toUInt();
211

212 213
        QVariant paramValue;
        switch (paramType) {
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        case MAV_PARAM_TYPE_REAL32:
            paramValue = QVariant(valStr.toFloat());
            break;
        case MAV_PARAM_TYPE_UINT32:
            paramValue = QVariant(valStr.toUInt());
            break;
        case MAV_PARAM_TYPE_INT32:
            paramValue = QVariant(valStr.toInt());
            break;
        case MAV_PARAM_TYPE_UINT16:
            paramValue = QVariant((quint16)valStr.toUInt());
            break;
        case MAV_PARAM_TYPE_INT16:
            paramValue = QVariant((qint16)valStr.toInt());
            break;
        case MAV_PARAM_TYPE_UINT8:
            paramValue = QVariant((quint8)valStr.toUInt());
            break;
        case MAV_PARAM_TYPE_INT8:
            paramValue = QVariant((qint8)valStr.toUInt());
            break;
        default:
            qCritical() << "Unknown type" << paramType;
            paramValue = QVariant(valStr.toInt());
            break;
239
        }
240

Don Gagne's avatar
Don Gagne committed
241
        qCDebug(MockLinkVerboseLog) << "Loading param" << paramName << paramValue;
242

243
        _mapParamName2Value[componentId][paramName] = paramValue;
244
        _mapParamName2MavParamType[paramName] = static_cast<MAV_PARAM_TYPE>(paramType);
245 246 247 248 249 250 251 252 253 254
    }
}

void MockLink::_sendHeartBeat(void)
{
    mavlink_message_t   msg;

    mavlink_msg_heartbeat_pack(_vehicleSystemId,
                               _vehicleComponentId,
                               &msg,
Don Gagne's avatar
Don Gagne committed
255
                               _vehicleType,        // MAV_TYPE
Don Gagne's avatar
Don Gagne committed
256
                               _firmwareType,      // MAV_AUTOPILOT
Don Gagne's avatar
Don Gagne committed
257 258
                               _mavBaseMode,        // MAV_MODE
                               _mavCustomMode,      // custom mode
259
                               _mavState);          // MAV_STATE
dogmaphobic's avatar
dogmaphobic committed
260

261 262
    respondWithMavlinkMessage(msg);
}
263

Don Gagne's avatar
Don Gagne committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
void MockLink::_sendVibration(void)
{
    mavlink_message_t   msg;

    mavlink_msg_vibration_pack(_vehicleSystemId,
                               _vehicleComponentId,
                               &msg,
                               0,       // time_usec
                               50.5,    // vibration_x,
                               10.5,    // vibration_y,
                               60.0,    // vibration_z,
                               1,       // clipping_0
                               2,       // clipping_0
                               3);      // clipping_0

    respondWithMavlinkMessage(msg);
}

282 283 284
void MockLink::respondWithMavlinkMessage(const mavlink_message_t& msg)
{
    uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
dogmaphobic's avatar
dogmaphobic committed
285

286 287 288 289 290 291
    int cBuffer = mavlink_msg_to_send_buffer(buffer, &msg);
    QByteArray bytes((char *)buffer, cBuffer);
    emit bytesReceived(this, bytes);
}

/// @brief Called when QGC wants to write bytes to the MAV
292
void MockLink::_writeBytes(const QByteArray bytes)
293 294 295 296 297 298 299 300
{
    if (_inNSH) {
        _handleIncomingNSHBytes(bytes.constData(), bytes.count());
    } else {
        if (bytes.startsWith(QByteArray("\r\r\r"))) {
            _inNSH  = true;
            _handleIncomingNSHBytes(&bytes.constData()[3], bytes.count() - 3);
        }
301

302 303 304 305 306 307 308 309
        _handleIncomingMavlinkBytes((uint8_t *)bytes.constData(), bytes.count());
    }
}

/// @brief Handle incoming bytes which are meant to be interpreted by the NuttX shell
void MockLink::_handleIncomingNSHBytes(const char* bytes, int cBytes)
{
    Q_UNUSED(cBytes);
310

311 312 313 314 315 316 317 318
    // Drop back out of NSH
    if (cBytes == 4 && bytes[0] == '\r' && bytes[1] == '\r' && bytes[2] == '\r') {
        _inNSH  = false;
        return;
    }

    if (cBytes > 0) {
        qDebug() << "NSH:" << (const char*)bytes;
319

Don Gagne's avatar
Don Gagne committed
320 321
#if 0
        // MockLink not quite ready to handle this correctly yet
322 323 324 325
        if (strncmp(bytes, "sh /etc/init.d/rc.usb\n", cBytes) == 0) {
            // This is the mavlink start command
            _mavlinkStarted = true;
        }
Don Gagne's avatar
Don Gagne committed
326
#endif
327 328 329 330 331 332 333 334
    }
}

/// @brief Handle incoming bytes which are meant to be handled by the mavlink protocol
void MockLink::_handleIncomingMavlinkBytes(const uint8_t* bytes, int cBytes)
{
    mavlink_message_t msg;
    mavlink_status_t comm;
335

336 337
    for (qint64 i=0; i<cBytes; i++)
    {
338
        if (!mavlink_parse_char(getMavlinkChannel(), bytes[i], &msg, &comm)) {
339 340
            continue;
        }
dogmaphobic's avatar
dogmaphobic committed
341

342
        if (_missionItemHandler.handleMessage(msg)) {
Don Gagne's avatar
Don Gagne committed
343 344
            continue;
        }
345

346
        switch (msg.msgid) {
347 348 349
        case MAVLINK_MSG_ID_HEARTBEAT:
            _handleHeartBeat(msg);
            break;
350

351 352 353
        case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
            _handleParamRequestList(msg);
            break;
354

355 356 357
        case MAVLINK_MSG_ID_SET_MODE:
            _handleSetMode(msg);
            break;
358

359 360 361
        case MAVLINK_MSG_ID_PARAM_SET:
            _handleParamSet(msg);
            break;
362

363 364 365
        case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
            _handleParamRequestRead(msg);
            break;
dogmaphobic's avatar
dogmaphobic committed
366

367 368 369
        case MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL:
            _handleFTP(msg);
            break;
dogmaphobic's avatar
dogmaphobic committed
370

371 372 373
        case MAVLINK_MSG_ID_COMMAND_LONG:
            _handleCommandLong(msg);
            break;
374

375 376 377
        case MAVLINK_MSG_ID_MANUAL_CONTROL:
            _handleManualControl(msg);
            break;
Don Gagne's avatar
Don Gagne committed
378

379 380
        default:
            break;
381 382 383 384 385 386 387
        }
    }
}

void MockLink::_handleHeartBeat(const mavlink_message_t& msg)
{
    Q_UNUSED(msg);
388
    qCDebug(MockLinkLog) << "Heartbeat";
389 390 391 392 393 394
}

void MockLink::_handleSetMode(const mavlink_message_t& msg)
{
    mavlink_set_mode_t request;
    mavlink_msg_set_mode_decode(&msg, &request);
395

396
    Q_ASSERT(request.target_system == _vehicleSystemId);
397

398 399 400 401
    _mavBaseMode = request.base_mode;
    _mavCustomMode = request.custom_mode;
}

Don Gagne's avatar
Don Gagne committed
402 403 404 405 406 407 408 409
void MockLink::_handleManualControl(const mavlink_message_t& msg)
{
    mavlink_manual_control_t manualControl;
    mavlink_msg_manual_control_decode(&msg, &manualControl);

    qDebug() << "MANUAL_CONTROL" << manualControl.x << manualControl.y << manualControl.z << manualControl.r;
}

410
void MockLink::_setParamFloatUnionIntoMap(int componentId, const QString& paramName, float paramFloat)
411 412
{
    mavlink_param_union_t   valueUnion;
413

414 415
    Q_ASSERT(_mapParamName2Value.contains(componentId));
    Q_ASSERT(_mapParamName2Value[componentId].contains(paramName));
416
    Q_ASSERT(_mapParamName2MavParamType.contains(paramName));
417

418
    valueUnion.param_float = paramFloat;
419

420
    MAV_PARAM_TYPE paramType = _mapParamName2MavParamType[paramName];
421

422
    QVariant paramVariant;
423

424
    switch (paramType) {
425 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
    case MAV_PARAM_TYPE_REAL32:
        paramVariant = QVariant::fromValue(valueUnion.param_float);
        break;

    case MAV_PARAM_TYPE_UINT32:
        paramVariant = QVariant::fromValue(valueUnion.param_uint32);
        break;

    case MAV_PARAM_TYPE_INT32:
        paramVariant = QVariant::fromValue(valueUnion.param_int32);
        break;

    case MAV_PARAM_TYPE_UINT16:
        paramVariant = QVariant::fromValue(valueUnion.param_uint16);
        break;

    case MAV_PARAM_TYPE_INT16:
        paramVariant = QVariant::fromValue(valueUnion.param_int16);
        break;

    case MAV_PARAM_TYPE_UINT8:
        paramVariant = QVariant::fromValue(valueUnion.param_uint8);
        break;

    case MAV_PARAM_TYPE_INT8:
        paramVariant = QVariant::fromValue(valueUnion.param_int8);
        break;

    default:
        qCritical() << "Invalid parameter type" << paramType;
        paramVariant = QVariant::fromValue(valueUnion.param_int32);
        break;
457
    }
458

459
    qCDebug(MockLinkLog) << "_setParamFloatUnionIntoMap" << paramName << paramVariant;
460
    _mapParamName2Value[componentId][paramName] = paramVariant;
461 462
}

463
/// Convert from a parameter variant to the float value from mavlink_param_union_t
464
float MockLink::_floatUnionForParam(int componentId, const QString& paramName)
465
{
466
    mavlink_param_union_t   valueUnion;
467

468 469
    Q_ASSERT(_mapParamName2Value.contains(componentId));
    Q_ASSERT(_mapParamName2Value[componentId].contains(paramName));
470
    Q_ASSERT(_mapParamName2MavParamType.contains(paramName));
471

472
    MAV_PARAM_TYPE paramType = _mapParamName2MavParamType[paramName];
473
    QVariant paramVar = _mapParamName2Value[componentId][paramName];
474

475
    switch (paramType) {
476
    case MAV_PARAM_TYPE_REAL32:
477
        valueUnion.param_float = paramVar.toFloat();
478
        break;
479

480 481 482 483 484 485 486
    case MAV_PARAM_TYPE_UINT32:
        if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            valueUnion.param_float = paramVar.toUInt();
        } else {
            valueUnion.param_uint32 = paramVar.toUInt();
        }
        break;
487

488 489 490 491 492 493 494
    case MAV_PARAM_TYPE_INT32:
        if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            valueUnion.param_float = paramVar.toInt();
        } else {
            valueUnion.param_int32 = paramVar.toInt();
        }
        break;
495

496 497 498 499 500 501 502
    case MAV_PARAM_TYPE_UINT16:
        if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            valueUnion.param_float = paramVar.toUInt();
        } else {
            valueUnion.param_uint16 = paramVar.toUInt();
        }
        break;
503

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    case MAV_PARAM_TYPE_INT16:
        if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            valueUnion.param_float = paramVar.toInt();
        } else {
            valueUnion.param_int16 = paramVar.toInt();
        }
        break;

    case MAV_PARAM_TYPE_UINT8:
        if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            valueUnion.param_float = paramVar.toUInt();
        } else {
            valueUnion.param_uint8 = paramVar.toUInt();
        }
        break;

    case MAV_PARAM_TYPE_INT8:
        if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            valueUnion.param_float = (unsigned char)paramVar.toChar().toLatin1();
        } else {
            valueUnion.param_int8 = (unsigned char)paramVar.toChar().toLatin1();
        }
        break;

    default:
        if (_firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            valueUnion.param_float = paramVar.toInt();
        } else {
            valueUnion.param_int32 = paramVar.toInt();
        }
        qCritical() << "Invalid parameter type" << paramType;
535
    }
536

537
    return valueUnion.param_float;
538 539 540 541
}

void MockLink::_handleParamRequestList(const mavlink_message_t& msg)
{
Don Gagne's avatar
Don Gagne committed
542 543 544 545
    if (_failureMode == MockConfiguration::FailParamNoReponseToRequestList) {
        return;
    }

546
    mavlink_param_request_list_t request;
547

548
    mavlink_msg_param_request_list_decode(&msg, &request);
549

550
    Q_ASSERT(request.target_system == _vehicleSystemId);
551
    Q_ASSERT(request.target_component == MAV_COMP_ID_ALL);
dogmaphobic's avatar
dogmaphobic committed
552

Don Gagne's avatar
Don Gagne committed
553 554 555 556
    // Start the worker routine
    _currentParamRequestListComponentIndex = 0;
    _currentParamRequestListParamIndex = 0;
}
557

Don Gagne's avatar
Don Gagne committed
558 559 560 561 562 563 564
/// Sends the next parameter to the vehicle
void MockLink::_paramRequestListWorker(void)
{
    if (_currentParamRequestListComponentIndex == -1) {
        // Initial request complete
        return;
    }
dogmaphobic's avatar
dogmaphobic committed
565

Don Gagne's avatar
Don Gagne committed
566 567 568
    int componentId = _mapParamName2Value.keys()[_currentParamRequestListComponentIndex];
    int cParameters = _mapParamName2Value[componentId].count();
    QString paramName = _mapParamName2Value[componentId].keys()[_currentParamRequestListParamIndex];
569

Don Gagne's avatar
Don Gagne committed
570 571 572
    if ((_failureMode == MockConfiguration::FailMissingParamOnInitialReqest || _failureMode == MockConfiguration::FailMissingParamOnAllRequests) && paramName == _failParam) {
        qCDebug(MockLinkLog) << "Skipping param send:" << paramName;
    } else {
573

Don Gagne's avatar
Don Gagne committed
574 575
        char paramId[MAVLINK_MSG_ID_PARAM_VALUE_LEN];
        mavlink_message_t responseMsg;
576

Don Gagne's avatar
Don Gagne committed
577 578
        Q_ASSERT(_mapParamName2Value[componentId].contains(paramName));
        Q_ASSERT(_mapParamName2MavParamType.contains(paramName));
579

Don Gagne's avatar
Don Gagne committed
580
        MAV_PARAM_TYPE paramType = _mapParamName2MavParamType[paramName];
581

Don Gagne's avatar
Don Gagne committed
582 583
        Q_ASSERT(paramName.length() <= MAVLINK_MSG_ID_PARAM_VALUE_LEN);
        strncpy(paramId, paramName.toLocal8Bit().constData(), MAVLINK_MSG_ID_PARAM_VALUE_LEN);
dogmaphobic's avatar
dogmaphobic committed
584

Don Gagne's avatar
Don Gagne committed
585 586 587 588 589 590 591 592 593 594 595
        qCDebug(MockLinkLog) << "Sending msg_param_value" << componentId << paramId << paramType << _mapParamName2Value[componentId][paramId];

        mavlink_msg_param_value_pack(_vehicleSystemId,
                                     componentId,                                   // component id
                                     &responseMsg,                                  // Outgoing message
                                     paramId,                                       // Parameter name
                                     _floatUnionForParam(componentId, paramName),   // Parameter value
                                     paramType,                                     // MAV_PARAM_TYPE
                                     cParameters,                                   // Total number of parameters
                                     _currentParamRequestListParamIndex);           // Index of this parameter
        respondWithMavlinkMessage(responseMsg);
596
    }
dogmaphobic's avatar
dogmaphobic committed
597

Don Gagne's avatar
Don Gagne committed
598 599 600 601 602 603 604 605
    // Move to next param index
    if (++_currentParamRequestListParamIndex >= cParameters) {
        // We've sent the last parameter for this component, move to next component
        if (++_currentParamRequestListComponentIndex >= _mapParamName2Value.keys().count()) {
            // We've finished sending the last parameter for the last component, request is complete
            _currentParamRequestListComponentIndex = -1;
        } else {
            _currentParamRequestListParamIndex = 0;
606
        }
607 608 609 610 611 612 613
    }
}

void MockLink::_handleParamSet(const mavlink_message_t& msg)
{
    mavlink_param_set_t request;
    mavlink_msg_param_set_decode(&msg, &request);
614

615
    Q_ASSERT(request.target_system == _vehicleSystemId);
616
    int componentId = request.target_component;
dogmaphobic's avatar
dogmaphobic committed
617

618 619
    // Param may not be null terminated if exactly fits
    char paramId[MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN + 1];
Don Gagne's avatar
Don Gagne committed
620
    paramId[MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN] = 0;
621
    strncpy(paramId, request.param_id, MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN);
622

Don Gagne's avatar
Don Gagne committed
623
    qCDebug(MockLinkLog) << "_handleParamSet" << componentId << paramId << request.param_type;
dogmaphobic's avatar
dogmaphobic committed
624

625 626
    Q_ASSERT(_mapParamName2Value.contains(componentId));
    Q_ASSERT(_mapParamName2Value[componentId].contains(paramId));
627
    Q_ASSERT(request.param_type == _mapParamName2MavParamType[paramId]);
628

629
    // Save the new value
630
    _setParamFloatUnionIntoMap(componentId, paramId, request.param_value);
631

632 633 634
    // Respond with a param_value to ack
    mavlink_message_t responseMsg;
    mavlink_msg_param_value_pack(_vehicleSystemId,
635 636 637 638 639 640 641
                                 componentId,                                               // component id
                                 &responseMsg,                                              // Outgoing message
                                 paramId,                                                   // Parameter name
                                 request.param_value,                                       // Send same value back
                                 request.param_type,                                        // Send same type back
                                 _mapParamName2Value[componentId].count(),                  // Total number of parameters
                                 _mapParamName2Value[componentId].keys().indexOf(paramId)); // Index of this parameter
642
    respondWithMavlinkMessage(responseMsg);
643 644 645 646
}

void MockLink::_handleParamRequestRead(const mavlink_message_t& msg)
{
647
    mavlink_message_t   responseMsg;
648 649
    mavlink_param_request_read_t request;
    mavlink_msg_param_request_read_decode(&msg, &request);
650

Don Gagne's avatar
Don Gagne committed
651
    const QString paramName(QString::fromLocal8Bit(request.param_id, strnlen(request.param_id, MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN)));
652
    int componentId = request.target_component;
653 654

    // special case for magic _HASH_CHECK value
Don Gagne's avatar
Don Gagne committed
655
    if (request.target_component == MAV_COMP_ID_ALL && paramName == "_HASH_CHECK") {
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
        mavlink_param_union_t   valueUnion;
        valueUnion.type = MAV_PARAM_TYPE_UINT32;
        valueUnion.param_uint32 = 0;
        // Special case of magic hash check value
        mavlink_msg_param_value_pack(_vehicleSystemId,
                                     componentId,
                                     &responseMsg,
                                     request.param_id,
                                     valueUnion.param_float,
                                     MAV_PARAM_TYPE_UINT32,
                                     0,
                                     -1);
        respondWithMavlinkMessage(responseMsg);
        return;
    }

672
    Q_ASSERT(_mapParamName2Value.contains(componentId));
673

674 675
    char paramId[MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN + 1];
    paramId[0] = 0;
676

677
    Q_ASSERT(request.target_system == _vehicleSystemId);
678

679 680 681
    if (request.param_index == -1) {
        // Request is by param name. Param may not be null terminated if exactly fits
        strncpy(paramId, request.param_id, MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN);
682
    } else {
683
        // Request is by index
684

685
        Q_ASSERT(request.param_index >= 0 && request.param_index < _mapParamName2Value[componentId].count());
686

687
        QString key = _mapParamName2Value[componentId].keys().at(request.param_index);
688 689
        Q_ASSERT(key.length() <= MAVLINK_MSG_PARAM_REQUEST_READ_FIELD_PARAM_ID_LEN);
        strcpy(paramId, key.toLocal8Bit().constData());
690
    }
691

692
    Q_ASSERT(_mapParamName2Value[componentId].contains(paramId));
693
    Q_ASSERT(_mapParamName2MavParamType.contains(paramId));
694

Don Gagne's avatar
Don Gagne committed
695 696 697 698 699 700
    if (_failureMode == MockConfiguration::FailMissingParamOnAllRequests && strcmp(paramId, _failParam) == 0) {
        qCDebug(MockLinkLog) << "Ignoring request read for " << _failParam;
        // Fail to send this param no matter what
        return;
    }

701
    mavlink_msg_param_value_pack(_vehicleSystemId,
702 703 704 705 706 707 708
                                 componentId,                                               // component id
                                 &responseMsg,                                              // Outgoing message
                                 paramId,                                                   // Parameter name
                                 _floatUnionForParam(componentId, paramId),                 // Parameter value
                                 _mapParamName2MavParamType[paramId],                       // Parameter type
                                 _mapParamName2Value[componentId].count(),                  // Total number of parameters
                                 _mapParamName2Value[componentId].keys().indexOf(paramId)); // Index of this parameter
709
    respondWithMavlinkMessage(responseMsg);
710 711
}

712 713 714
void MockLink::emitRemoteControlChannelRawChanged(int channel, uint16_t raw)
{
    uint16_t chanRaw[18];
dogmaphobic's avatar
dogmaphobic committed
715

716 717 718 719
    for (int i=0; i<18; i++) {
        chanRaw[i] = UINT16_MAX;
    }
    chanRaw[channel] = raw;
dogmaphobic's avatar
dogmaphobic committed
720

721 722 723 724 725 726 727
    mavlink_message_t responseMsg;
    mavlink_msg_rc_channels_pack(_vehicleSystemId,
                                 _vehicleComponentId,
                                 &responseMsg,          // Outgoing message
                                 0,                     // time since boot, ignored
                                 18,                    // channel count
                                 chanRaw[0],            // channel raw value
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
            chanRaw[1],            // channel raw value
            chanRaw[2],            // channel raw value
            chanRaw[3],            // channel raw value
            chanRaw[4],            // channel raw value
            chanRaw[5],            // channel raw value
            chanRaw[6],            // channel raw value
            chanRaw[7],            // channel raw value
            chanRaw[8],            // channel raw value
            chanRaw[9],            // channel raw value
            chanRaw[10],           // channel raw value
            chanRaw[11],           // channel raw value
            chanRaw[12],           // channel raw value
            chanRaw[13],           // channel raw value
            chanRaw[14],           // channel raw value
            chanRaw[15],           // channel raw value
            chanRaw[16],           // channel raw value
            chanRaw[17],           // channel raw value
            0);                    // rss
746 747 748 749 750 751 752
    respondWithMavlinkMessage(responseMsg);
}

void MockLink::_handleFTP(const mavlink_message_t& msg)
{
    Q_ASSERT(_fileServer);
    _fileServer->handleFTPMessage(msg);
753
}
754 755 756 757

void MockLink::_handleCommandLong(const mavlink_message_t& msg)
{
    mavlink_command_long_t request;
758
    uint8_t commandResult = MAV_RESULT_UNSUPPORTED;
dogmaphobic's avatar
dogmaphobic committed
759

760 761
    mavlink_msg_command_long_decode(&msg, &request);

762 763
    switch (request.command) {
    case MAV_CMD_COMPONENT_ARM_DISARM:
764 765 766 767 768
        if (request.param1 == 0.0f) {
            _mavBaseMode &= ~MAV_MODE_FLAG_SAFETY_ARMED;
        } else {
            _mavBaseMode |= MAV_MODE_FLAG_SAFETY_ARMED;
        }
769
        commandResult = MAV_RESULT_ACCEPTED;
770 771
        break;
    case MAV_CMD_PREFLIGHT_CALIBRATION:
772 773 774
        _handlePreFlightCalibration(request);
        commandResult = MAV_RESULT_ACCEPTED;
        break;
775 776 777
    case MAV_CMD_PREFLIGHT_STORAGE:
        commandResult = MAV_RESULT_ACCEPTED;
        break;
778 779 780 781
    case MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES:
        commandResult = MAV_RESULT_ACCEPTED;
        _respondWithAutopilotVersion();
        break;
782
    }
783 784 785 786 787 788 789 790

    mavlink_message_t commandAck;
    mavlink_msg_command_ack_pack(_vehicleSystemId,
                                 _vehicleComponentId,
                                 &commandAck,
                                 request.command,
                                 commandResult);
    respondWithMavlinkMessage(commandAck);
791 792
}

793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
void MockLink::_respondWithAutopilotVersion(void)
{
    mavlink_message_t msg;

    uint8_t customVersion[8];
    memset(customVersion, 0, sizeof(customVersion));

    // Only flight_sw_version is supported a this point
    mavlink_msg_autopilot_version_pack(_vehicleSystemId,
                                       _vehicleComponentId,
                                       &msg,
                                       0,                                           // capabilities,
                                       (1 << (8*3)) | FIRMWARE_VERSION_TYPE_DEV,    // flight_sw_version,
                                       0,                                           // middleware_sw_version,
                                       0,                                           // os_sw_version,
                                       0,                                           // board_version,
                                       (uint8_t *)&customVersion,                   // flight_custom_version,
                                       (uint8_t *)&customVersion,                   // middleware_custom_version,
                                       (uint8_t *)&customVersion,                   // os_custom_version,
                                       0,                                           // vendor_id,
                                       0,                                           // product_id,
                                       0);                                          // uid
    respondWithMavlinkMessage(msg);
}

818
void MockLink::setMissionItemFailureMode(MockLinkMissionItemHandler::FailureMode_t failureMode)
819
{
820
    _missionItemHandler.setMissionItemFailureMode(failureMode);
821
}
822 823 824

void MockLink::_sendHomePosition(void)
{
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
    mavlink_message_t msg;

    float bogus[4];
    bogus[0] = 0.0f;
    bogus[1] = 0.0f;
    bogus[2] = 0.0f;
    bogus[3] = 0.0f;

    mavlink_msg_home_position_pack(_vehicleSystemId,
                                   _vehicleComponentId,
                                   &msg,
                                   (int32_t)(_vehicleLatitude * 1E7),
                                   (int32_t)(_vehicleLongitude * 1E7),
                                   (int32_t)(_vehicleAltitude * 1000),
                                   0.0f, 0.0f, 0.0f,
                                   &bogus[0],
            0.0f, 0.0f, 0.0f);
    respondWithMavlinkMessage(msg);
843
}
Don Gagne's avatar
Don Gagne committed
844 845 846 847 848 849 850 851 852 853 854

void MockLink::_sendGpsRawInt(void)
{
    static uint64_t timeTick = 0;
    mavlink_message_t msg;

    mavlink_msg_gps_raw_int_pack(_vehicleSystemId,
                                 _vehicleComponentId,
                                 &msg,
                                 timeTick++,                            // time since boot
                                 3,                                     // 3D fix
dogmaphobic's avatar
dogmaphobic committed
855
                                 (int32_t)(_vehicleLatitude  * 1E7),
Don Gagne's avatar
Don Gagne committed
856
                                 (int32_t)(_vehicleLongitude * 1E7),
dogmaphobic's avatar
dogmaphobic committed
857
                                 (int32_t)(_vehicleAltitude  * 1000),
Don Gagne's avatar
Don Gagne committed
858 859 860 861 862 863
                                 UINT16_MAX, UINT16_MAX,                // HDOP/VDOP not known
                                 UINT16_MAX,                            // velocity not known
                                 UINT16_MAX,                            // course over ground not known
                                 8);                                    // satellite count
    respondWithMavlinkMessage(msg);
}
864

865 866 867 868 869 870 871 872
void MockLink::_sendStatusTextMessages(void)
{
    struct StatusMessage {
        MAV_SEVERITY        severity;
        const char*         msg;
    };

    static const struct StatusMessage rgMessages[] = {
873 874 875 876 877 878 879 880 881 882
    { MAV_SEVERITY_INFO,        "#Testing audio output" },
    { MAV_SEVERITY_EMERGENCY,   "Status text emergency" },
    { MAV_SEVERITY_ALERT,       "Status text alert" },
    { MAV_SEVERITY_CRITICAL,    "Status text critical" },
    { MAV_SEVERITY_ERROR,       "Status text error" },
    { MAV_SEVERITY_WARNING,     "Status text warning" },
    { MAV_SEVERITY_NOTICE,      "Status text notice" },
    { MAV_SEVERITY_INFO,        "Status text info" },
    { MAV_SEVERITY_DEBUG,       "Status text debug" },
};
883 884 885 886 887 888 889 890 891 892 893 894 895 896

    for (size_t i=0; i<sizeof(rgMessages)/sizeof(rgMessages[0]); i++) {
        mavlink_message_t msg;
        const struct StatusMessage* status = &rgMessages[i];

        mavlink_msg_statustext_pack(_vehicleSystemId,
                                    _vehicleComponentId,
                                    &msg,
                                    status->severity,
                                    status->msg);
        respondWithMavlinkMessage(msg);
    }
}

897 898 899
MockConfiguration::MockConfiguration(const QString& name)
    : LinkConfiguration(name)
    , _firmwareType(MAV_AUTOPILOT_PX4)
900
    , _vehicleType(MAV_TYPE_QUADROTOR)
901
    , _sendStatusText(false)
Don Gagne's avatar
Don Gagne committed
902
    , _failureMode(FailNone)
903 904 905 906 907 908 909
{

}

MockConfiguration::MockConfiguration(MockConfiguration* source)
    : LinkConfiguration(source)
{
910
    _firmwareType =     source->_firmwareType;
dogmaphobic's avatar
dogmaphobic committed
911
    _vehicleType =      source->_vehicleType;
912
    _sendStatusText =   source->_sendStatusText;
Don Gagne's avatar
Don Gagne committed
913
    _failureMode =      source->_failureMode;
914 915 916 917 918 919
}

void MockConfiguration::copyFrom(LinkConfiguration *source)
{
    LinkConfiguration::copyFrom(source);
    MockConfiguration* usource = dynamic_cast<MockConfiguration*>(source);
920 921 922 923 924 925 926

    if (!usource) {
        qWarning() << "dynamic_cast failed" << source << usource;
        return;
    }

    _firmwareType =     usource->_firmwareType;
927
    _vehicleType =      usource->_vehicleType;
928
    _sendStatusText =   usource->_sendStatusText;
Don Gagne's avatar
Don Gagne committed
929
    _failureMode =      usource->_failureMode;
930 931 932 933 934 935
}

void MockConfiguration::saveSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
    settings.setValue(_firmwareTypeKey, (int)_firmwareType);
936
    settings.setValue(_vehicleTypeKey, (int)_vehicleType);
937
    settings.setValue(_sendStatusTextKey, _sendStatusText);
Don Gagne's avatar
Don Gagne committed
938
    settings.setValue(_failureModeKey, (int)_failureMode);
939 940 941 942 943 944 945 946
    settings.sync();
    settings.endGroup();
}

void MockConfiguration::loadSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
    _firmwareType = (MAV_AUTOPILOT)settings.value(_firmwareTypeKey, (int)MAV_AUTOPILOT_PX4).toInt();
947
    _vehicleType = (MAV_TYPE)settings.value(_vehicleTypeKey, (int)MAV_TYPE_QUADROTOR).toInt();
948
    _sendStatusText = settings.value(_sendStatusTextKey, false).toBool();
Don Gagne's avatar
Don Gagne committed
949
    _failureMode = (FailureMode_t)settings.value(_failureModeKey, (int)FailNone).toInt();
950 951 952 953 954 955 956 957 958
    settings.endGroup();
}

void MockConfiguration::updateSettings()
{
    if (_link) {
        MockLink* ulink = dynamic_cast<MockLink*>(_link);
        if (ulink) {
            // Restart connect not supported
959
            qWarning() << "updateSettings not supported";
960 961 962 963
            //ulink->_restartConnection();
        }
    }
}
964 965 966 967 968 969 970 971 972 973 974

MockLink*  MockLink::_startMockLink(MockConfiguration* mockConfig)
{
    LinkManager* linkManager = qgcApp()->toolbox()->linkManager();

    mockConfig->setDynamic(true);
    linkManager->linkConfigurations()->append(mockConfig);

    return qobject_cast<MockLink*>(linkManager->createConnectedLink(mockConfig));
}

Don Gagne's avatar
Don Gagne committed
975
MockLink*  MockLink::startPX4MockLink(bool sendStatusText, MockConfiguration::FailureMode_t failureMode)
976 977 978 979 980 981
{
    MockConfiguration* mockConfig = new MockConfiguration("PX4 MockLink");

    mockConfig->setFirmwareType(MAV_AUTOPILOT_PX4);
    mockConfig->setVehicleType(MAV_TYPE_QUADROTOR);
    mockConfig->setSendStatusText(sendStatusText);
Don Gagne's avatar
Don Gagne committed
982
    mockConfig->setFailureMode(failureMode);
983 984 985 986

    return _startMockLink(mockConfig);
}

Don Gagne's avatar
Don Gagne committed
987
MockLink*  MockLink::startGenericMockLink(bool sendStatusText, MockConfiguration::FailureMode_t failureMode)
988 989 990 991 992 993
{
    MockConfiguration* mockConfig = new MockConfiguration("Generic MockLink");

    mockConfig->setFirmwareType(MAV_AUTOPILOT_GENERIC);
    mockConfig->setVehicleType(MAV_TYPE_QUADROTOR);
    mockConfig->setSendStatusText(sendStatusText);
Don Gagne's avatar
Don Gagne committed
994
    mockConfig->setFailureMode(failureMode);
995 996 997 998

    return _startMockLink(mockConfig);
}

Don Gagne's avatar
Don Gagne committed
999
MockLink*  MockLink::startAPMArduCopterMockLink(bool sendStatusText, MockConfiguration::FailureMode_t failureMode)
1000 1001 1002 1003 1004 1005
{
    MockConfiguration* mockConfig = new MockConfiguration("APM ArduCopter MockLink");

    mockConfig->setFirmwareType(MAV_AUTOPILOT_ARDUPILOTMEGA);
    mockConfig->setVehicleType(MAV_TYPE_QUADROTOR);
    mockConfig->setSendStatusText(sendStatusText);
Don Gagne's avatar
Don Gagne committed
1006
    mockConfig->setFailureMode(failureMode);
1007 1008 1009 1010

    return _startMockLink(mockConfig);
}

Don Gagne's avatar
Don Gagne committed
1011
MockLink*  MockLink::startAPMArduPlaneMockLink(bool sendStatusText, MockConfiguration::FailureMode_t failureMode)
1012 1013 1014 1015 1016 1017
{
    MockConfiguration* mockConfig = new MockConfiguration("APM ArduPlane MockLink");

    mockConfig->setFirmwareType(MAV_AUTOPILOT_ARDUPILOTMEGA);
    mockConfig->setVehicleType(MAV_TYPE_FIXED_WING);
    mockConfig->setSendStatusText(sendStatusText);
Don Gagne's avatar
Don Gagne committed
1018
    mockConfig->setFailureMode(failureMode);
1019 1020 1021 1022

    return _startMockLink(mockConfig);
}

Don Gagne's avatar
Don Gagne committed
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
void MockLink::_sendRCChannels(void)
{
    mavlink_message_t   msg;

    mavlink_msg_rc_channels_pack(_vehicleSystemId,
                                 _vehicleComponentId,
                                 &msg,
                                 0,                     // time_boot_ms
                                 8,                     // chancount
                                 1500,                  // chan1_raw
                                 1500,                  // chan2_raw
                                 1500,                  // chan3_raw
                                 1500,                  // chan4_raw
                                 1500,                  // chan5_raw
                                 1500,                  // chan6_raw
                                 1500,                  // chan7_raw
                                 1500,                  // chan8_raw
                                 UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX,
                                 0);                    // rssi

    respondWithMavlinkMessage(msg);

}
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

void MockLink::_handlePreFlightCalibration(const mavlink_command_long_t& request)
{
    const char* pCalMessage;
    static const char* gyroCalResponse = "[cal] calibration started: 2 gyro";
    static const char* magCalResponse = "[cal] calibration started: 2 mag";
    static const char* accelCalResponse = "[cal] calibration started: 2 accel";

    if (request.param1 == 1) {
        // Gyro cal
        pCalMessage = gyroCalResponse;
    } else if (request.param2 == 1) {
        // Mag cal
        pCalMessage = magCalResponse;
    } else if (request.param5 == 1) {
        // Accel cal
        pCalMessage = accelCalResponse;
    } else {
        return;
    }

    mavlink_message_t msg;
    mavlink_msg_statustext_pack(_vehicleSystemId,
                                _vehicleComponentId,
                                &msg,
                                MAV_SEVERITY_INFO,
                                pCalMessage);
    respondWithMavlinkMessage(msg);
}