@@ -498,14 +498,18 @@ bool AP_Mission::start_command(const Mission_Command& cmd)
498
498
// / cmd.index is updated with it's new position in the mission
499
499
bool AP_Mission::add_cmd (Mission_Command& cmd)
500
500
{
501
+ // Home is always the index 0.
502
+ // Commands should be added after home.
503
+ const uint16_t index = MAX (_cmd_total, AP_MISSION_FIRST_REAL_COMMAND);
504
+
501
505
// attempt to write the command to storage
502
- bool ret = write_cmd_to_storage (_cmd_total , cmd);
506
+ bool ret = write_cmd_to_storage (index , cmd);
503
507
504
508
if (ret) {
505
509
// update command's index
506
- cmd.index = _cmd_total ;
510
+ cmd.index = index ;
507
511
// increment total number of commands
508
- _cmd_total.set_and_save (_cmd_total + 1 );
512
+ _cmd_total.set_and_save (index + 1 );
509
513
}
510
514
511
515
return ret;
@@ -516,8 +520,8 @@ bool AP_Mission::add_cmd(Mission_Command& cmd)
516
520
// / returns true if successfully replaced, false on failure
517
521
bool AP_Mission::replace_cmd (uint16_t index, const Mission_Command& cmd)
518
522
{
519
- // sanity check index
520
- if (index >= (unsigned )_cmd_total) {
523
+ // sanity check index, can't replace home or a waypoint which does not exist
524
+ if ((index == 0 ) || index >= (unsigned )_cmd_total) {
521
525
return false ;
522
526
}
523
527
@@ -704,11 +708,19 @@ bool AP_Mission::restart_current_nav_cmd()
704
708
// returns false on any issue at all.
705
709
bool AP_Mission::set_item (uint16_t index, mavlink_mission_item_int_t & src_packet)
706
710
{
711
+ // Cannot set home
712
+ if (index < AP_MISSION_FIRST_REAL_COMMAND) {
713
+ return false ;
714
+ }
715
+
707
716
// this is the on-storage format
708
717
AP_Mission::Mission_Command cmd {};
709
718
719
+ // Missions start at 1
720
+ const uint16_t mission_index = MAX (num_commands (), AP_MISSION_FIRST_REAL_COMMAND);
721
+
710
722
// can't handle request for anything bigger than the mission size+1...
711
- if (index > num_commands () ) {
723
+ if (index > mission_index ) {
712
724
return false ;
713
725
}
714
726
@@ -719,7 +731,7 @@ bool AP_Mission::set_item(uint16_t index, mavlink_mission_item_int_t& src_packet
719
731
720
732
// A request to set the 'next' item after the end is how we add an extra
721
733
// item to the list, thus allowing us to write entire missions if needed.
722
- if (index == num_commands () ) {
734
+ if (index == mission_index ) {
723
735
return add_cmd (cmd);
724
736
}
725
737
0 commit comments