From 3a35c014bef9ce085dda20d38f8f26a29558e4c6 Mon Sep 17 00:00:00 2001 From: Gennaro Guidone <99129829+gguidone@users.noreply.github.com> Date: Fri, 7 Aug 2026 11:46:17 +0200 Subject: [PATCH] feat(control_allocator): reversible-motor failure recovery for hexarotors (#28078) * feat(control_allocator): add reversible-motor failure recovery for hexarotors On a single motor failure (CA_FAILURE_MODE), handle the failed motor's geometric-opposite motor on a hexarotor to recover the lost control authority: 1 = remove failed + shut off opposite (restores symmetry) 2 = remove failed + make opposite reversible (assumes a reverse-capable ESC) Non-hex frames have no opposite and keep the upstream remove-only behavior. The opposite motor is found geometrically (opposite spin, closest antipode) and only for hexarotors. Reverse thrust is modeled as CA_REV_THR_FRAC of forward thrust and the reversible actuator range is rescaled to [-1, 0] on publish. Consumes failure_detector_status.motor_failure_mask, independent of detection. * feat(uavcan): render reversible motor outputs as signed RawCommand Re-encode reversible channels from the mixer's [min,max] range to a signed RawCommand (negative = reverse). A channel at its disarmed value is passed through untouched, so a stopped motor is never inverted to reverse. * fix(dshot): match per-channel minimums to the 3D encoding calculate_output_value() applies the 3D split when DSHOT_3D_ENABLE is set or the channel is reversible, but the per-channel minimum was derived from the reversible bit alone. Two problems followed. A reversible channel made reversible at runtime kept a stale minimum, so its neutral no longer landed on the mid-throttle split. A non-reversible channel with 3D enabled was worse: it mapped from DSHOT_MIN, which sits below the split, so zero commanded thrust decoded as near-full reverse. Select the minimum from the same two facts the encoder uses. A reversible channel keeps the range bottom so neutral lands on the split, a forward-only channel starts just above it, and without 3D the DSHOT_MIN idle floor applies as before. For a split channel the idle floor is applied per direction inside convert_output_to_3d_scaling(), so it must not be added to the minimum. The deadband is now applied only to reversible channels, since a channel that cannot be commanded negative has no neutral to guard. Apply the minimums from a new OutputModuleInterface::reversibleMaskChanged(), called once the new mask is known and before any output is computed with it. Applying them from Run() left the range one cycle behind the mask it depends on, which in 3D mode changed the sign of the output on the transition. The reversible mask can now change while armed, since failure recovery reverses a motor in flight, so the reversibleOutputs() contract is updated to say so. Changes output values for every DSHOT_3D_ENABLE=1 setup that has any non-reversible motor. Verified on fmu-v4 with 3D-mode ESCs: forward-only channels floor at 1001 with no samples below the split across 85 s armed, and a runtime-reversed recovery motor tracks yaw input through the split in both directions. * docs(control_allocator): document motor failure recovery Add a Motor Failure Recovery page covering CA_FAILURE_MODE, the hexarotor stop-or-reverse behaviour of the opposite motor, CA_REV_THR_FRAC, the detection prerequisites and which output protocols can drive a motor in reverse. Document the signed DroneCAN RawCommand encoding for reversible motors, and correct the failure detector section, which claimed motor failures are non-latching while the current-based check holds a flagged motor until the vehicle disarms. Add the page to the navigation and to the v1.18 release notes. * docs(docs): subedit * docs(docs): subedit * refactor(control_allocator): align CA_REV_THR_FRAC naming and description Rename the parameter member to _param_ca_rev_thr_frac to match the parameter name, and note in the description that the reverse thrust fraction is mostly a property of the propeller. * docs(motor_failure_recovery): move under Actuators and target v1.19 The page documents how control allocation is reconfigured, so list it under Actuators next to Actuator Allocation instead of under Safety, and link it from the Actuators and multicopter Features indexes. Safety configuration still links to it from the motor failure trigger section. The release branch for v1.18 is already cut, so move the release notes to main.md and set the version badges to main (PX4 v1.19). * docs(motor_failure_recovery): spell out the reversing requirements Any of the six motors can fail, so every motor has to be reverse-capable, not just one. List the settings that mode 2 needs, split the per-protocol detail out (DroneCAN reverses from the signed RawCommand alone, DShot also needs the ESCs in 3D mode and DSHOT_3D_ENABLE to match), and say what happens when they are not set: a reverse command comes out as forward thrust, and on PWM the recovery motor sits at around half throttle. Also note that motors do not have to be marked bidirectional (CA_R_REV) for this, since the recovery motor is made reversible at runtime. * Apply suggestions from code review Co-authored-by: Hamish Willee * fix(uavcan_main): log final value in actuator_outputs, always run through reversible logic We want worst case execution time all the time and as little control paths as possible. Also actuator_outputs is used to debug ESC behavior and should contain the final value that is sent out over the wire. * refactor(DShot): directly calculate minimum dshot value in apply_min_values() * refactor(control_allocator): static_cast, correct CA_FAILURE_MODE description * fix(control_allocator): treat undefined parameter values as default, use matrix function to zero a collumn --------- Co-authored-by: Hamish Willee Co-authored-by: Matthias Grob --- docs/en/SUMMARY.md | 1 + docs/en/_sidebar.md | 1 + docs/en/actuators/index.md | 1 + docs/en/config/actuators.md | 4 +- docs/en/config/motor_failure_recovery.md | 108 ++++++++++++++++++ docs/en/config/safety.md | 21 ++-- docs/en/dronecan/escs.md | 22 ++++ docs/en/features_mc/index.md | 1 + docs/en/releases/main.md | 4 +- src/drivers/dshot/DShot.cpp | 57 +++++---- src/drivers/dshot/DShot.h | 12 +- src/drivers/uavcan/uavcan_main.cpp | 17 +++ src/lib/mixer_module/mixer_module.cpp | 5 + src/lib/mixer_module/mixer_module.hpp | 9 +- .../control_allocator/ControlAllocator.cpp | 102 ++++++++++++----- .../control_allocator/ControlAllocator.hpp | 12 +- .../ActuatorEffectivenessMultirotor.hpp | 2 + src/modules/control_allocator/module.yaml | 20 +++- 18 files changed, 335 insertions(+), 64 deletions(-) create mode 100644 docs/en/config/motor_failure_recovery.md diff --git a/docs/en/SUMMARY.md b/docs/en/SUMMARY.md index ff7f4b29a2b..6ec2b2e663d 100644 --- a/docs/en/SUMMARY.md +++ b/docs/en/SUMMARY.md @@ -307,6 +307,7 @@ - [Sensor Thermal Compensation](advanced_config/sensor_thermal_calibration.md) - [Actuators](actuators/index.md) - [Actuator Allocation](config/actuators.md) + - [Motor Failure Recovery](config/motor_failure_recovery.md) - [ESC Calibration](advanced_config/esc_calibration.md) - [ESCs & Motors](peripherals/esc_motors.md) - [ESC Protocols](esc/esc_protocols.md) diff --git a/docs/en/_sidebar.md b/docs/en/_sidebar.md index b419727ca58..0f5e733bee4 100644 --- a/docs/en/_sidebar.md +++ b/docs/en/_sidebar.md @@ -308,6 +308,7 @@ - [Sensor Thermal Compensation](/advanced_config/sensor_thermal_calibration.md) - [Actuators](/actuators/index.md) - [Actuator Allocation](/config/actuators.md) + - [Motor Failure Recovery](/config/motor_failure_recovery.md) - [ESC Calibration](/advanced_config/esc_calibration.md) - [ESCs & Motors](/peripherals/esc_motors.md) - [ESC Protocols](/esc/esc_protocols.md) diff --git a/docs/en/actuators/index.md b/docs/en/actuators/index.md index 786f2e13044..4e98b4374d0 100644 --- a/docs/en/actuators/index.md +++ b/docs/en/actuators/index.md @@ -3,6 +3,7 @@ This section contains topics about the core actuators used for flight control (ESC/motors, and servos), and how they are assigned to the flight controller outputs, configured, and calibrated. - [Actuator Allocation](../config/actuators.md) — Configure flight controller outputs for specific functions and ESC/servo types. +- [Motor Failure Recovery](../config/motor_failure_recovery.md) — How allocation is reconfigured if a motor fails. - [ESCs & Motors](../peripherals/esc_motors.md) — ESCs such as [DShot](../peripherals/dshot.md) (recommended) and DroneCAN. - [ESC Calibration](../advanced_config/esc_calibration.md) — Calibration for PWM ESC (not required for DShot/CAN ESC/servos). diff --git a/docs/en/config/actuators.md b/docs/en/config/actuators.md index 9544eef9c61..14049faaafd 100644 --- a/docs/en/config/actuators.md +++ b/docs/en/config/actuators.md @@ -131,7 +131,9 @@ If bidiectional motors are used, make sure to select the **Reversible** checkbox ![Reversible](../../assets/config/actuators/qgc_geometry_reversible_marked.png) -Note that you will need to also ensure that the ESC associated with bidirectional motors is configured appropriately (e.g. 3D mode enabled for DShot ESCs, which can be achieved via [DShot commands](../peripherals/dshot.md#commands)). +Note that you will also need to ensure that the ESC associated with bidirectional motors is configured appropriately. +For DShot ESC you will need to enable 3D mode using [DShot commands](../peripherals/dshot.md#commands). +For DroneCAN ESC you will need [firmware that supports reversal](../dronecan/escs.md#reversible-motors) and an appropriate configuration. ### Control Surfaces Geometry diff --git a/docs/en/config/motor_failure_recovery.md b/docs/en/config/motor_failure_recovery.md new file mode 100644 index 00000000000..9adb0031cdf --- /dev/null +++ b/docs/en/config/motor_failure_recovery.md @@ -0,0 +1,108 @@ +# Motor Failure Recovery + + + +PX4 can reconfigure [control allocation (mixing)](../concept/control_allocation.md) in flight when a motor failure is detected, so that the vehicle can keep flying on the motors that are left. + +The failure action is selected with [CA_FAILURE_MODE](#CA_FAILURE_MODE). +This can be set to `0` (the default) to simply warn the user, or `1` to remove the failed motor from allocation. +Hexarotor frames provide additional recovery options, which are outlined in the following sections. + +::: warning +A vehicle flying with a failed motor has less control authority and thrust margin than a healthy one. +Fly gently and land as soon as it is safe to do so. +::: + +## Hexarotor + +### Stop or Reverse the Opposite Motor + +Modes `1` and `2` only differ on a hexarotor; on any other airframe both simply remove the failed motor. + +On a hexarotor the rotor opposite the failed one is the rotor that used to cancel its drag (yaw) torque, so what happens to it decides how much yaw authority is left: + +- Mode `1` stops it, leaving four symmetric rotors and no yaw bias to trim, but a third of the thrust is gone and the heading can still drift. +- Mode `2` keeps it in the allocation and lets it spin backwards. Driving a rotor in reverse inverts both its thrust and its drag torque, so it can still generate yaw torque. This needs an ESC that can actually reverse the motor. + +The opposite motor is taken from the configured [geometry](actuators.md#motor-geometry-multicopter): it is the counter-rotating rotor closest to the failed rotor's antipode, and it is only computed for a 6-rotor multirotor geometry. + +### Reverse Thrust Fraction + +A propeller spun backwards produces less thrust than it does forwards, and [CA_REV_THR_FRAC](#CA_REV_THR_FRAC) tells the allocator what fraction to expect (default `0.4`, i.e. 40%, which is representative of a standard multicopter propeller). +A symmetric (3D) propeller produces almost the same thrust either way, so it should be set closer to `1.0`. + +A value in the right region is best, but it is not critical: a hexarotor still recovers with `1.0` set on a propeller whose real fraction is 0.4. + +### ESC Requirements for Reversing + +Mode `2` reverses whichever motor sits opposite the one that failed, and any of the six can fail, so every motor on the vehicle has to be able to reverse (not just one of them). + +Reversing needs all of the following: + +1. Motors and ESCs that can be driven backwards. +2. Reversal enabled in the ESC configuration. + This is set in the ESC (PX4 does not set it for you). +3. [CA_FAILURE_MODE](#CA_FAILURE_MODE) = `2`. +4. For DShot ESCs only: [DSHOT_3D_ENABLE](../advanced_config/parameter_reference.md#DSHOT_3D_ENABLE) = `1`. + +Nothing else is required, in particular the motors do _not_ have to be marked as [bidirectional](actuators.md#bidirectional-motors) ([CA_R_REV](../advanced_config/parameter_reference.md#CA_R_REV)). +PX4 makes the recovery motor reversible by itself while handling the failure, and returns it to forward-only if the failure clears. + +#### DroneCAN + +Reverse is part of the protocol: PX4 sends the recovery motor a negative `RawCommand`, and an ESC configured for bidirectional operation spins it backwards. +No additional PX4 parameter is needed. +See [Reversible motors](../dronecan/escs.md#reversible-motors) in _DroneCAN ESCs_. + +#### DShot + +A reversible output is encoded using the DShot 3D split range, where neutral sits in the middle of the range +The ESC has to be running in 3D mode, which is a persistent ESC setting (see [ESC Commands](../peripherals/dshot.md#commands)), and PX4 has to be told about it with [DSHOT_3D_ENABLE](../advanced_config/parameter_reference.md#DSHOT_3D_ENABLE). +`DSHOT_3D_ENABLE` puts every motor on the matching encoding. +This has nothing to do with [Bidirectional DShot](../peripherals/dshot.md#bidirectional-dshot-telemetry), which is about eRPM telemetry rather than reversing a motor. + +::: warning +`DSHOT_3D_ENABLE` and the 3D setting in the ESCs must always agree, whether or not a motor has failed. +If the ESCs run in 3D mode while `DSHOT_3D_ENABLE` is `0`, the lower part of the throttle range is sent in the range those ESCs read as reverse, and the vehicle is not flyable. +::: + +#### PWM, OneShot, and Other Protocols + +These cannot reverse a motor, so [CA_FAILURE_MODE](#CA_FAILURE_MODE) has to be `1` or `0`. +With mode `2` the recovery motor would sit at around half throttle forwards instead of reversing, which is worse than stopping it. + +::: warning +PX4 does not check whether an ESC can reverse, and a reverse command sent to an ESC that is not set up for it comes out as forward thrust. +Before flying with mode `2`, confirm on the bench that each motor really does spin backwards, for example from the sign of the reported RPM. +::: + +## Failure Detection + +Recovery reacts to the motor failure flag raised by the [failure detector](safety.md#motor-failure-trigger), which is set when either: + +- an ESC stops sending telemetry, or reports a fault. + This requires [COM_ARM_CHK_ESCS](../advanced_config/parameter_reference.md#COM_ARM_CHK_ESCS) to be enabled. +- the current reported by an ESC is outside the band expected for its commanded thrust. + This requires [FD_ACT_EN](safety.md#FD_ACT_EN) to be enabled, and the [MOTFAIL\_\*](safety.md#motor-failure-trigger) thresholds to be tuned for the vehicle. + +Either path needs ESC telemetry, so recovery is only possible with telemetry-capable ESCs (such as [DroneCAN](../dronecan/escs.md) or [DShot with telemetry](../peripherals/dshot.md#esc-telemetry)). +Note that the two are gated by different parameters: an ESC that goes silent triggers recovery with `FD_ACT_EN` disabled, as long as `COM_ARM_CHK_ESCS` is enabled. + +The current-based check **latches**: once a motor is flagged it stays flagged until the vehicle disarms. +This is deliberate, because the recovery stops the failed motor, which would otherwise make it look healthy again and clear the failure. +The ESC offline/fault check does clear if the ESC starts reporting again, in which case all motors are restored to the allocation and any runtime reverse is removed. + +To exercise the whole chain you can take an ESC offline with [failure injection](../debug/failure_injection.md): `failure esc off -i `. + +## Parameters + +| Parameter | Description | +| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE) | What to do on a single motor failure.
`0` (default): Ignore and report failure.
`1`: Remove failed motor from allocation. Hexarotor: also stop the opposite motor.
`2`: Remove failed motor from allocation. Hexarotor: also reverse the opposite motor. | +| [CA_REV_THR_FRAC](../advanced_config/parameter_reference.md#CA_REV_THR_FRAC) | Fraction of forward thrust that the recovery motor is expected to produce in reverse (default `0.4`). Only used by mode `2`. | + +## See Also + +- [Safety Configuration (Failsafes)](../config/safety.md), covering the failure detector and motor failure detection. +- [Control Allocation (Mixing)](../concept/control_allocation.md) +- [Actuator Configuration and Testing](actuators.md), covering geometry, motor order and bidirectional motors. diff --git a/docs/en/config/safety.md b/docs/en/config/safety.md index 5cad2c15fed..23108678620 100644 --- a/docs/en/config/safety.md +++ b/docs/en/config/safety.md @@ -415,7 +415,7 @@ The relevant parameters are shown below: ### Motor Failure Trigger The failure detector can be configured to detect a motor failure while armed (and trigger an associated action) if the ESC current falls outside expected threshold for more than [MOTFAIL_TIME](#MOTFAIL_TIME) seconds. -Motor failures are non-latching: if the failure condition clears, the failure is cleared. +A motor flagged by this current check stays flagged until the vehicle disarms, because the reaction to a failure may stop the motor and thereby make it look healthy again. The undercurrent and overcurrent conditions are defined by: @@ -424,14 +424,17 @@ undercurrent: {esc current} < {MOTFAIL_C2T} * {motor command [0,1]} - {MOTFAIL_O overcurrent: {esc current} > {MOTFAIL_C2T} * {motor command [0,1]} + {MOTFAIL_OFF} ``` -| Parameter | Description | -| -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [FD_ACT_EN](../advanced_config/parameter_reference.md#FD_ACT_EN) | Enable/disable the motor failure trigger completely. | -| [MOTFAIL_C2T](../advanced_config/parameter_reference.md#MOTFAIL_C2T) | Slope between normalized motor command [0–1] and expected steady-state current (FD_ACT_MOT_C2T at 100%) (A/%). | -| [MOTFAIL_OFF](../advanced_config/parameter_reference.md#MOTFAIL_OFF) | Under/over-current detection threshold offset (A). Added to the expected current to form the upper bound. Subtracted from the expected current to form the lower bound. | -| | -| [MOTFAIL_TIME](../advanced_config/parameter_reference.md#MOTFAIL_TIME) | Hysteresis time (s) for which the current threshold must remain exceeded before a motor failure is triggered. | -| [CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE) | Configure to not only warn about a motor failure but remove the first motor that detects a failure from the allocation effectiveness which turns off the motor and tries to operate the vehicle without it until disarming the next time. | +The action on motor failure is set with [CA_FAILURE_MODE](#CA_FAILURE_MODE). +Actions depend on the vehicle type, and might include warning the user, removing failed motors from control allocation, disabling symmetrically opposite motors, and so on. +For more information see [Motor Failure Recovery](motor_failure_recovery.md). + +| Parameter | Description | +| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| [FD_ACT_EN](../advanced_config/parameter_reference.md#FD_ACT_EN) | Enable/disable the motor failure trigger completely. | +| [MOTFAIL_C2T](../advanced_config/parameter_reference.md#MOTFAIL_C2T) | Slope between normalized motor command [0–1] and expected steady-state current (FD_ACT_MOT_C2T at 100%) (A/%). | +| [MOTFAIL_OFF](../advanced_config/parameter_reference.md#MOTFAIL_OFF) | Under/over-current detection threshold offset (A). Added/subtracted to the expected current to form the upper and lower bounds. | +| [MOTFAIL_TIME](../advanced_config/parameter_reference.md#MOTFAIL_TIME) | Hysteresis time (s) for which the current threshold must remain exceeded before a motor failure is triggered. | +| [CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE) | Failure mode. See [Motor Failure Recovery](motor_failure_recovery.md). | ### External Automatic Trigger System (ATS) diff --git a/docs/en/dronecan/escs.md b/docs/en/dronecan/escs.md index da950af29d8..264d617b8ad 100644 --- a/docs/en/dronecan/escs.md +++ b/docs/en/dronecan/escs.md @@ -31,3 +31,25 @@ In addition to the general setup, such as setting `UAVCAN_ENABLE` to `3`: - Select the specific CAN interface(s) used for ESC data output using the [UAVCAN_ESC_IFACE](../advanced_config/parameter_reference.md#UAVCAN_ESC_IFACE) parameter (all that all interfaces are selected by default). - Configure the [motor order and servo outputs](../config/actuators.md). + +## Reversible Motors {#reversible-motors} + + + +Motors can be reversible "on the fly" (bidirectional) if the motor hardware supports reversal, the ESC firmware is configured for 3D/bidirectional operation, and the motor is set as [bidirectional](../config/actuators.md#bidirectional-motors) in the actuator configuration. + +When configured as bidirectional, PX4 commands the motor with a _signed_ `uavcan.equipment.esc.RawCommand` value, as defined by the DroneCAN ESC message protocol: + +- **Zero:** Motor stop / neutral +- **Positive values:** Forward thrust +- **Negative values:** Reverse thrust + +Motors that are not configured as bidirectional continue to receive positive values only. + +::: tip Verifying Operation +Check the sign of the RPM reported in the ESC telemetry to confirm that the ESC is interpreting negative commands correctly and actively spinning the motor in reverse. +::: + +Reversible motors may also be used in [Motor Failure Recovery](../config/motor_failure_recovery.md) to keep a hexarotor controllable after a single motor failure. +That case still needs ESCs configured for reversal. +However it is not necessary to set the motor as bidirectional in the actuator configuration, because PX4 makes the recovery motor reversible as it handles the failure. diff --git a/docs/en/features_mc/index.md b/docs/en/features_mc/index.md index 78e8970eb83..44e8a339ff9 100644 --- a/docs/en/features_mc/index.md +++ b/docs/en/features_mc/index.md @@ -7,3 +7,4 @@ This section lists features that are specific to (or customised for) multicopter - [Precision Landing](../advanced_features/precland.md) - [Terrain Following/Holding](../flying/terrain_following_holding.md) - [Throw Launch](../flight_modes_mc/throw_launch.md) +- [Motor Failure Recovery](../config/motor_failure_recovery.md) diff --git a/docs/en/releases/main.md b/docs/en/releases/main.md index c586ff217c5..74634cdf097 100644 --- a/docs/en/releases/main.md +++ b/docs/en/releases/main.md @@ -26,11 +26,12 @@ Please continue reading for [upgrade instructions](#upgrade-guide). ## Major Changes -- TBD +- **[Motor failure recovery for hexarotors](../config/motor_failure_recovery.md).** On a detected single motor failure the control allocator removes the failed motor and, on a hexarotor, additionally stops ([CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE) = `1`) or reverses (`2`) the motor opposite it, recovering the yaw authority that is otherwise lost. Reversing keeps the opposite motor in the allocation and needs a reverse-capable ESC; the reverse thrust the allocator expects from a forward propeller is set with [CA_REV_THR_FRAC](../advanced_config/parameter_reference.md#CA_REV_THR_FRAC) (default `0.4`). Disabled by default. ([PX4-Autopilot#28078](https://github.com/PX4/PX4-Autopilot/pull/28078)) ## Upgrade Guide - `COM_ARM_TRAFF` has been replaced by `COM_TRAFF_AVOID`. The old value 3 ("enforce for mission modes only") is migrated to `COM_TRAFF_AVOID=2`, which blocks arming in all modes, not just mission modes. If you relied on being able to arm manually with traffic detected, set `COM_TRAFF_AVOID=1` (warning only) instead. +- **Re-check motor failure handling on hexarotors.** [CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE) = `1` now also stops the motor opposite the failed one on a hexarotor (previously only the failed motor was removed from the allocation). Other airframes are unaffected, and `CA_FAILURE_MODE=0` (the default) is unchanged. See [Motor Failure Recovery](../config/motor_failure_recovery.md). ([PX4-Autopilot#28078](https://github.com/PX4/PX4-Autopilot/pull/28078)) ## Other changes @@ -53,6 +54,7 @@ Please continue reading for [upgrade instructions](#upgrade-guide). - [Geofence Aware Return mode](../flight_modes/return.md#geofence_awareness). ([PX4-Autopilot#27145: feat(navigator): Geofence Aware RTL](https://github.com/PX4/PX4-Autopilot/pull/27145), [PX4-Autopilot#28001: docs(navigator): [geofence] added some more warnings about limitations](https://github.com/PX4/PX4-Autopilot/pull/28001)). - [Flight termination](../advanced_config/flight_termination.md) can now be used instead of a Descent mode as a fallback failsafe mode, allowing safer landing for unpiloted vehicles that carry a parachute. See [Battery level failsafe](../config/safety.md#battery-level-failsafe) ([COM_LOW_BAT_ACT](../advanced_config/parameter_reference.md#COM_LOW_BAT_ACT)) and [Position Loss Failsafe Action](../config/safety.md#position-loss-failsafe-action) (new [COM_POS_FS_ACT](../advanced_config/parameter_reference.md#COM_POS_FS_ACT)). ([PX4-Autopilot#28064: feat(commander): add terminate options for critical battery and lost position failsafes](https://github.com/PX4/PX4-Autopilot/pull/28064)). +- [Motor failure recovery](../config/motor_failure_recovery.md) for hexarotors: on a single motor failure the control allocator removes the failed motor and additionally stops ([CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE) = `1`) or reverses (`2`) the motor opposite it to recover the lost yaw authority. Mode `2` requires a reverse-capable ESC and models the reverse thrust of a forward propeller with the new [CA_REV_THR_FRAC](../advanced_config/parameter_reference.md#CA_REV_THR_FRAC) (default `0.4`). Reversible motor outputs on DroneCAN are now sent as signed `RawCommand` values (negative is reverse). ([PX4-Autopilot#28078](https://github.com/PX4/PX4-Autopilot/pull/28078)) ### Estimation diff --git a/src/drivers/dshot/DShot.cpp b/src/drivers/dshot/DShot.cpp index 8af98164466..ef34e2dc46e 100644 --- a/src/drivers/dshot/DShot.cpp +++ b/src/drivers/dshot/DShot.cpp @@ -431,10 +431,11 @@ uint16_t DShot::esc_armed_mask(uint16_t *outputs, uint8_t num_outputs) uint16_t DShot::calculate_output_value(uint16_t raw, int index) { uint16_t output = raw; + const bool reversible = _mixing_output.reversibleOutputs() & (1u << index); // Reverse output if required - if (_3d_enabled || (_mixing_output.reversibleOutputs() & (1u << index))) { - output = convert_output_to_3d_scaling(raw); + if (_3d_enabled || reversible) { + output = convert_output_to_3d_scaling(raw, reversible); } output = math::min(output, DSHOT_MAX_THROTTLE); @@ -751,31 +752,33 @@ void DShot::consume_esc_data(const EscData &esc) } } -uint16_t DShot::convert_output_to_3d_scaling(uint16_t output) +uint16_t DShot::convert_output_to_3d_scaling(uint16_t output, bool reversible) { // DShot 3D splits the throttle ranges in two. // This is in terms of DShot values, code below is in terms of actuator_output // Direction 1) 48 is the slowest, 1047 is the fastest. // Direction 2) 1049 is the slowest, 2047 is the fastest. - if (output >= _3d_dead_l && output <= _3d_dead_h) { + + // The deadband guards a neutral, which only a reversible output has. + if (reversible && output >= _3d_dead_l && output <= _3d_dead_h) { return DSHOT_DISARM_VALUE; } - bool upper_range = output >= 1000; + bool upper_range = output >= DSHOT_3D_SPLIT; if (upper_range) { - output -= 1000; + output -= DSHOT_3D_SPLIT; } else { - output = 999 - output; // lower range is inverted + output = DSHOT_3D_SPLIT - 1 - output; // lower range is inverted } - float max_output = 999.f; + float max_output = DSHOT_3D_SPLIT - 1; float min_output = max_output * _dshot_min; output = math::min(max_output, (min_output + output * (max_output - min_output) / max_output)); if (upper_range) { - output += 1000; + output += DSHOT_3D_SPLIT; } return output; @@ -912,6 +915,28 @@ int DShot::get_pole_count(int motor_index) const return 14; } +void DShot::apply_min_values(uint32_t reversible) +{ + for (uint8_t i = 0; i < DSHOT_MAXIMUM_CHANNELS; i++) { + if (reversible & (1u << i)) { + // Spans both halves, so neutral has to land on the split. + _mixing_output.minValue(i) = DSHOT_MIN_THROTTLE; + + } else if (_3d_enabled) { + _mixing_output.minValue(i) = DSHOT_3D_FORWARD_START; + + } else { + const float min_value = _dshot_min * (float)DSHOT_MAX_THROTTLE; + _mixing_output.minValue(i) = math::constrain((uint16_t)min_value, DSHOT_MIN_THROTTLE, DSHOT_MAX_THROTTLE); + } + } +} + +void DShot::reversibleMaskChanged(uint32_t reversible_mask) +{ + apply_min_values(reversible_mask); +} + void DShot::update_params() { parameter_update_s pupdate; @@ -927,18 +952,8 @@ void DShot::update_params() _dshot_min = _param_dshot_min.get(); _esc_type = _param_dshot_esc_type.get(); - // Calculate minimum DShot output as percent of throttle and constrain. - float min_value = _dshot_min * (float)DSHOT_MAX_THROTTLE; - uint16_t dshot_min_value = math::constrain((uint16_t)min_value, DSHOT_MIN_THROTTLE, DSHOT_MAX_THROTTLE); - - _mixing_output.setAllMinValues(dshot_min_value); - - // Do not use the minimum parameter for reversible outputs - for (uint8_t i = 0; i < DSHOT_MAXIMUM_CHANNELS; i++) { - if (_mixing_output.reversibleOutputs() & (1 << i)) { - _mixing_output.minValue(i) = DSHOT_MIN_THROTTLE; - } - } + // Re-apply after updateParams(), which reloads the minimums from the shared output params. + apply_min_values(_mixing_output.reversibleOutputs()); // Update per-motor pole count param handles and cached values for (int i = 0; i < DSHOT_MAX_MOTORS; i++) { diff --git a/src/drivers/dshot/DShot.h b/src/drivers/dshot/DShot.h index a4a54a56919..3efd6d164fa 100644 --- a/src/drivers/dshot/DShot.h +++ b/src/drivers/dshot/DShot.h @@ -63,6 +63,12 @@ static constexpr int32_t TIM_CONFIG_BDSHOT150 = -8; static constexpr int32_t TIM_CONFIG_BDSHOT300 = -7; static constexpr int32_t TIM_CONFIG_BDSHOT600 = -6; +// A 3D ESC reads the range as two halves meeting here: below is reverse, above is forward. +static constexpr uint16_t DSHOT_3D_SPLIT = 1000; +// Forward-only channels start at the bottom of the forward half. The DSHOT_MIN idle floor is +// applied within that half by convert_output_to_3d_scaling(), so it must not be added here. +static constexpr uint16_t DSHOT_3D_FORWARD_START = DSHOT_3D_SPLIT + 1; + static constexpr uint16_t DSHOT_DISARM_VALUE = 0; static constexpr uint16_t DSHOT_MIN_THROTTLE = 1; static constexpr uint16_t DSHOT_MAX_THROTTLE = 1999; @@ -124,11 +130,15 @@ private: void consume_esc_data(const EscData &data); uint16_t calculate_output_value(uint16_t raw, int index); - uint16_t convert_output_to_3d_scaling(uint16_t output); + uint16_t convert_output_to_3d_scaling(uint16_t output, bool reversible); void Run() override; void update_params(); + // Per-channel minimums must match how calculate_output_value() encodes each channel. + void apply_min_values(uint32_t reversible); + void reversibleMaskChanged(uint32_t reversible_mask) override; + // Mavlink command handlers void handle_vehicle_commands(); void handle_configure_actuator(const vehicle_command_s &command); diff --git a/src/drivers/uavcan/uavcan_main.cpp b/src/drivers/uavcan/uavcan_main.cpp index ef328d1ab5b..66e2575d7bd 100644 --- a/src/drivers/uavcan/uavcan_main.cpp +++ b/src/drivers/uavcan/uavcan_main.cpp @@ -58,6 +58,7 @@ #include #include +#include #include "uavcan_module.hpp" #include "uavcan_main.hpp" @@ -1113,6 +1114,22 @@ bool UavcanMixingInterfaceESC::updateOutputs(float outputs[MAX_ACTUATORS], unsig } } + // Reversible motors: send reverse as a signed RawCommand (negative = reverse). Encoded in + // place so actuator_outputs reflects the actual wire value sent to the ESC. Done here rather + // than via minValue()/maxValue() (as DShot does for its 3D range) because those are uint16_t + // and can't hold the negative bound a signed RawCommand would need. + const uint32_t reversible = mixingOutput().reversibleOutputs(); + + for (unsigned i = 0; i < output_array_size; i++) { + // Encode armed outputs only; a stopped channel sits at the disarmed value and must + // not be inverted to full reverse (the disarmed < min invariant is not guaranteed). + if ((reversible & (1u << i)) && outputs[i] > (float)mixingOutput().disarmedValue(i)) { + const float min_i = (float)mixingOutput().minValue(i); + const float max_i = (float)mixingOutput().maxValue(i); + outputs[i] = math::interpolate(outputs[i], min_i, max_i, -max_i, max_i); + } + } + _esc_controller.update_outputs(outputs, output_array_size); } diff --git a/src/lib/mixer_module/mixer_module.cpp b/src/lib/mixer_module/mixer_module.cpp index 7789c6e3464..d353cd2e91e 100644 --- a/src/lib/mixer_module/mixer_module.cpp +++ b/src/lib/mixer_module/mixer_module.cpp @@ -451,6 +451,7 @@ bool MixingOutput::update() // get output values float outputs[MAX_ACTUATORS]; bool all_disabled = true; + const uint32_t reversible_mask_prev = _reversible_mask; _reversible_mask = 0; for (int i = 0; i < _max_num_outputs; ++i) { @@ -471,6 +472,10 @@ bool MixingOutput::update() } } + if (_reversible_mask != reversible_mask_prev) { + _interface.reversibleMaskChanged(_reversible_mask); + } + // Send output if any function mapped or one last disabling sample if (!all_disabled || !_was_all_disabled) { if (!_armed.armed && !_armed.kill) { diff --git a/src/lib/mixer_module/mixer_module.hpp b/src/lib/mixer_module/mixer_module.hpp index 8f98df5e65d..d2b9d70936b 100644 --- a/src/lib/mixer_module/mixer_module.hpp +++ b/src/lib/mixer_module/mixer_module.hpp @@ -88,6 +88,12 @@ public: /** called whenever the mixer gets updated/reset */ virtual void mixerChanged() {} + + /** + * Called when the reversible output mask changes, before the new mask is used to compute outputs. + * Drivers whose output range depends on reversibility must update it here, not from their Run(). + */ + virtual void reversibleMaskChanged(uint32_t reversible_mask) {} }; /** @@ -202,7 +208,8 @@ public: /** * Get the bitmask of reversible outputs (motors only). - * This might change at any time (while disarmed), so output drivers requiring this should query this regularly. + * This might change at any time, including while armed (motor failure recovery reverses a motor in + * flight). Drivers that must react to a change should override reversibleMaskChanged(). */ uint32_t reversibleOutputs() const { return _reversible_mask; } diff --git a/src/modules/control_allocator/ControlAllocator.cpp b/src/modules/control_allocator/ControlAllocator.cpp index de0c2993ad7..1e36b4c1dcb 100644 --- a/src/modules/control_allocator/ControlAllocator.cpp +++ b/src/modules/control_allocator/ControlAllocator.cpp @@ -40,6 +40,7 @@ */ #include "ControlAllocator.hpp" +#include "VehicleActuatorEffectiveness/ActuatorEffectivenessMultirotor.hpp" #include #include @@ -512,7 +513,12 @@ ControlAllocator::update_effectiveness_matrix_if_needed(EffectivenessUpdateReaso break; } - if (_param_r_rev.get() & (1u << actuator_type_idx)) { + if (_runtime_reversible_bitmask & (1u << actuator_type_idx)) { + // Failure recovery: a forward propeller driven in reverse makes only a fraction of its forward thrust + minimum[selected_matrix](actuator_idx_matrix[selected_matrix]) = -_param_ca_rev_thr_frac.get(); + + } else if (_param_r_rev.get() & (1u << actuator_type_idx)) { + // Statically reversible thruster (symmetric): full reverse authority minimum[selected_matrix](actuator_idx_matrix[selected_matrix]) = -1.f; } else { @@ -543,8 +549,13 @@ ControlAllocator::update_effectiveness_matrix_if_needed(EffectivenessUpdateReaso } } + // Recompute the opposite-motor lookup on any effectiveness update except motor-activation changes + if (reason != EffectivenessUpdateReason::MOTOR_ACTIVATION_UPDATE) { + computeOppositeMotors(); + } + // Handle failed actuators - if (_handled_motor_failure_bitmask) { + if (_handled_motor_failure_bitmask != 0) { actuator_idx = 0; memset(&actuator_idx_matrix, 0, sizeof(actuator_idx_matrix)); @@ -552,11 +563,7 @@ ControlAllocator::update_effectiveness_matrix_if_needed(EffectivenessUpdateReaso int selected_matrix = _control_allocation_selection_indexes[actuator_idx]; if (_handled_motor_failure_bitmask & (1 << motors_idx)) { - ActuatorEffectiveness::EffectivenessMatrix &matrix = config.effectiveness_matrices[selected_matrix]; - - for (int i = 0; i < NUM_AXES; i++) { - matrix(i, actuator_idx_matrix[selected_matrix]) = 0.0f; - } + config.effectiveness_matrices[selected_matrix].setCol(actuator_idx_matrix[selected_matrix], 0.f); } ++actuator_idx_matrix[selected_matrix]; @@ -721,7 +728,7 @@ ControlAllocator::publish_actuator_controls() actuator_servos.timestamp = actuator_motors.timestamp; actuator_servos.timestamp_sample = _timestamp_sample; - actuator_motors.reversible_flags = _param_r_rev.get(); + actuator_motors.reversible_flags = _param_r_rev.get() | _runtime_reversible_bitmask; int actuator_idx = 0; int actuator_idx_matrix[ActuatorEffectiveness::MAX_NUM_MATRICES] {}; @@ -732,6 +739,12 @@ ControlAllocator::publish_actuator_controls() for (motors_idx = 0; motors_idx < _num_actuators[0] && motors_idx < actuator_motors_s::NUM_CONTROLS; motors_idx++) { int selected_matrix = _control_allocation_selection_indexes[actuator_idx]; float actuator_sp = _control_allocation[selected_matrix]->getActuatorSetpoint()(actuator_idx_matrix[selected_matrix]); + + // Recovery motor was solved with min = -CA_REV_THR_FRAC; re-expand to [-1, 0] (static CA_R_REV uses -1, no rescale). + if ((_runtime_reversible_bitmask & (1u << motors_idx)) && PX4_ISFINITE(actuator_sp) && actuator_sp < 0.f) { + actuator_sp /= _param_ca_rev_thr_frac.get(); + } + actuator_motors.control[motors_idx] = PX4_ISFINITE(actuator_sp) ? actuator_sp : NAN; ++actuator_idx_matrix[selected_matrix]; ++actuator_idx; @@ -763,12 +776,43 @@ ControlAllocator::publish_actuator_controls() } } +void +ControlAllocator::computeOppositeMotors() +{ + memset(_opposite_motor, -1, sizeof(_opposite_motor)); + + // Only supported for hexarotor multirotors + if ((_effectiveness_source_id != EffectivenessSource::MULTIROTOR) || + _num_actuators[(int)ActuatorType::MOTORS] != 6) { + return; + } + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) + const auto &geo = static_cast(_actuator_effectiveness)->geometry(); + + for (int i = 0; i < geo.num_rotors; i++) { + float min_dist_sq = FLT_MAX; + + for (int8_t j = 0; j < geo.num_rotors; j++) { + if (geo.rotors[i].moment_ratio * geo.rotors[j].moment_ratio >= 0.f) { continue; } + + const float dist_sq = (Vector2f(geo.rotors[i].position) + Vector2f(geo.rotors[j].position)).norm_squared(); + + if (dist_sq < min_dist_sq) { + min_dist_sq = dist_sq; + _opposite_motor[i] = j; + } + } + } +} + void ControlAllocator::check_for_motor_failures() { failure_detector_status_s failure_detector_status; + const FailureMode failure_mode = static_cast(_param_ca_failure_mode.get()); - if ((FailureMode)_param_ca_failure_mode.get() > FailureMode::IGNORE + if ((failure_mode == FailureMode::REMOVE_AND_STOP_OPPOSITE || failure_mode == FailureMode::REMOVE_AND_REVERSE_OPPOSITE) && _failure_detector_status_sub.update(&failure_detector_status)) { if (_motor_stop_mask != failure_detector_status.motor_stop_mask) { @@ -777,37 +821,43 @@ ControlAllocator::check_for_motor_failures() } if (failure_detector_status.fd_motor) { - if (_handled_motor_failure_bitmask != failure_detector_status.motor_failure_mask) { - // motor failure bitmask changed - switch ((FailureMode)_param_ca_failure_mode.get()) { - case FailureMode::REMOVE_FIRST_FAILING_MOTOR: { - // Count number of failed motors - const int num_motors_failed = math::countSetBits(failure_detector_status.motor_failure_mask); + const int num_motors_failed = math::countSetBits(failure_detector_status.motor_failure_mask); - // Only handle if it is the first failure - if (_handled_motor_failure_bitmask == 0 && num_motors_failed == 1) { - _handled_motor_failure_bitmask = failure_detector_status.motor_failure_mask; - PX4_WARN("Removing motor from allocation (0x%x)", _handled_motor_failure_bitmask); + if (_handled_motor_failure_bitmask == 0 && num_motors_failed == 1) { + _handled_motor_failure_bitmask = failure_detector_status.motor_failure_mask; - for (int i = 0; i < _num_control_allocation; ++i) { - _control_allocation[i]->setHadActuatorFailure(true); - } + const int failed = math::countTrailingZeros(_handled_motor_failure_bitmask); + const int opposite = _opposite_motor[failed]; + const uint16_t opposite_mask = (opposite >= 0) ? (1u << opposite) : 0u; - update_effectiveness_matrix_if_needed(EffectivenessUpdateReason::MOTOR_ACTIVATION_UPDATE); - } - } + // Non-hex frames have no opposite (mask 0), so both modes reduce to dropping the failed motor. + switch (failure_mode) { + case FailureMode::REMOVE_AND_STOP_OPPOSITE: + _handled_motor_failure_bitmask |= opposite_mask; + break; + + case FailureMode::REMOVE_AND_REVERSE_OPPOSITE: + _runtime_reversible_bitmask = opposite_mask; break; default: break; } + PX4_WARN("Handling motor %d failure (mode %d, mask 0x%x)", failed, + (int)failure_mode, _handled_motor_failure_bitmask); + + for (int i = 0; i < _num_control_allocation; ++i) { + _control_allocation[i]->setHadActuatorFailure(true); + } + + update_effectiveness_matrix_if_needed(EffectivenessUpdateReason::MOTOR_ACTIVATION_UPDATE); } } else if (_handled_motor_failure_bitmask != 0) { - // Clear bitmask completely PX4_INFO("Restoring all motors"); _handled_motor_failure_bitmask = 0; + _runtime_reversible_bitmask = 0; for (int i = 0; i < _num_control_allocation; ++i) { _control_allocation[i]->setHadActuatorFailure(false); diff --git a/src/modules/control_allocator/ControlAllocator.hpp b/src/modules/control_allocator/ControlAllocator.hpp index a8ebb762f3a..b56b131f9c3 100644 --- a/src/modules/control_allocator/ControlAllocator.hpp +++ b/src/modules/control_allocator/ControlAllocator.hpp @@ -143,6 +143,9 @@ private: void check_for_motor_failures(); + // Populate _opposite_motor[] with each motor's geometric antipode (hexarotor only); -1 if none. + void computeOppositeMotors(); + void publish_control_allocator_status(int matrix_index); void publish_actuator_controls(); @@ -177,7 +180,8 @@ private: enum class FailureMode { IGNORE = 0, - REMOVE_FIRST_FAILING_MOTOR = 1, + REMOVE_AND_STOP_OPPOSITE = 1, ///< remove failed motor; on a hexarotor also stop its geometric opposite + REMOVE_AND_REVERSE_OPPOSITE = 2, ///< remove failed motor; on a hexarotor reverse its geometric opposite }; EffectivenessSource _effectiveness_source_id{EffectivenessSource::NONE}; @@ -222,6 +226,11 @@ private: uint16_t _handled_motor_failure_bitmask{0}; uint16_t _motor_stop_mask{0}; + // Motor-failure recovery: the geometric-opposite motor is made reversible at runtime to recover + // control authority after a motor failure. + uint16_t _runtime_reversible_bitmask{0}; // motors made reversible at runtime because of failure event + int8_t _opposite_motor[MAX_NUM_MOTORS]; // per-motor index of geometric opposite; -1 if none + ActuatorGroupPreflightCheck _actuator_group_preflight_check; perf_counter_t _loop_perf; /**< loop duration performance counter */ @@ -242,6 +251,7 @@ private: (ParamInt) _param_ca_method, (ParamInt) _param_ca_failure_mode, (ParamInt) _param_r_rev, + (ParamFloat) _param_ca_rev_thr_frac, (ParamFloat) _param_ice_shedding_period ) diff --git a/src/modules/control_allocator/VehicleActuatorEffectiveness/ActuatorEffectivenessMultirotor.hpp b/src/modules/control_allocator/VehicleActuatorEffectiveness/ActuatorEffectivenessMultirotor.hpp index e5b7f3dcf8e..a9c00b90b81 100644 --- a/src/modules/control_allocator/VehicleActuatorEffectiveness/ActuatorEffectivenessMultirotor.hpp +++ b/src/modules/control_allocator/VehicleActuatorEffectiveness/ActuatorEffectivenessMultirotor.hpp @@ -56,6 +56,8 @@ public: const char *name() const override { return "Multirotor"; } + const ActuatorEffectivenessRotors::Geometry &geometry() const { return _mc_rotors.geometry(); } + protected: ActuatorEffectivenessRotors _mc_rotors; }; diff --git a/src/modules/control_allocator/module.yaml b/src/modules/control_allocator/module.yaml index fbd0e72afaa..8571373930f 100644 --- a/src/modules/control_allocator/module.yaml +++ b/src/modules/control_allocator/module.yaml @@ -70,6 +70,16 @@ parameters: 10: Motor 11 11: Motor 12 default: 0 + CA_REV_THR_FRAC: + description: + short: Reverse thrust fraction for reversible motors + long: | + Fraction of forward thrust a reversible motor produces in reverse (e.g. 0.4 = 40%). + This is mostly a property of the propeller. + type: float + min: 0.1 + max: 1.0 + default: 0.4 CA_R${i}_SLEW: description: short: Motor ${i} slew rate limit @@ -614,12 +624,16 @@ parameters: description: short: Motor failure handling mode long: | - This is used to specify how to handle motor failures - reported by failure detector. + What to do on a single motor failure. Ignore disables this feature entirely. Otherwise + the failed motor is removed from the allocation, and on a hexarotor its geometric-opposite + motor is additionally stopped (mode 1) or reversed (mode 2) to recover the lost + yaw/roll/pitch authority; on other airframes only the failed motor is removed. Mode 2 + needs a reverse-capable ESC on the opposite motor. type: enum values: 0: Ignore - 1: Remove first failed motor from effectiveness + 1: Remove failed motor and stop its opposite + 2: Remove failed motor and reverse its opposite default: 0 CA_ICE_PERIOD: