Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Ardupilot
GitHub Repository: Ardupilot/ardupilot
Path: blob/master/ArduCopter/mode.cpp
9447 views
1
#include "Copter.h"
2
3
/*
4
* High level calls to set and update flight modes logic for individual
5
* flight modes is in control_acro.cpp, control_stabilize.cpp, etc
6
*/
7
8
/*
9
constructor for Mode object
10
*/
11
Mode::Mode(void) :
12
g(copter.g),
13
g2(copter.g2),
14
wp_nav(copter.wp_nav),
15
loiter_nav(copter.loiter_nav),
16
pos_control(copter.pos_control),
17
ahrs(copter.ahrs),
18
attitude_control(copter.attitude_control),
19
motors(copter.motors),
20
channel_roll(copter.channel_roll),
21
channel_pitch(copter.channel_pitch),
22
channel_throttle(copter.channel_throttle),
23
channel_yaw(copter.channel_yaw),
24
G_Dt(copter.G_Dt)
25
{ };
26
27
#if AC_PAYLOAD_PLACE_ENABLED
28
PayloadPlace Mode::payload_place;
29
#endif
30
31
// return the static controller object corresponding to supplied mode
32
Mode *Copter::mode_from_mode_num(const Mode::Number mode)
33
{
34
35
switch (mode) {
36
#if MODE_ACRO_ENABLED
37
case Mode::Number::ACRO:
38
return &mode_acro;
39
#endif
40
41
case Mode::Number::STABILIZE:
42
return &mode_stabilize;
43
44
case Mode::Number::ALT_HOLD:
45
return &mode_althold;
46
47
#if MODE_AUTO_ENABLED
48
case Mode::Number::AUTO:
49
return &mode_auto;
50
#endif
51
52
#if MODE_CIRCLE_ENABLED
53
case Mode::Number::CIRCLE:
54
return &mode_circle;
55
#endif
56
57
#if MODE_LOITER_ENABLED
58
case Mode::Number::LOITER:
59
return &mode_loiter;
60
#endif
61
62
#if MODE_GUIDED_ENABLED
63
case Mode::Number::GUIDED:
64
return &mode_guided;
65
#endif
66
67
case Mode::Number::LAND:
68
return &mode_land;
69
70
#if MODE_RTL_ENABLED
71
case Mode::Number::RTL:
72
return &mode_rtl;
73
#endif
74
75
#if MODE_DRIFT_ENABLED
76
case Mode::Number::DRIFT:
77
return &mode_drift;
78
#endif
79
80
#if MODE_SPORT_ENABLED
81
case Mode::Number::SPORT:
82
return &mode_sport;
83
#endif
84
85
#if MODE_FLIP_ENABLED
86
case Mode::Number::FLIP:
87
return &mode_flip;
88
#endif
89
90
#if AUTOTUNE_ENABLED
91
case Mode::Number::AUTOTUNE:
92
return &mode_autotune;
93
#endif
94
95
#if MODE_POSHOLD_ENABLED
96
case Mode::Number::POSHOLD:
97
return &mode_poshold;
98
#endif
99
100
#if MODE_BRAKE_ENABLED
101
case Mode::Number::BRAKE:
102
return &mode_brake;
103
#endif
104
105
#if MODE_THROW_ENABLED
106
case Mode::Number::THROW:
107
return &mode_throw;
108
#endif
109
110
#if AP_ADSB_AVOIDANCE_ENABLED
111
case Mode::Number::AVOID_ADSB:
112
return &mode_avoid_adsb;
113
#endif
114
115
#if MODE_GUIDED_NOGPS_ENABLED
116
case Mode::Number::GUIDED_NOGPS:
117
return &mode_guided_nogps;
118
#endif
119
120
#if MODE_SMARTRTL_ENABLED
121
case Mode::Number::SMART_RTL:
122
return &mode_smartrtl;
123
#endif
124
125
#if MODE_FLOWHOLD_ENABLED
126
case Mode::Number::FLOWHOLD:
127
return (Mode *)g2.mode_flowhold_ptr;
128
#endif
129
130
#if MODE_FOLLOW_ENABLED
131
case Mode::Number::FOLLOW:
132
return &mode_follow;
133
#endif
134
135
#if MODE_ZIGZAG_ENABLED
136
case Mode::Number::ZIGZAG:
137
return &mode_zigzag;
138
#endif
139
140
#if MODE_SYSTEMID_ENABLED
141
case Mode::Number::SYSTEMID:
142
return (Mode *)g2.mode_systemid_ptr;
143
#endif
144
145
#if MODE_AUTOROTATE_ENABLED
146
case Mode::Number::AUTOROTATE:
147
return &mode_autorotate;
148
#endif
149
150
#if MODE_TURTLE_ENABLED
151
case Mode::Number::TURTLE:
152
return &mode_turtle;
153
#endif
154
155
default:
156
break;
157
}
158
159
#if MODE_GUIDED_ENABLED && AP_SCRIPTING_ENABLED
160
// Check registered custom modes
161
for (uint8_t i = 0; i < ARRAY_SIZE(mode_guided_custom); i++) {
162
if ((mode_guided_custom[i] != nullptr) && (mode_guided_custom[i]->mode_number() == mode)) {
163
return mode_guided_custom[i];
164
}
165
}
166
#endif
167
168
return nullptr;
169
}
170
171
172
// called when an attempt to change into a mode is unsuccessful:
173
void Copter::mode_change_failed(const Mode *mode, const char *reason)
174
{
175
gcs().send_text(MAV_SEVERITY_WARNING, "Mode change to %s failed: %s", mode->name(), reason);
176
LOGGER_WRITE_ERROR(LogErrorSubsystem::FLIGHT_MODE, LogErrorCode(mode->mode_number()));
177
// make sad noise
178
if (copter.ap.initialised) {
179
AP_Notify::events.user_mode_change_failed = 1;
180
}
181
}
182
183
// Check if this mode can be entered from the GCS
184
bool Copter::gcs_mode_enabled(const Mode::Number mode_num)
185
{
186
// List of modes that can be blocked, index is bit number in parameter bitmask
187
static const uint8_t mode_list [] {
188
(uint8_t)Mode::Number::STABILIZE,
189
(uint8_t)Mode::Number::ACRO,
190
(uint8_t)Mode::Number::ALT_HOLD,
191
(uint8_t)Mode::Number::AUTO,
192
(uint8_t)Mode::Number::GUIDED,
193
(uint8_t)Mode::Number::LOITER,
194
(uint8_t)Mode::Number::CIRCLE,
195
(uint8_t)Mode::Number::DRIFT,
196
(uint8_t)Mode::Number::SPORT,
197
(uint8_t)Mode::Number::FLIP,
198
(uint8_t)Mode::Number::AUTOTUNE,
199
(uint8_t)Mode::Number::POSHOLD,
200
(uint8_t)Mode::Number::BRAKE,
201
(uint8_t)Mode::Number::THROW,
202
(uint8_t)Mode::Number::AVOID_ADSB,
203
(uint8_t)Mode::Number::GUIDED_NOGPS,
204
(uint8_t)Mode::Number::SMART_RTL,
205
(uint8_t)Mode::Number::FLOWHOLD,
206
(uint8_t)Mode::Number::FOLLOW,
207
(uint8_t)Mode::Number::ZIGZAG,
208
(uint8_t)Mode::Number::SYSTEMID,
209
(uint8_t)Mode::Number::AUTOROTATE,
210
(uint8_t)Mode::Number::AUTO_RTL,
211
(uint8_t)Mode::Number::TURTLE
212
};
213
214
if (!block_GCS_mode_change((uint8_t)mode_num, mode_list, ARRAY_SIZE(mode_list))) {
215
return true;
216
}
217
218
// Mode disabled, try and grab a mode name to give a better warning.
219
Mode *new_flightmode = mode_from_mode_num(mode_num);
220
if (new_flightmode != nullptr) {
221
mode_change_failed(new_flightmode, "GCS entry disabled (FLTMODE_GCSBLOCK)");
222
} else {
223
notify_no_such_mode((uint8_t)mode_num);
224
}
225
226
return false;
227
}
228
229
// set_mode - change flight mode and perform any necessary initialisation
230
// optional force parameter used to force the flight mode change (used only first time mode is set)
231
// returns true if mode was successfully set
232
// ACRO, STABILIZE, ALTHOLD, LAND, DRIFT and SPORT can always be set successfully but the return state of other flight modes should be checked and the caller should deal with failures appropriately
233
bool Copter::set_mode(Mode::Number mode, ModeReason reason)
234
{
235
// update last reason
236
const ModeReason last_reason = _last_reason;
237
_last_reason = reason;
238
239
// return immediately if we are already in the desired mode
240
if (mode == flightmode->mode_number()) {
241
control_mode_reason = reason;
242
// set yaw rate time constant during autopilot startup
243
if (reason == ModeReason::INITIALISED && mode == Mode::Number::STABILIZE) {
244
attitude_control->set_yaw_rate_tc(g2.command_model_pilot_y.get_rate_tc());
245
}
246
// make happy noise
247
if (copter.ap.initialised && (reason != last_reason)) {
248
AP_Notify::events.user_mode_change = 1;
249
}
250
return true;
251
}
252
253
// Check if GCS mode change is disabled via parameter
254
if ((reason == ModeReason::GCS_COMMAND) && !gcs_mode_enabled(mode)) {
255
return false;
256
}
257
258
#if MODE_AUTO_ENABLED
259
if (mode == Mode::Number::AUTO_RTL) {
260
// Special case for AUTO RTL, not a true mode, just AUTO in disguise
261
// Attempt to join return path, fallback to do-land-start
262
return mode_auto.return_path_or_jump_to_landing_sequence_auto_RTL(reason);
263
}
264
#endif
265
266
Mode *new_flightmode = mode_from_mode_num(mode);
267
if (new_flightmode == nullptr) {
268
notify_no_such_mode((uint8_t)mode);
269
return false;
270
}
271
272
bool ignore_checks = !motors->armed(); // allow switching to any mode if disarmed. We rely on the arming check to perform
273
274
#if FRAME_CONFIG == HELI_FRAME
275
// do not allow helis to enter a non-manual throttle mode if the
276
// rotor runup is not complete
277
if (!ignore_checks && !new_flightmode->has_manual_throttle() && !motors->rotor_runup_complete()) {
278
mode_change_failed(new_flightmode, "runup not complete");
279
return false;
280
}
281
#endif
282
283
#if FRAME_CONFIG != HELI_FRAME
284
// ensure vehicle doesn't leap off the ground if a user switches
285
// into a manual throttle mode from a non-manual-throttle mode
286
// (e.g. user arms in guided, raises throttle to 1300 (not enough to
287
// trigger auto takeoff), then switches into manual):
288
bool user_throttle = new_flightmode->has_manual_throttle();
289
#if MODE_DRIFT_ENABLED
290
if (new_flightmode == &mode_drift) {
291
user_throttle = true;
292
}
293
#endif
294
if (!ignore_checks &&
295
ap.land_complete &&
296
user_throttle &&
297
!copter.flightmode->has_manual_throttle() &&
298
new_flightmode->get_pilot_desired_throttle() > copter.get_non_takeoff_throttle()) {
299
mode_change_failed(new_flightmode, "throttle too high");
300
return false;
301
}
302
#endif
303
304
if (!ignore_checks &&
305
new_flightmode->requires_position() &&
306
!copter.position_ok()) {
307
mode_change_failed(new_flightmode, "requires position");
308
return false;
309
}
310
311
// check for valid altitude if old mode did not require it but new one does
312
// we only want to stop changing modes if it could make things worse
313
if (!ignore_checks &&
314
!copter.ekf_alt_ok() &&
315
flightmode->has_manual_throttle() &&
316
!new_flightmode->has_manual_throttle()) {
317
mode_change_failed(new_flightmode, "need alt estimate");
318
return false;
319
}
320
321
#if AP_FENCE_ENABLED
322
// may not be allowed to change mode if recovering from fence breach
323
if (!ignore_checks &&
324
fence.enabled() &&
325
fence.option_enabled(AC_Fence::OPTIONS::DISABLE_MODE_CHANGE) &&
326
fence.get_breaches() &&
327
motors->armed() &&
328
get_control_mode_reason() == ModeReason::FENCE_BREACHED &&
329
!ap.land_complete) {
330
mode_change_failed(new_flightmode, "in fence recovery");
331
return false;
332
}
333
#endif
334
335
if (rc().in_rc_failsafe() && !new_flightmode->allows_entry_in_rc_failsafe()) {
336
mode_change_failed(new_flightmode, "in RC failsafe");
337
return false;
338
}
339
340
if (!new_flightmode->init(ignore_checks)) {
341
mode_change_failed(new_flightmode, "init failed");
342
return false;
343
}
344
345
// perform any cleanup required by previous flight mode
346
exit_mode(flightmode, new_flightmode);
347
348
// update flight mode
349
flightmode = new_flightmode;
350
control_mode_reason = reason;
351
#if HAL_LOGGING_ENABLED
352
logger.Write_Mode((uint8_t)flightmode->mode_number(), reason);
353
#endif
354
gcs().send_message(MSG_HEARTBEAT);
355
356
#if HAL_ADSB_ENABLED
357
adsb.set_is_auto_mode((mode == Mode::Number::AUTO) || (mode == Mode::Number::RTL) || (mode == Mode::Number::GUIDED));
358
#endif
359
360
#if AP_FENCE_ENABLED
361
if (fence.get_action() != AC_Fence::Action::REPORT_ONLY) {
362
// pilot requested flight mode change during a fence breach indicates pilot is attempting to manually recover
363
// this flight mode change could be automatic (i.e. fence, battery, GPS or GCS failsafe)
364
// but it should be harmless to disable the fence temporarily in these situations as well
365
fence.manual_recovery_start();
366
}
367
#endif
368
369
#if AP_CAMERA_ENABLED
370
camera.set_is_auto_mode(flightmode->mode_number() == Mode::Number::AUTO);
371
#endif
372
373
// set rate shaping time constants
374
#if MODE_ACRO_ENABLED || MODE_SPORT_ENABLED
375
attitude_control->set_roll_pitch_rate_tc(g2.command_model_acro_rp.get_rate_tc());
376
#endif
377
attitude_control->set_yaw_rate_tc(g2.command_model_pilot_y.get_rate_tc());
378
#if MODE_ACRO_ENABLED || MODE_DRIFT_ENABLED
379
if (mode== Mode::Number::ACRO || mode== Mode::Number::DRIFT) {
380
attitude_control->set_yaw_rate_tc(g2.command_model_acro_y.get_rate_tc());
381
}
382
#endif
383
384
// update notify object
385
notify_flight_mode();
386
387
// make happy noise
388
if (copter.ap.initialised) {
389
AP_Notify::events.user_mode_change = 1;
390
}
391
392
// return success
393
return true;
394
}
395
396
bool Copter::set_mode(const uint8_t new_mode, const ModeReason reason)
397
{
398
static_assert(sizeof(Mode::Number) == sizeof(new_mode), "The new mode can't be mapped to the vehicles mode number");
399
#ifdef DISALLOW_GCS_MODE_CHANGE_DURING_RC_FAILSAFE
400
if (reason == ModeReason::GCS_COMMAND && copter.failsafe.radio) {
401
// don't allow mode changes while in radio failsafe
402
return false;
403
}
404
#endif
405
return copter.set_mode(static_cast<Mode::Number>(new_mode), reason);
406
}
407
408
// update_flight_mode - calls the appropriate attitude controllers based on flight mode
409
// called at 100hz or more
410
void Copter::update_flight_mode()
411
{
412
#if AP_RANGEFINDER_ENABLED
413
surface_tracking.invalidate_for_logging(); // invalidate surface tracking alt, flight mode will set to true if used
414
#endif
415
attitude_control->landed_gain_reduction(copter.ap.land_complete); // Adjust gains when landed to attenuate ground oscillation
416
417
// set ekf reset handling method
418
pos_control->set_reset_handling_method(flightmode->move_vehicle_on_ekf_reset() ? AC_PosControl::EKFResetMethod::MoveVehicle : AC_PosControl::EKFResetMethod::MoveTarget);
419
420
flightmode->run();
421
}
422
423
// exit_mode - high level call to organise cleanup as a flight mode is exited
424
void Copter::exit_mode(Mode *&old_flightmode,
425
Mode *&new_flightmode)
426
{
427
// smooth throttle transition when switching from manual to automatic flight modes
428
if (old_flightmode->has_manual_throttle() && !new_flightmode->has_manual_throttle() && motors->armed() && !ap.land_complete) {
429
// this assumes all manual flight modes use get_pilot_desired_throttle to translate pilot input to output throttle
430
set_accel_throttle_I_from_pilot_throttle();
431
}
432
433
// cancel any takeoffs in progress
434
old_flightmode->takeoff_stop();
435
436
// perform cleanup required for each flight mode
437
old_flightmode->exit();
438
439
#if FRAME_CONFIG == HELI_FRAME
440
// firmly reset the flybar passthrough to false when exiting acro mode.
441
if (old_flightmode == &mode_acro) {
442
attitude_control->use_flybar_passthrough(false, false);
443
motors->set_acro_tail(false);
444
}
445
446
//last collective output
447
input_manager.set_last_coll_output(motors->get_throttle());
448
449
// if we are changing from a mode that did not use manual throttle,
450
// collective ramp functions should be called to blend the transition
451
if (new_flightmode->has_manual_throttle()) {
452
input_manager.set_collective_ramp(1.0);
453
}
454
455
// Make sure inverted flight is disabled if not supported in the new mode
456
if (!new_flightmode->allows_inverted()) {
457
attitude_control->set_inverted_flight(false);
458
}
459
#endif //HELI_FRAME
460
}
461
462
// notify_flight_mode - sets notify object based on current flight mode. Only used for OreoLED notify device
463
void Copter::notify_flight_mode() {
464
AP_Notify::flags.autopilot_mode = flightmode->is_autopilot();
465
AP_Notify::flags.flight_mode = (uint8_t)flightmode->mode_number();
466
notify.set_flight_mode_str(flightmode->name4());
467
}
468
469
// get_pilot_desired_angle - transform pilot's roll or pitch input into a desired lean angle
470
// returns desired angle in radians
471
void Mode::get_pilot_desired_lean_angles_rad(float &roll_out_rad, float &pitch_out_rad, float angle_max_rad, float angle_limit_rad) const
472
{
473
// throttle failsafe check
474
if (!rc().has_valid_input()) {
475
roll_out_rad = 0.0;
476
pitch_out_rad = 0.0;
477
return;
478
}
479
480
//transform pilot's normalised roll or pitch stick input into a roll and pitch euler angle command
481
rc_input_to_roll_pitch_rad(channel_roll->norm_input_dz(), channel_pitch->norm_input_dz(), angle_max_rad, angle_limit_rad, roll_out_rad, pitch_out_rad);
482
}
483
484
// transform pilot's roll or pitch input into a desired velocity
485
Vector2f Mode::get_pilot_desired_velocity(float vel_max) const
486
{
487
Vector2f vel;
488
489
if (!rc().has_valid_input()) {
490
return vel;
491
}
492
// fetch roll and pitch inputs
493
float roll_out = channel_roll->norm_input_dz();
494
float pitch_out = channel_pitch->norm_input_dz();
495
496
// convert roll and pitch inputs into velocity in NE frame
497
vel = Vector2f(-pitch_out, roll_out);
498
if (vel.is_zero()) {
499
return vel;
500
}
501
vel = copter.ahrs.body_to_earth2D(vel);
502
503
// Transform square input range to circular output
504
// vel_scalar is the vector to the edge of the +- 1.0 square in the direction of the current input
505
Vector2f vel_scalar = vel / MAX(fabsf(vel.x), fabsf(vel.y));
506
// We scale the output by the ratio of the distance to the square to the unit circle and multiply by vel_max
507
vel *= vel_max / vel_scalar.length();
508
return vel;
509
}
510
511
bool Mode::_TakeOff::triggered_ms(const float target_climb_rate_ms) const
512
{
513
if (!copter.ap.land_complete) {
514
// can't take off if we're already flying
515
return false;
516
}
517
if (target_climb_rate_ms <= 0.0f) {
518
// can't takeoff unless we want to go up...
519
return false;
520
}
521
522
if (copter.motors->get_spool_state() != AP_Motors::SpoolState::THROTTLE_UNLIMITED) {
523
// hold aircraft on the ground until rotor speed runup has finished
524
return false;
525
}
526
527
return true;
528
}
529
530
bool Mode::is_disarmed_or_landed() const
531
{
532
if (!motors->armed() || !copter.ap.auto_armed || copter.ap.land_complete) {
533
return true;
534
}
535
return false;
536
}
537
538
void Mode::zero_throttle_and_relax_ac(bool spool_up)
539
{
540
if (spool_up) {
541
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);
542
} else {
543
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::GROUND_IDLE);
544
}
545
attitude_control->input_euler_angle_roll_pitch_euler_rate_yaw_rad(0.0f, 0.0f, 0.0f);
546
attitude_control->set_throttle_out(0.0f, false, copter.g.throttle_filt);
547
}
548
549
void Mode::zero_throttle_and_hold_attitude()
550
{
551
// run attitude controller
552
attitude_control->input_rate_bf_roll_pitch_yaw_rads(0.0f, 0.0f, 0.0f);
553
attitude_control->set_throttle_out(0.0f, false, copter.g.throttle_filt);
554
}
555
556
// handle situations where the vehicle is on the ground waiting for takeoff
557
// force_throttle_unlimited should be true in cases where we want to keep the motors spooled up
558
// (instead of spooling down to ground idle). This is required for tradheli's in Guided and Auto
559
// where we always want the motor spooled up in Guided or Auto mode. Tradheli's main rotor stops
560
// when spooled down to ground idle.
561
// ultimately it forces the motor interlock to be obeyed in auto and guided modes when on the ground.
562
void Mode::make_safe_ground_handling(bool force_throttle_unlimited)
563
{
564
if (force_throttle_unlimited) {
565
// keep rotors turning
566
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);
567
} else {
568
// spool down to ground idle
569
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::GROUND_IDLE);
570
}
571
572
// aircraft is landed, integrator terms must be reset regardless of spool state
573
attitude_control->reset_rate_controller_I_terms_smoothly();
574
575
switch (motors->get_spool_state()) {
576
case AP_Motors::SpoolState::SHUT_DOWN:
577
case AP_Motors::SpoolState::GROUND_IDLE:
578
// reset yaw targets and rates during idle states
579
attitude_control->reset_yaw_target_and_rate();
580
break;
581
case AP_Motors::SpoolState::SPOOLING_UP:
582
case AP_Motors::SpoolState::THROTTLE_UNLIMITED:
583
case AP_Motors::SpoolState::SPOOLING_DOWN:
584
// while transitioning though active states continue to operate normally
585
break;
586
}
587
588
pos_control->NE_relax_velocity_controller();
589
pos_control->NE_update_controller();
590
pos_control->D_relax_controller(0.0f); // forces throttle output to decay to zero
591
pos_control->D_update_controller();
592
// we may need to move this out
593
attitude_control->input_euler_angle_roll_pitch_euler_rate_yaw_rad(0.0f, 0.0f, 0.0f);
594
}
595
596
/*
597
get a height above ground estimate for landing
598
*/
599
float Mode::get_alt_above_ground_m(void) const
600
{
601
float alt_above_ground_m;
602
if (copter.get_rangefinder_height_interpolated_m(alt_above_ground_m)) {
603
return alt_above_ground_m;
604
}
605
if (!copter.current_loc.initialised()) {
606
// current loc uninitialised during startup, return zero
607
return 0;
608
}
609
if (copter.current_loc.get_alt_m(Location::AltFrame::ABOVE_TERRAIN, alt_above_ground_m)) {
610
return alt_above_ground_m;
611
}
612
613
// Assume the Earth is flat:
614
return copter.current_loc.alt * 0.01;
615
}
616
617
void Mode::land_run_vertical_control(bool pause_descent)
618
{
619
float climb_rate_ms = 0;
620
bool ignore_descent_limit = false;
621
if (!pause_descent) {
622
623
// do not ignore limits until we have slowed down for landing
624
const float land_alt_low_m = copter.mode_land.get_land_alt_low_m();
625
ignore_descent_limit = (MAX(land_alt_low_m, 1) > get_alt_above_ground_m()) || copter.ap.land_complete_maybe;
626
627
float max_land_descent_speed_ms;
628
const float land_speed_high_ms = copter.mode_land.get_land_speed_high_ms();
629
if (land_speed_high_ms > 0) {
630
max_land_descent_speed_ms = land_speed_high_ms;
631
} else {
632
max_land_descent_speed_ms = pos_control->get_max_speed_down_ms();
633
}
634
635
// Don't speed up for landing.
636
const float land_speed_ms = copter.mode_land.get_land_speed_ms();
637
max_land_descent_speed_ms = MAX(max_land_descent_speed_ms, fabsf(land_speed_ms));
638
639
// Compute a vertical velocity demand such that the vehicle approaches land_alt_low. Without the below constraint, this would cause the vehicle to hover at land_alt_low.
640
climb_rate_ms = sqrt_controller(MAX(land_alt_low_m, 1) - get_alt_above_ground_m(), pos_control->D_get_pos_p().kP(), pos_control->D_get_max_accel_mss(), G_Dt);
641
642
// Constrain the demanded vertical velocity so that it is between the configured maximum descent speed and the configured minimum descent speed.
643
climb_rate_ms = constrain_float(climb_rate_ms, -max_land_descent_speed_ms, -fabsf(land_speed_ms));
644
645
#if AC_PRECLAND_ENABLED
646
const bool navigating = pos_control->NE_is_active();
647
bool doing_precision_landing = !copter.ap.land_repo_active && copter.precland.target_acquired() && navigating;
648
649
if (doing_precision_landing) {
650
// prec landing is active
651
Vector2p target_pos_ne_m;
652
float target_error_m = 0.0f;
653
if (copter.precland.get_target_position_m(target_pos_ne_m)) {
654
const Vector2p current_pos_ne_m = pos_control->get_pos_estimate_NED_m().xy();
655
// target is this many m away from the vehicle
656
target_error_m = (target_pos_ne_m - current_pos_ne_m).tofloat().length();
657
}
658
// check if we should descend or not
659
const float max_horiz_pos_error_m = copter.precland.get_max_xy_error_before_descending_m();
660
Vector3f target_pos_meas_ned_m;
661
copter.precland.get_target_position_measurement_NED_m(target_pos_meas_ned_m);
662
if (target_error_m > max_horiz_pos_error_m && !is_zero(max_horiz_pos_error_m)) {
663
// doing precland but too far away from the obstacle
664
// do not descend
665
climb_rate_ms = 0.0f;
666
} else if (target_pos_meas_ned_m.z > 0.35 && target_pos_meas_ned_m.z < 2.0 && !copter.precland.do_fast_descend()) {
667
// very close to the ground and doing prec land, lets slow down to make sure we land on target
668
// compute desired descent velocity
669
const float precland_acceptable_error_m = 0.15;
670
const float precland_min_descent_speed_ms = 0.1;
671
const float max_descent_speed_ms = fabsf(land_speed_ms) * 0.5;
672
const float land_slowdown_ms = MAX(0.0f, target_error_m * (max_descent_speed_ms / precland_acceptable_error_m));
673
climb_rate_ms = MIN(-precland_min_descent_speed_ms, -max_descent_speed_ms + land_slowdown_ms);
674
}
675
}
676
#endif
677
}
678
679
// update altitude target and call position controller
680
pos_control->D_set_pos_target_from_climb_rate_ms(climb_rate_ms, ignore_descent_limit);
681
pos_control->D_update_controller();
682
}
683
684
void Mode::land_run_horizontal_control()
685
{
686
Vector2f vel_correction_ms;
687
688
// relax loiter target if we might be landed
689
if (copter.ap.land_complete_maybe) {
690
pos_control->NE_soften_for_landing();
691
}
692
693
// process pilot inputs
694
if (rc().has_valid_input()) {
695
if ((g.throttle_behavior & THR_BEHAVE_HIGH_THROTTLE_CANCELS_LAND) != 0 && copter.rc_throttle_control_in_filter.get() > LAND_CANCEL_TRIGGER_THR){
696
LOGGER_WRITE_EVENT(LogEvent::LAND_CANCELLED_BY_PILOT);
697
// exit land if throttle is high
698
if (!set_mode(Mode::Number::LOITER, ModeReason::THROTTLE_LAND_ESCAPE)) {
699
set_mode(Mode::Number::ALT_HOLD, ModeReason::THROTTLE_LAND_ESCAPE);
700
}
701
}
702
703
if (g.land_repositioning) {
704
// apply SIMPLE mode transform to pilot inputs
705
update_simple_mode();
706
707
// convert pilot input to reposition velocity
708
// use half maximum acceleration as the maximum velocity to ensure aircraft will
709
// stop from full reposition speed in less than 1 second.
710
const float max_pilot_vel_ms = wp_nav->get_wp_acceleration_mss() * 0.5;
711
vel_correction_ms = get_pilot_desired_velocity(max_pilot_vel_ms);
712
713
// record if pilot has overridden roll or pitch
714
if (!vel_correction_ms.is_zero()) {
715
if (!copter.ap.land_repo_active) {
716
LOGGER_WRITE_EVENT(LogEvent::LAND_REPO_ACTIVE);
717
}
718
copter.ap.land_repo_active = true;
719
#if AC_PRECLAND_ENABLED
720
} else {
721
// no override right now, check if we should allow precland
722
if (copter.precland.allow_precland_after_reposition()) {
723
copter.ap.land_repo_active = false;
724
}
725
#endif
726
}
727
}
728
}
729
730
// this variable will be updated if prec land target is in sight and pilot isn't trying to reposition the vehicle
731
copter.ap.prec_land_active = false;
732
#if AC_PRECLAND_ENABLED
733
copter.ap.prec_land_active = !copter.ap.land_repo_active && copter.precland.target_acquired();
734
// run precision landing
735
if (copter.ap.prec_land_active) {
736
Vector2p target_pos_ne_m;
737
Vector2f target_vel_ne_ms;
738
if (!copter.precland.get_target_position_m(target_pos_ne_m)) {
739
target_pos_ne_m = pos_control->get_pos_estimate_NED_m().xy();
740
}
741
// get the velocity of the target
742
copter.precland.get_target_velocity_ms(pos_control->get_vel_estimate_NED_ms().xy(), target_vel_ne_ms);
743
744
Vector2f accel_zero;
745
// target vel will remain zero if landing target is stationary
746
pos_control->input_pos_vel_accel_NE_m(target_pos_ne_m, target_vel_ne_ms, accel_zero);
747
}
748
#endif
749
750
if (!copter.ap.prec_land_active) {
751
Vector2f accel;
752
pos_control->input_vel_accel_NE_m(vel_correction_ms, accel);
753
}
754
755
// run pos controller
756
pos_control->NE_update_controller();
757
Vector3f thrust_vector = pos_control->get_thrust_vector();
758
759
// call attitude controller
760
attitude_control->input_thrust_vector_heading(thrust_vector, auto_yaw.get_heading());
761
762
}
763
764
// run normal or precision landing (if enabled)
765
// pause_descent is true if vehicle should not descend
766
void Mode::land_run_normal_or_precland(bool pause_descent)
767
{
768
#if AC_PRECLAND_ENABLED
769
if (pause_descent || !copter.precland.enabled()) {
770
// we don't want to start descending immediately or prec land is disabled
771
// in both cases just run simple land controllers
772
land_run_horiz_and_vert_control(pause_descent);
773
} else {
774
// prec land is enabled and we have not paused descent
775
// the state machine takes care of the entire prec landing procedure
776
precland_run();
777
}
778
#else
779
land_run_horiz_and_vert_control(pause_descent);
780
#endif
781
}
782
783
#if AC_PRECLAND_ENABLED
784
// Go towards a position commanded by prec land state machine in order to retry landing
785
// The passed in location is expected to be NED and in m
786
void Mode::precland_retry_position(const Vector3p &retry_pos_ned_m)
787
{
788
if (rc().has_valid_input()) {
789
if ((g.throttle_behavior & THR_BEHAVE_HIGH_THROTTLE_CANCELS_LAND) != 0 && copter.rc_throttle_control_in_filter.get() > LAND_CANCEL_TRIGGER_THR){
790
LOGGER_WRITE_EVENT(LogEvent::LAND_CANCELLED_BY_PILOT);
791
// exit land if throttle is high
792
if (!set_mode(Mode::Number::LOITER, ModeReason::THROTTLE_LAND_ESCAPE)) {
793
set_mode(Mode::Number::ALT_HOLD, ModeReason::THROTTLE_LAND_ESCAPE);
794
}
795
}
796
797
// allow user to take control during repositioning. Note: copied from land_run_horizontal_control()
798
// To-Do: this code exists at several different places in slightly different forms and that should be fixed
799
if (g.land_repositioning) {
800
float target_roll_rad = 0.0f;
801
float target_pitch_rad = 0.0f;
802
// convert pilot input to lean angles
803
get_pilot_desired_lean_angles_rad(target_roll_rad, target_pitch_rad, loiter_nav->get_angle_max_rad(), attitude_control->get_althold_lean_angle_max_rad());
804
805
// record if pilot has overridden roll or pitch
806
if (!is_zero(target_roll_rad) || !is_zero(target_pitch_rad)) {
807
if (!copter.ap.land_repo_active) {
808
LOGGER_WRITE_EVENT(LogEvent::LAND_REPO_ACTIVE);
809
}
810
// this flag will be checked by prec land state machine later and any further landing retires will be cancelled
811
copter.ap.land_repo_active = true;
812
}
813
}
814
}
815
816
pos_control->input_pos_NED_m(retry_pos_ned_m, 0.0f, 10.0);
817
818
// run position controllers
819
pos_control->NE_update_controller();
820
pos_control->D_update_controller();
821
822
// call attitude controller
823
attitude_control->input_thrust_vector_heading(pos_control->get_thrust_vector(), auto_yaw.get_heading());
824
}
825
826
// Run precland statemachine. This function should be called from any mode that wants to do precision landing.
827
// This handles everything from prec landing, to prec landing failures, to retries and failsafe measures
828
void Mode::precland_run()
829
{
830
// if user is taking control, we will not run the statemachine, and simply land (may or may not be on target)
831
if (!copter.ap.land_repo_active) {
832
// This will get updated later to a retry pos if needed
833
Vector3p retry_pos_ned_m;
834
835
switch (copter.precland_statemachine.update(retry_pos_ned_m)) {
836
case AC_PrecLand_StateMachine::Status::RETRYING:
837
// we want to retry landing by going to another position
838
precland_retry_position(retry_pos_ned_m);
839
break;
840
841
case AC_PrecLand_StateMachine::Status::FAILSAFE: {
842
// we have hit a failsafe. Failsafe can only mean two things, we either want to stop permanently till user takes over or land
843
switch (copter.precland_statemachine.get_failsafe_actions()) {
844
case AC_PrecLand_StateMachine::FailSafeAction::DESCEND:
845
// descend normally, prec land target is definitely not in sight
846
land_run_horiz_and_vert_control();
847
break;
848
case AC_PrecLand_StateMachine::FailSafeAction::HOLD_POS:
849
// sending "true" in this argument will stop the descend
850
land_run_horiz_and_vert_control(true);
851
break;
852
}
853
break;
854
}
855
case AC_PrecLand_StateMachine::Status::ERROR:
856
// should never happen, is certainly a bug. Report then descend
857
INTERNAL_ERROR(AP_InternalError::error_t::flow_of_control);
858
FALLTHROUGH;
859
case AC_PrecLand_StateMachine::Status::DESCEND:
860
// run land controller. This will descend towards the target if prec land target is in sight
861
// else it will just descend vertically
862
land_run_horiz_and_vert_control();
863
break;
864
}
865
} else {
866
// just land, since user has taken over controls, it does not make sense to run any retries or failsafe measures
867
land_run_horiz_and_vert_control();
868
}
869
}
870
#endif
871
872
float Mode::throttle_hover() const
873
{
874
return motors->get_throttle_hover();
875
}
876
877
// transform pilot's manual throttle input to make hover throttle mid stick
878
// used only for manual throttle modes
879
// thr_mid should be in the range 0 to 1
880
// returns throttle output 0 to 1
881
float Mode::get_pilot_desired_throttle() const
882
{
883
int16_t mid_stick = copter.get_throttle_mid();
884
// protect against unlikely divide by zero
885
if (mid_stick <= 0) {
886
mid_stick = 500;
887
}
888
889
int16_t throttle_control = channel_throttle->get_control_in();
890
// ensure reasonable throttle values
891
throttle_control = constrain_int16(throttle_control,0,1000);
892
893
// calculate normalised throttle input
894
float throttle_in;
895
if (throttle_control < mid_stick) {
896
throttle_in = ((float)throttle_control)*0.5f/(float)mid_stick;
897
} else {
898
throttle_in = 0.5f + ((float)(throttle_control-mid_stick)) * 0.5f / (float)(1000-mid_stick);
899
}
900
901
const float thr_mid = throttle_hover();
902
const float expo = constrain_float(-(thr_mid-0.5f)/0.375f, -0.5f, 1.0f);
903
// calculate the output throttle using the given expo function
904
float throttle_out = throttle_in*(1.0f-expo) + expo*throttle_in*throttle_in*throttle_in;
905
return throttle_out;
906
}
907
908
float Mode::get_avoidance_adjusted_climbrate_ms(float target_rate_ms)
909
{
910
#if AP_AVOIDANCE_ENABLED
911
float target_rate_cms = target_rate_ms * 100.0;
912
AP::ac_avoid()->adjust_velocity_z(pos_control->D_get_pos_p().kP(), pos_control->D_get_max_accel_mss() * 100.0, target_rate_cms, G_Dt);
913
return target_rate_cms * 0.01;
914
#else
915
return target_rate_ms;
916
#endif
917
}
918
919
// send output to the motors, can be overridden by subclasses
920
void Mode::output_to_motors()
921
{
922
motors->output();
923
}
924
925
Mode::AltHoldModeState Mode::get_alt_hold_state_D_ms(float target_climb_rate_ms)
926
{
927
// Alt Hold State Machine Determination
928
if (!motors->armed()) {
929
// the aircraft should moved to a shut down state
930
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::SHUT_DOWN);
931
932
// transition through states as aircraft spools down
933
switch (motors->get_spool_state()) {
934
935
case AP_Motors::SpoolState::SHUT_DOWN:
936
return AltHoldModeState::MotorStopped;
937
938
case AP_Motors::SpoolState::GROUND_IDLE:
939
return AltHoldModeState::Landed_Ground_Idle;
940
941
default:
942
return AltHoldModeState::Landed_Pre_Takeoff;
943
}
944
945
} else if (takeoff.running() || takeoff.triggered_ms(target_climb_rate_ms)) {
946
// the aircraft is currently landed or taking off, asking for a positive climb rate and in THROTTLE_UNLIMITED
947
// the aircraft should progress through the take off procedure
948
return AltHoldModeState::Takeoff;
949
950
} else if (!copter.ap.auto_armed || copter.ap.land_complete) {
951
// the aircraft is armed and landed
952
if (target_climb_rate_ms < 0.0f && !copter.ap.using_interlock) {
953
// the aircraft should move to a ground idle state
954
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::GROUND_IDLE);
955
} else if (copter.ap.using_interlock && !motors->get_interlock()) {
956
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::GROUND_IDLE);
957
} else {
958
// the aircraft should prepare for imminent take off
959
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);
960
}
961
962
if (motors->get_spool_state() == AP_Motors::SpoolState::GROUND_IDLE) {
963
// the aircraft is waiting in ground idle
964
return AltHoldModeState::Landed_Ground_Idle;
965
966
} else {
967
// the aircraft can leave the ground at any time
968
return AltHoldModeState::Landed_Pre_Takeoff;
969
}
970
971
} else {
972
// the aircraft is in a flying state
973
motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);
974
return AltHoldModeState::Flying;
975
}
976
}
977
978
// transform pilot's yaw input into a desired yaw rate
979
// returns desired yaw rate in centi-degrees per second
980
float Mode::get_pilot_desired_yaw_rate_rads() const
981
{
982
if (!rc().has_valid_input()) {
983
return 0.0f;
984
}
985
986
// Get yaw input
987
const float yaw_in = channel_yaw->norm_input_dz();
988
989
// convert pilot input to the desired yaw rate
990
return radians(g2.command_model_pilot_y.get_rate()) * input_expo(yaw_in, g2.command_model_pilot_y.get_expo());
991
}
992
993
// pass-through functions to reduce code churn on conversion;
994
// these are candidates for moving into the Mode base
995
// class.
996
997
// Returns the pilot’s commanded climb rate in m/s.
998
float Mode::get_pilot_desired_climb_rate_ms() const
999
{
1000
return copter.get_pilot_desired_climb_rate_ms();
1001
}
1002
1003
// Returns half the hover throttle.
1004
float Mode::get_non_takeoff_throttle() const
1005
{
1006
return copter.get_non_takeoff_throttle();
1007
}
1008
1009
// Updates simple/super-simple heading reference based on current yaw and mode.
1010
void Mode::update_simple_mode(void) {
1011
copter.update_simple_mode();
1012
}
1013
1014
// Requests a mode change with the specified reason; returns true if accepted.
1015
bool Mode::set_mode(Mode::Number mode, ModeReason reason)
1016
{
1017
return copter.set_mode(mode, reason);
1018
}
1019
1020
// Sets the “land complete” state flag.
1021
void Mode::set_land_complete(bool b)
1022
{
1023
return copter.set_land_complete(b);
1024
}
1025
1026
// Returns a reference to the GCS interface for Copter.
1027
GCS_Copter &Mode::gcs() const
1028
{
1029
return copter.gcs();
1030
}
1031
1032
// Returns the pilot’s maximum upward speed in m/s.
1033
float Mode::get_pilot_speed_up_ms() const
1034
{
1035
return g.pilot_speed_up_cms * 0.01;
1036
}
1037
1038
// Returns the pilot’s maximum downward speed in m/s.
1039
float Mode::get_pilot_speed_dn_ms() const
1040
{
1041
return copter.get_pilot_speed_dn() * 0.01;
1042
}
1043
1044
// Returns the pilot’s vertical acceleration limit in m/s².
1045
float Mode::get_pilot_accel_D_mss() const
1046
{
1047
return g.pilot_accel_d_cmss * 0.01;
1048
}
1049
1050
// Return stopping point as a location with above origin alt frame
1051
Location Mode::get_stopping_point() const
1052
{
1053
Vector3p stopping_point_ned_m;
1054
copter.pos_control->get_stopping_point_NE_m(stopping_point_ned_m.xy());
1055
copter.pos_control->get_stopping_point_D_m(stopping_point_ned_m.z);
1056
return Location::from_ekf_offset_NED_m(stopping_point_ned_m, Location::AltFrame::ABOVE_ORIGIN);
1057
}
1058
1059