QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
PlanManager.cc
Go to the documentation of this file.
1#include "PlanManager.h"
2
3#include "AppMessages.h"
4#include "FirmwarePlugin.h"
5#include "MAVLinkLib.h"
6#include "MAVLinkProtocol.h"
9#include "Vehicle.h"
10#include "VehicleLinkManager.h"
11
12QGC_LOGGING_CATEGORY(PlanManagerLog, "PlanManager.PlanManager")
13
14PlanManager::PlanManager(Vehicle* vehicle, MAV_MISSION_TYPE planType)
15 : QObject (vehicle)
16 , _vehicle (vehicle)
17 , _planType (planType)
18 , _ackTimeoutTimer (nullptr)
21 , _resumeMission (false)
26{
27 _ackTimeoutTimer = new QTimer(this);
28 _ackTimeoutTimer->setSingleShot(true);
29
30 connect(_ackTimeoutTimer, &QTimer::timeout, this, &PlanManager::_ackTimeout);
31}
32
37
39{
41
42 emit progressPctChanged(0);
43
44 qCDebug(PlanManagerLog) << QStringLiteral("writeMissionItems %1 count:").arg(_planTypeString()) << _writeMissionItems.count();
45
46 // Prime write list
47 _itemIndicesToWrite.clear();
48 for (int i=0; i<_writeMissionItems.count(); i++) {
50 }
51
52 _retryCount = 0;
53 _setTransactionInProgress(TransactionWrite);
56}
57
58
59void PlanManager::writeMissionItems(const QList<MissionItem*>& missionItems)
60{
61 if (_vehicle->isOfflineEditingVehicle()) {
62 return;
63 }
64
65 if (inProgress()) {
66 qCDebug(PlanManagerLog) << QStringLiteral("writeMissionItems %1 called while transaction in progress").arg(_planTypeString());
67 return;
68 }
69
71
72 bool skipFirstItem = _planType == MAV_MISSION_TYPE_MISSION && !_vehicle->firmwarePlugin()->sendHomePositionToVehicle();
73
74 if (skipFirstItem && missionItems.count() > 0) {
75 // First item is not going to be moved to _writeMissionItems, free it now.
76 delete missionItems[0];
77 }
78
79 int firstIndex = skipFirstItem ? 1 : 0;
80
81 for (int i=firstIndex; i<missionItems.count(); i++) {
82 MissionItem* item = missionItems[i];
83 _writeMissionItems.append(item); // PlanManager takes control of passed MissionItem
84
85 item->setIsCurrentItem(i == firstIndex);
86
87 if (skipFirstItem) {
88 // Home is in sequence 0, remainder of items start at sequence 1
89 item->setSequenceNumber(item->sequenceNumber() - 1);
90 if (item->command() == MAV_CMD_DO_JUMP) {
91 item->setParam1((int)item->param1() - 1);
92 }
93 }
94 }
95
97}
98
101{
102 qCDebug(PlanManagerLog) << QStringLiteral("_writeMissionCount %1 count:_retryCount").arg(_planTypeString()) << _writeMissionItems.count() << _retryCount;
103
104 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
105 if (sharedLink) {
106 mavlink_message_t message;
107
108 mavlink_msg_mission_count_pack_chan(
109 MAVLinkProtocol::instance()->getSystemId(),
111 sharedLink->mavlinkChannel(),
112 &message,
113 _vehicle->id(),
114 MAV_COMP_ID_AUTOPILOT1,
115 _writeMissionItems.count(),
116 _planType,
117 0
118 );
119
120 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), message);
121 }
123}
124
126{
127 if (_vehicle->isOfflineEditingVehicle()) {
128 return;
129 }
130
131 qCDebug(PlanManagerLog) << QStringLiteral("loadFromVehicle %1 read sequence").arg(_planTypeString());
132
133 if (inProgress()) {
134 qCDebug(PlanManagerLog) << QStringLiteral("loadFromVehicle %1 called while transaction in progress").arg(_planTypeString());
135 return;
136 }
137
138 _retryCount = 0;
139 _setTransactionInProgress(TransactionRead);
141 _requestList();
142}
143
146{
147 qCDebug(PlanManagerLog) << QStringLiteral("_requestList %1 _planType:_retryCount").arg(_planTypeString()) << _planType << _retryCount;
148
149 _itemIndicesToRead.clear();
151
152 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
153 if (sharedLink){
154 mavlink_message_t message;
155 mavlink_msg_mission_request_list_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
157 sharedLink->mavlinkChannel(),
158 &message,
159 _vehicle->id(),
160 MAV_COMP_ID_AUTOPILOT1,
161 _planType);
162
163 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), message);
164 }
166}
167
168void PlanManager::_ackTimeout(void)
169{
170 if (_expectedAck == AckNone) {
171 return;
172 }
173
174 switch (_expectedAck) {
175 case AckNone:
176 qCWarning(PlanManagerLog) << QStringLiteral("_ackTimeout %1 timeout with AckNone").arg(_planTypeString());
177 _sendError(InternalError, tr("Internal error occurred during Mission Item communication: _ackTimeOut:_expectedAck == AckNone"));
178 break;
179 case AckMissionCount:
180 // MISSION_COUNT message expected
182 _sendError(MaxRetryExceeded, tr("Mission request list failed, maximum retries exceeded."));
183 _finishTransaction(false);
184 } else {
185 _retryCount++;
186 qCDebug(PlanManagerLog) << tr("Retrying %1 REQUEST_LIST retry Count").arg(_planTypeString()) << _retryCount;
187 _requestList();
188 }
189 break;
190 case AckMissionItem:
191 // MISSION_ITEM expected
193 _sendError(MaxRetryExceeded, tr("Mission read failed, maximum retries exceeded."));
194 _finishTransaction(false);
195 } else {
196 _retryCount++;
197 qCDebug(PlanManagerLog) << tr("Retrying %1 MISSION_REQUEST retry Count").arg(_planTypeString()) << _retryCount;
199 }
200 break;
202 // MISSION_REQUEST is expected, or MISSION_ACK to end sequence
203 if (_itemIndicesToWrite.count() == 0) {
204 if (_writeMissionItems.isEmpty() || _planType != MAV_MISSION_TYPE_MISSION) {
205 // Nothing to resend for an empty mission. For fence and rally PX4 can answer a resent last item
206 // with a success ack even though storing the plan failed, so don't recover those.
207 _sendError(ProtocolError, tr("Mission write failed, vehicle failed to send final ack."));
208 _finishTransaction(false);
209 } else if (_retryCount >= _maxRetryCount) {
210 _sendError(MaxRetryExceeded, tr("Mission write failed, maximum retries exceeded waiting for final ack."));
211 _finishTransaction(false);
212 } else {
213 // The vehicle may have stored the mission and only the ack was lost. PX4 answers a resent last
214 // item with another ack. The vehicle only recognizes the last item as the duplicate, so resend
215 // that one rather than the last item it happened to request.
216 _retryCount++;
217 qCDebug(PlanManagerLog) << QStringLiteral("Retrying %1 final ack by resending last item, retry Count").arg(_planTypeString()) << _retryCount;
219 }
220 } else if (_itemIndicesToWrite[0] == 0) {
221 // Vehicle did not respond to MISSION_COUNT, try again
223 _sendError(MaxRetryExceeded, tr("Mission write mission count failed, maximum retries exceeded."));
224 _finishTransaction(false);
225 } else {
226 _retryCount++;
227 qCDebug(PlanManagerLog) << QStringLiteral("Retrying %1 MISSION_COUNT retry Count").arg(_planTypeString()) << _retryCount;
229 }
230 } else {
231 // Vehicle did not request all items from ground station
232 _sendError(ProtocolError, tr("Vehicle did not request all items from ground station: %1").arg(_ackTypeToString(_expectedAck)));
234 _finishTransaction(false);
235 }
236 break;
238 // MISSION_ACK expected
240 _sendError(MaxRetryExceeded, tr("Mission remove all, maximum retries exceeded."));
241 _finishTransaction(false);
242 } else {
243 _retryCount++;
244 qCDebug(PlanManagerLog) << tr("Retrying %1 MISSION_CLEAR_ALL retry Count").arg(_planTypeString()) << _retryCount;
246 }
247 break;
248 case AckGuidedItem:
249 // MISSION_REQUEST is expected, or MISSION_ACK to end sequence
250 default:
251 _sendError(AckTimeoutError, tr("Vehicle did not respond to mission item communication: %1").arg(_ackTypeToString(_expectedAck)));
253 _finishTransaction(false);
254 }
255}
256
258{
259 // Use much shorter timeouts in unit tests since MockLink responds instantly
260 const int retryTimeout = QGC::runningUnitTests() ? 10 : _retryTimeoutMilliseconds;
262
263 switch (ack) {
264 case AckMissionItem:
265 // We are actively trying to get the mission item, so we don't want to wait as long.
266 _ackTimeoutTimer->setInterval(retryTimeout);
267 break;
268 case AckNone:
269 // FALLTHROUGH
270 case AckMissionCount:
271 // FALLTHROUGH
273 // FALLTHROUGH
275 // FALLTHROUGH
276 case AckGuidedItem:
277 _ackTimeoutTimer->setInterval(ackTimeout);
278 break;
279 }
280
281 _expectedAck = ack;
282 _ackTimeoutTimer->start();
283}
284
288{
289 if (receivedAck == _expectedAck) {
291 _ackTimeoutTimer->stop();
292 return true;
293 } else {
294 if (_expectedAck == AckNone) {
295 // Don't worry about unexpected mission commands, just ignore them; ArduPilot updates home position using
296 // spurious MISSION_ITEMs.
297 } else {
298 // We just warn in this case, this could be crap left over from a previous transaction or the vehicle going bonkers.
299 // Whatever it is we let the ack timeout handle any error output to the user.
300 qCDebug(PlanManagerLog) << QString("Out of sequence ack %1 expected:received %2:%3").arg(_planTypeString()).arg(_ackTypeToString(_expectedAck)).arg(_ackTypeToString(receivedAck));
301 }
302 return false;
303 }
304}
305
307{
308 qCDebug(PlanManagerLog) << "_readTransactionComplete read sequence complete";
309
310 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
311 if (sharedLink) {
312 mavlink_message_t message;
313
314 mavlink_msg_mission_ack_pack_chan(
315 MAVLinkProtocol::instance()->getSystemId(),
317 sharedLink->mavlinkChannel(),
318 &message,
319 _vehicle->id(),
320 MAV_COMP_ID_AUTOPILOT1,
321 MAV_MISSION_ACCEPTED,
322 _planType,
323 0
324 );
325
326 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), message);
327 }
328
329 _finishTransaction(true);
330}
331
333{
334 mavlink_mission_count_t missionCount;
335
336 mavlink_msg_mission_count_decode(&message, &missionCount);
337
338 if (missionCount.mission_type != _planType) {
339 // if there was a previous transaction with a different mission_type, it can happen that we receive
340 // a stale message here, for example when the MAV ran into a timeout and sent a message twice
341 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionCount %1 Incorrect mission_type received expected:actual").arg(_planTypeString()) << _planType << missionCount.mission_type;
342 return;
343 }
344
346 return;
347 }
348
349 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionCount %1 count:").arg(_planTypeString()) << missionCount.count;
350
351 _retryCount = 0;
352
353 if (missionCount.count == 0) {
355 } else {
356 // Prime read list
357 for (int i=0; i<missionCount.count; i++) {
359 }
360 _missionItemCountToRead = missionCount.count;
362 }
363}
364
366{
367 if (_itemIndicesToRead.count() == 0) {
368 _sendError(InternalError, tr("Internal Error: Call to Vehicle _requestNextMissionItem with no more indices to read"));
369 return;
370 }
371
372 qCDebug(PlanManagerLog) << QStringLiteral("_requestNextMissionItem %1 sequenceNumber:retry").arg(_planTypeString()) << _itemIndicesToRead[0] << _retryCount;
373
374 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
375 if (sharedLink) {
376 mavlink_message_t message;
377
378 mavlink_msg_mission_request_int_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
380 sharedLink->mavlinkChannel(),
381 &message,
382 _vehicle->id(),
383 MAV_COMP_ID_AUTOPILOT1,
385 _planType);
386 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), message);
387 }
389}
390
392{
393 MAV_CMD command;
394 MAV_FRAME frame;
395 MAV_MISSION_TYPE missionType;
396 double param1;
397 double param2;
398 double param3;
399 double param4;
400 double param5;
401 double param6;
402 double param7;
403 bool autoContinue;
404 bool isCurrentItem;
405 int seq;
406
407 mavlink_mission_item_int_t missionItem;
408 mavlink_msg_mission_item_int_decode(&message, &missionItem);
409
410 command = (MAV_CMD)missionItem.command;
411 frame = (MAV_FRAME)missionItem.frame;
412 missionType = (MAV_MISSION_TYPE)missionItem.mission_type;
413 param1 = missionItem.param1;
414 param2 = missionItem.param2;
415 param3 = missionItem.param3;
416 param4 = missionItem.param4;
417 param5 = missionItem.frame == MAV_FRAME_MISSION ? (double)missionItem.x : (double)missionItem.x * 1e-7;
418 param6 = missionItem.frame == MAV_FRAME_MISSION ? (double)missionItem.y : (double)missionItem.y * 1e-7;
419 param7 = (double)missionItem.z;
420 autoContinue = missionItem.autocontinue;
421 isCurrentItem = missionItem.current;
422 seq = missionItem.seq;
423
424 // Check the mission_type field. It can happen that we receive a late duplicate message for a
425 // different mission_type request.
426 if (missionType != _planType) {
427 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionItem %1 dropping spurious item seq:command:missionType").arg(_planTypeString()) << seq << command << missionType;
428 return;
429 }
430
431 // We don't support editing ALT_INT frames so change on the way in.
432 if (frame == MAV_FRAME_GLOBAL_INT) {
433 frame = MAV_FRAME_GLOBAL;
434 } else if (frame == MAV_FRAME_GLOBAL_RELATIVE_ALT_INT) {
435 frame = MAV_FRAME_GLOBAL_RELATIVE_ALT;
436 } else if (frame == MAV_FRAME_GLOBAL_TERRAIN_ALT_INT) {
437 frame = MAV_FRAME_GLOBAL_TERRAIN_ALT;
438 }
439
440 bool ardupilotHomePositionUpdate = false;
442 if (_vehicle->apmFirmware() && seq == 0 && _planType == MAV_MISSION_TYPE_MISSION) {
443 ardupilotHomePositionUpdate = true;
444 } else {
445 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionItem %1 dropping spurious item seq:command:current").arg(_planTypeString()) << seq << command << isCurrentItem;
446 return;
447 }
448 }
449
450 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionItem %1 seq:command:current:ardupilotHomePositionUpdate").arg(_planTypeString()) << seq << command << isCurrentItem << ardupilotHomePositionUpdate;
451
452 if (ardupilotHomePositionUpdate) {
453 QGeoCoordinate newHomePosition(param5, param6, param7);
454 _vehicle->_setHomePosition(newHomePosition);
455 return;
456 }
457
458 if (_itemIndicesToRead.contains(seq)) {
459 _itemIndicesToRead.removeOne(seq);
460
461 MissionItem* item = new MissionItem(seq,
462 command,
463 frame,
464 param1,
465 param2,
466 param3,
467 param4,
468 param5,
469 param6,
470 param7,
471 autoContinue,
472 isCurrentItem,
473 this);
474
475 if (item->command() == MAV_CMD_DO_JUMP && !_vehicle->firmwarePlugin()->sendHomePositionToVehicle()) {
476 // Home is in position 0
477 item->setParam1((int)item->param1() + 1);
478 }
479
480 _missionItems.append(item);
481 } else {
482 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionItem %1 mission item received item index which was not requested, disregrarding:").arg(_planTypeString()) << seq;
483 // We have to put the ack timeout back since it was removed above
485 return;
486 }
487
488 emit progressPctChanged((double)seq / (double)_missionItemCountToRead);
489
490 _retryCount = 0;
491 if (_itemIndicesToRead.count() == 0) {
493 } else {
495 }
496}
497
503
505{
506 MAV_MISSION_TYPE missionRequestMissionType;
507 uint16_t missionRequestSeq;
508
509 mavlink_mission_request_int_t missionRequest;
510 mavlink_msg_mission_request_int_decode(&message, &missionRequest);
511 missionRequestMissionType = static_cast<MAV_MISSION_TYPE>(missionRequest.mission_type);
512 missionRequestSeq = missionRequest.seq;
513
514 if (missionRequestMissionType != _planType) {
515 // if there was a previous transaction with a different mission_type, it can happen that we receive
516 // a stale message here, for example when the MAV ran into a timeout and sent a message twice
517 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionRequest %1 Incorrect mission_type received expected:actual").arg(_planTypeString()) << _planType << missionRequestMissionType;
518 return;
519 }
520
522 return;
523 }
524
525 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionRequest %1 sequenceNumber").arg(_planTypeString()) << missionRequestSeq;
526
527 if (missionRequestSeq > _writeMissionItems.count() - 1) {
528 _sendError(RequestRangeError, tr("Vehicle requested item outside range, count:request %1:%2. Send to Vehicle failed.").arg(_writeMissionItems.count()).arg(missionRequestSeq));
529 _finishTransaction(false);
530 return;
531 }
532
533 emit progressPctChanged((double)missionRequestSeq / (double)_writeMissionItems.count());
534
535 // The vehicle is requesting items, so retries spent on MISSION_COUNT must not count against the final ack.
536 _retryCount = 0;
537
538 _lastMissionRequest = missionRequestSeq;
539 if (!_itemIndicesToWrite.contains(missionRequestSeq)) {
540 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionRequest %1 sequence number requested which has already been sent, sending again:").arg(_planTypeString()) << missionRequestSeq;
541 } else {
542 _itemIndicesToWrite.removeOne(missionRequestSeq);
543 }
544
545 _sendMissionItem(missionRequestSeq);
546}
547
552{
553 MissionItem* item = _writeMissionItems[seq];
554 qCDebug(PlanManagerLog) << QStringLiteral("_sendMissionItem %1 sequenceNumber:command").arg(_planTypeString()) << seq << item->command();
555
556 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
557 if (sharedLink) {
558 mavlink_message_t messageOut;
559
560 mavlink_msg_mission_item_int_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
562 sharedLink->mavlinkChannel(),
563 &messageOut,
564 _vehicle->id(),
565 MAV_COMP_ID_AUTOPILOT1,
566 seq,
567 item->frame(),
568 item->command(),
569 seq == 0,
570 item->autoContinue(),
571 item->param1(),
572 item->param2(),
573 item->param3(),
574 item->param4(),
575 item->frame() == MAV_FRAME_MISSION ? item->param5() : item->param5() * 1e7,
576 item->frame() == MAV_FRAME_MISSION ? item->param6() : item->param6() * 1e7,
577 item->param7(),
578 _planType);
579 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), messageOut);
580 }
582}
583
585{
586 mavlink_mission_ack_t missionAck;
587
588 mavlink_msg_mission_ack_decode(&message, &missionAck);
589 if (missionAck.mission_type != _planType) {
590 // if there was a previous transaction with a different mission_type, it can happen that we receive
591 // a stale message here, for example when the MAV ran into a timeout and sent a message twice
592 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionAck %1 Incorrect mission_type received expected:actual").arg(_planTypeString()) << _planType << missionAck.mission_type;
593 return;
594 }
595
596 if (_vehicle->apmFirmware() && missionAck.type == MAV_MISSION_INVALID_SEQUENCE) {
597 // ArduPilot sends these Acks which can happen just due to noisy links causing duplicated requests being responded to.
598 // As far as I'm concerned this is incorrect protocol implementation but we need to deal with it anyway. So we just
599 // ignore it and if things really go haywire the timeouts will fire to fail the overall transaction.
600 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionAck ArduPilot sending possibly bogus MAV_MISSION_INVALID_SEQUENCE").arg(_planTypeString()) << _planType;
601 return;
602 }
603
604 // Save the retry ack before calling _checkForExpectedAck since we'll need it to determine what
605 // type of a protocol sequence we are in.
606 AckType_t savedExpectedAck = _expectedAck;
607
608 // We can get a MISSION_ACK with an error at any time, so if the Acks don't match it is not
609 // a protocol sequence error. Call _checkForExpectedAck with _retryAck so it will succeed no
610 // matter what.
612 return;
613 }
614
615 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionAck %1 type:").arg(_planTypeString()) << _missionResultToString((MAV_MISSION_RESULT)missionAck.type);
616
617 switch (savedExpectedAck) {
618 case AckNone:
619 // State machine is idle. Vehicle is confused.
620 qCDebug(PlanManagerLog) << QStringLiteral("Vehicle sent unexpected MISSION_ACK message, error: %1").arg(_missionResultToString((MAV_MISSION_RESULT)missionAck.type));
621 break;
622 case AckMissionCount:
623 // MISSION_COUNT message expected
624 // FIXME: Protocol error
625 _sendError(VehicleAckError, _missionResultToString((MAV_MISSION_RESULT)missionAck.type));
626 _finishTransaction(false);
627 break;
628 case AckMissionItem:
629 // MISSION_ITEM expected
630 // FIXME: Protocol error
631 _sendError(VehicleAckError, _missionResultToString((MAV_MISSION_RESULT)missionAck.type));
632 _finishTransaction(false);
633 break;
635 // MISSION_REQUEST is expected, or MAV_MISSION_ACCEPTED to end sequence
636 if (missionAck.type == MAV_MISSION_ACCEPTED) {
637 if (_itemIndicesToWrite.count() == 0) {
638 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionAck write sequence complete %1").arg(_planTypeString());
639 _finishTransaction(true);
640 } else {
641 // FIXME: Protocol error
642 _sendError(VehicleAckError, _missionResultToString((MAV_MISSION_RESULT)missionAck.type));
643 _finishTransaction(false);
644 }
645 } else if (_itemIndicesToWrite.count() == 0 && _retryCount > 0 && missionAck.type == MAV_MISSION_ERROR) {
646 // ArduPilot rejects the resent last item once its upload is complete, so this error says nothing
647 // about the mission itself, which may well have been stored.
648 _sendError(ProtocolError, tr("Mission write could not be confirmed, the vehicle never acknowledged the final item. The mission may have been uploaded, load it from the vehicle to verify."));
649 _finishTransaction(false);
650 } else {
651 _sendError(VehicleAckError, _missionResultToString((MAV_MISSION_RESULT)missionAck.type));
652 _finishTransaction(false);
653 }
654 break;
656 // MAV_MISSION_ACCEPTED expected
657 if (missionAck.type != MAV_MISSION_ACCEPTED) {
658 _sendError(VehicleAckError, tr("Vehicle remove all failed. Error: %1").arg(_missionResultToString((MAV_MISSION_RESULT)missionAck.type)));
659 }
660 _finishTransaction(missionAck.type == MAV_MISSION_ACCEPTED);
661 break;
662 case AckGuidedItem:
663 // MISSION_REQUEST is expected, or MAV_MISSION_ACCEPTED to end sequence
664 if (missionAck.type == MAV_MISSION_ACCEPTED) {
665 qCDebug(PlanManagerLog) << QStringLiteral("_handleMissionAck %1 guided mode item accepted").arg(_planTypeString());
666 _finishTransaction(true, true /* apmGuidedItemWrite */);
667 } else {
668 // FIXME: Protocol error
669 _sendError(VehicleAckError, tr("Vehicle returned error: %1. %2Vehicle did not accept guided item.").arg(_missionResultToString((MAV_MISSION_RESULT)missionAck.type)));
670 _finishTransaction(false, true /* apmGuidedItemWrite */);
671 }
672 break;
673 }
674}
675
677void PlanManager::_mavlinkMessageReceived(const mavlink_message_t& message)
678{
679 switch (message.msgid) {
680 case MAVLINK_MSG_ID_MISSION_COUNT:
681 _handleMissionCount(message);
682 break;
683
684 case MAVLINK_MSG_ID_MISSION_ITEM_INT:
685 _handleMissionItem(message);
686 break;
687
688 case MAVLINK_MSG_ID_MISSION_REQUEST:
689 case MAVLINK_MSG_ID_MISSION_REQUEST_INT:
690 _handleMissionRequest(message);
691 break;
692
693 case MAVLINK_MSG_ID_MISSION_ACK:
694 _handleMissionAck(message);
695 break;
696 }
697}
698
699void PlanManager::_sendError(ErrorCode_t errorCode, const QString& errorMsg)
700{
701 qCDebug(PlanManagerLog) << QStringLiteral("Sending error - _planTypeString(%1) errorCode(%2) errorMsg(%4)").arg(_planTypeString()).arg(errorCode).arg(errorMsg);
702
703 emit error(errorCode, errorMsg);
704}
705
707{
708 switch (ackType) {
709 case AckNone:
710 return QString("No Ack");
711 case AckMissionCount:
712 return QString("MISSION_COUNT");
713 case AckMissionItem:
714 return QString("MISSION_ITEM");
716 return QString("MISSION_REQUEST");
717 case AckGuidedItem:
718 return QString("Guided Mode Item");
719 default:
720 qCWarning(PlanManagerLog) << QStringLiteral("Fell off end of switch statement %1").arg(_planTypeString());
721 return QString("QGC Internal Error");
722 }
723}
724
725QString PlanManager::_lastMissionReqestString(MAV_MISSION_RESULT result)
726{
727 QString prefix;
728 QString postfix;
729
732
733 prefix = tr("Item #%1 Command: %2").arg(_lastMissionRequest).arg(MissionCommandTree::instance()->friendlyName(item->command()));
734
735 switch (result) {
736 case MAV_MISSION_UNSUPPORTED_FRAME:
737 postfix = tr("Frame: %1").arg(item->frame());
738 break;
739 case MAV_MISSION_UNSUPPORTED:
740 // All we need is the prefix
741 break;
742 case MAV_MISSION_INVALID_PARAM1:
743 postfix = tr("Value: %1").arg(item->param1());
744 break;
745 case MAV_MISSION_INVALID_PARAM2:
746 postfix = tr("Value: %1").arg(item->param2());
747 break;
748 case MAV_MISSION_INVALID_PARAM3:
749 postfix = tr("Value: %1").arg(item->param3());
750 break;
751 case MAV_MISSION_INVALID_PARAM4:
752 postfix = tr("Value: %1").arg(item->param4());
753 break;
754 case MAV_MISSION_INVALID_PARAM5_X:
755 postfix = tr("Value: %1").arg(item->param5());
756 break;
757 case MAV_MISSION_INVALID_PARAM6_Y:
758 postfix = tr("Value: %1").arg(item->param6());
759 break;
760 case MAV_MISSION_INVALID_PARAM7:
761 postfix = tr("Value: %1").arg(item->param7());
762 break;
763 case MAV_MISSION_INVALID_SEQUENCE:
764 // All we need is the prefix
765 break;
766 default:
767 break;
768 }
769 }
770
771 return prefix + (postfix.isEmpty() ? QStringLiteral("") : QStringLiteral(" ")) + postfix;
772}
773
774QString PlanManager::_missionResultToString(MAV_MISSION_RESULT result)
775{
776 QString error;
777
778 switch (result) {
779 case MAV_MISSION_ACCEPTED:
780 error = tr("Mission accepted.");
781 break;
782 case MAV_MISSION_ERROR:
783 error = tr("Unspecified error.");
784 break;
785 case MAV_MISSION_UNSUPPORTED_FRAME:
786 error = tr("Coordinate frame is not supported.");
787 break;
788 case MAV_MISSION_UNSUPPORTED:
789 error = tr("Command is not supported.");
790 break;
791 case MAV_MISSION_NO_SPACE:
792 error = tr("Mission item exceeds storage space.");
793 break;
794 case MAV_MISSION_INVALID:
795 error = tr("One of the parameters has an invalid value.");
796 break;
797 case MAV_MISSION_INVALID_PARAM1:
798 error = tr("Param 1 invalid value.");
799 break;
800 case MAV_MISSION_INVALID_PARAM2:
801 error = tr("Param 2 invalid value.");
802 break;
803 case MAV_MISSION_INVALID_PARAM3:
804 error = tr("Param 3 invalid value.");
805 break;
806 case MAV_MISSION_INVALID_PARAM4:
807 error = tr("Param 4 invalid value.");
808 break;
809 case MAV_MISSION_INVALID_PARAM5_X:
810 error = tr("Param 5 invalid value.");
811 break;
812 case MAV_MISSION_INVALID_PARAM6_Y:
813 error = tr("Param 6 invalid value.");
814 break;
815 case MAV_MISSION_INVALID_PARAM7:
816 error = tr("Param 7 invalid value.");
817 break;
818 case MAV_MISSION_INVALID_SEQUENCE:
819 error = tr("Received mission item out of sequence.");
820 break;
821 case MAV_MISSION_DENIED:
822 error = tr("Not accepting any mission commands.");
823 break;
824 default:
825 qCWarning(PlanManagerLog) << QStringLiteral("Fell off end of switch statement %1 %2").arg(_planTypeString()).arg(result);
826 error = tr("Unknown error: %1.").arg(result);
827 break;
828 }
829
830 QString lastRequestString = _lastMissionReqestString(result);
831 if (!lastRequestString.isEmpty()) {
832 error += QStringLiteral(" ") + lastRequestString;
833 }
834
835 return error;
836}
837
838void PlanManager::_finishTransaction(bool success, bool apmGuidedItemWrite)
839{
840 emit progressPctChanged(1);
842
843 _itemIndicesToRead.clear();
844 _itemIndicesToWrite.clear();
845
846 // First thing we do is clear the transaction. This way inProgesss is off when we signal transaction complete.
847 TransactionType_t currentTransactionType = _transactionInProgress;
848 _setTransactionInProgress(TransactionNone);
849
850 switch (currentTransactionType) {
851 case TransactionRead:
852 if (!success) {
853 // Read from vehicle failed, clear partial list
855 }
856 emit newMissionItemsAvailable(false);
857 break;
858 case TransactionWrite:
859 // No need to do anything for ArduPilot guided go to waypoint write
860 if (!apmGuidedItemWrite) {
861 if (success) {
862 // Write succeeded, update internal list to be current
863 if (_planType == MAV_MISSION_TYPE_MISSION) {
866 emit currentIndexChanged(-1);
868 }
870 for (int i=0; i<_writeMissionItems.count(); i++) {
872 }
873 _writeMissionItems.clear();
874 } else {
875 // Write failed, throw out the write list
877 }
878 emit sendComplete(!success /* error */);
879 }
880 break;
882 emit removeAllComplete(!success /* error */);
883 break;
884 default:
885 break;
886 }
887
888 if (_resumeMission) {
889 _resumeMission = false;
890 if (success) {
891 emit resumeMissionReady();
892 } else {
894 }
895 }
896}
897
899{
901}
902
904{
905 qCDebug(PlanManagerLog) << "_removeAllWorker";
906
907 emit progressPctChanged(0);
908
910
911 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
912 if (sharedLink) {
913 mavlink_message_t message;
914
915 mavlink_msg_mission_clear_all_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
917 sharedLink->mavlinkChannel(),
918 &message,
919 _vehicle->id(),
920 MAV_COMP_ID_AUTOPILOT1,
921 _planType);
922 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), message);
923 }
925}
926
928{
929 if (inProgress()) {
930 return;
931 }
932
933 qCDebug(PlanManagerLog) << QStringLiteral("removeAll %1").arg(_planTypeString());
934
936
937 if (_planType == MAV_MISSION_TYPE_MISSION) {
940 emit currentIndexChanged(-1);
942 }
943
944 _retryCount = 0;
945 _setTransactionInProgress(TransactionRemoveAll);
946
948}
949
951{
952 for (int i=0; i<_missionItems.count(); i++) {
953 // Using deleteLater here causes too much transient memory to stack up
954 delete _missionItems[i];
955 }
956 _missionItems.clear();
957}
958
959
961{
962 for (int i=0; i<_writeMissionItems.count(); i++) {
963 // Using deleteLater here causes too much transient memory to stack up
964 delete _writeMissionItems[i];
965 }
966 _writeMissionItems.clear();
967}
968
970{
971 connect(_vehicle, &Vehicle::mavlinkMessageReceived, this, &PlanManager::_mavlinkMessageReceived);
972}
973
975{
976 disconnect(_vehicle, &Vehicle::mavlinkMessageReceived, this, &PlanManager::_mavlinkMessageReceived);
977}
978
980{
981 switch (_planType) {
982 case MAV_MISSION_TYPE_MISSION:
983 return QStringLiteral("T:Mission");
984 case MAV_MISSION_TYPE_FENCE:
985 return QStringLiteral("T:GeoFence");
986 case MAV_MISSION_TYPE_RALLY:
987 return QStringLiteral("T:Rally");
988 default:
989 qWarning() << "Unknown plan type" << _planType;
990 return QStringLiteral("T:Unknown");
991 }
992}
993
994void PlanManager::_setTransactionInProgress(TransactionType_t type)
995{
996 if (_transactionInProgress != type) {
997 qCDebug(PlanManagerLog) << "_setTransactionInProgress" << _planTypeString() << type;
1000 }
1001}
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static int getComponentId()
static MAVLinkProtocol * instance()
static MissionCommandTree * instance()
MAV_CMD command(void) const
Definition MissionItem.h:49
double param5(void) const
Definition MissionItem.h:58
double param7(void) const
Definition MissionItem.h:60
void setParam1(double param1)
MAV_FRAME frame(void) const
Definition MissionItem.h:52
void setIsCurrentItem(bool isCurrentItem)
bool autoContinue(void) const
Definition MissionItem.h:53
double param3(void) const
Definition MissionItem.h:56
double param6(void) const
Definition MissionItem.h:59
double param1(void) const
Definition MissionItem.h:54
int sequenceNumber(void) const
Definition MissionItem.h:51
double param4(void) const
Definition MissionItem.h:57
void setSequenceNumber(int sequenceNumber)
double param2(void) const
Definition MissionItem.h:55
int _currentMissionIndex
bool _resumeMission
QList< MissionItem * > _missionItems
Set of mission items on vehicle.
void resumeMissionUploadFail(void)
QList< int > _itemIndicesToRead
List of mission items which still need to be requested from vehicle.
int _lastMissionRequest
Index of item last requested by MISSION_REQUEST.
TransactionType_t _transactionInProgress
bool _checkForExpectedAck(AckType_t receivedAck)
void _handleMissionRequest(const mavlink_message_t &message)
void currentIndexChanged(int currentIndex)
void lastCurrentIndexChanged(int lastCurrentIndex)
void sendComplete(bool error)
void _handleMissionItem(const mavlink_message_t &message)
void resumeMissionReady(void)
void removeAll(void)
void _clearAndDeleteWriteMissionItems(void)
QTimer * _ackTimeoutTimer
ErrorCode_t
Error codes returned in error signal.
Definition PlanManager.h:45
@ AckTimeoutError
Timed out waiting for response from vehicle.
Definition PlanManager.h:47
@ MaxRetryExceeded
Retry failed.
Definition PlanManager.h:53
@ ProtocolError
Incorrect protocol sequence from vehicle.
Definition PlanManager.h:48
@ RequestRangeError
Vehicle requested item out of range.
Definition PlanManager.h:49
@ VehicleAckError
Vehicle returned error in ack.
Definition PlanManager.h:51
int _missionItemCountToRead
Count of all mission items to read.
static constexpr int kTestAckTimeoutMs
Ack timeout used in unit tests (much shorter for faster tests).
Definition PlanManager.h:65
int _lastCurrentIndex
void newMissionItemsAvailable(bool removeAllRequested)
MAV_MISSION_TYPE _planType
QString _missionResultToString(MAV_MISSION_RESULT result)
QString _lastMissionReqestString(MAV_MISSION_RESULT result)
static constexpr int _maxRetryCount
Definition PlanManager.h:62
void _finishTransaction(bool success, bool apmGuidedItemWrite=false)
void _requestList(void)
Internal call to request list of mission items. May be called during a retry sequence.
void _writeMissionItemsWorker(void)
PlanManager(Vehicle *vehicle, MAV_MISSION_TYPE planType)
void _connectToMavlink(void)
AckType_t _expectedAck
static constexpr int _ackTimeoutMilliseconds
Definition PlanManager.h:59
void _startAckTimeout(AckType_t ack)
void loadFromVehicle(void)
void _sendError(ErrorCode_t errorCode, const QString &errorMsg)
void removeAllComplete(bool error)
void writeMissionItems(const QList< MissionItem * > &missionItems)
QList< int > _itemIndicesToWrite
List of mission items which still need to be written to vehicle.
void _handleMissionAck(const mavlink_message_t &message)
void _removeAllWorker(void)
@ TransactionRemoveAll
Definition PlanManager.h:97
void _clearMissionItems(void)
bool inProgress(void) const
void inProgressChanged(bool inProgress)
QList< MissionItem * > _writeMissionItems
Set of mission items currently being written to vehicle.
void progressPctChanged(double progressPercentPct)
void _clearAndDeleteMissionItems(void)
@ AckMissionItem
MISSION_ITEM expected.
Definition PlanManager.h:87
@ AckMissionRequest
MISSION_REQUEST is expected, or MISSION_ACK to end sequence.
Definition PlanManager.h:88
@ AckMissionCount
MISSION_COUNT message expected.
Definition PlanManager.h:86
@ AckMissionClearAll
MISSION_CLEAR_ALL sent, MISSION_ACK is expected.
Definition PlanManager.h:89
@ AckNone
State machine is idle.
Definition PlanManager.h:85
@ AckGuidedItem
MISSION_ACK expected in response to ArduPilot guided mode single item send.
Definition PlanManager.h:90
QString _planTypeString(void)
static constexpr int _retryTimeoutMilliseconds
Definition PlanManager.h:61
const QList< MissionItem * > & missionItems(void)
Definition PlanManager.h:22
void _requestNextMissionItem(void)
void _writeMissionCount(void)
This begins the write sequence with the vehicle. This may be called during a retry.
QString _ackTypeToString(AckType_t ackType)
void _handleMissionCount(const mavlink_message_t &message)
void _sendMissionItem(int seq)
void _disconnectFromMavlink(void)
Vehicle * _vehicle
void error(int errorCode, const QString &errorMsg)
void _readTransactionComplete(void)
void mavlinkMessageReceived(const mavlink_message_t &message)
bool runningUnitTests()