From 55bb872df17cea19e0fb8419c32abff2f40e47be Mon Sep 17 00:00:00 2001 From: Claudio Chies <61051109+Claudio-Chies@users.noreply.github.com> Date: Fri, 21 Aug 2026 14:23:06 +0200 Subject: [PATCH] feat(failure_injection): add ADS-B traffic failure injection and battery severity levels (#27950) * feat(failure_injection): add ADS-B traffic-avoidance failure injection Wire up FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE (107) for the MAVLink-based traffic avoidance path: - OFF suppresses and STUCK freezes the incoming transponder_report, applied both at the MAVLink ADS-B ingestion (handle_message_adsb_vehicle) and at the navigator consumer (check_traffic), so it works for real ADS-B over MAVLink, simulated ADS-B and the fake_traffic command. - OFF additionally marks the ADS-B/FLARM heartbeat unhealthy so the traffic avoidance system health check fails, using a message-less process() overload. - Add the unit to the capability catalogue (OK/OFF/STUCK), the failure console command, the RC-switch unit selector and the docs. The matching MAVLink FAILURE_UNIT enum entry lives in the mavlink submodule (common.xml) and is handled by a separate PR; the uORB mirrors in VehicleCommand.msg and FailureInjection.msg are included here. * feat(failure_injection): enhance battery failure injection with severity levels * feat(failure_injection): improve battery failure handling with dynamic threshold parameters * refactor(failure_injection): remove traffic avoidance example from documentation * docs(docs): subedit * feat(failure_injection): add variance setting for distance sensor and integrate rangefinder in simulator * feat(docs): add failure injection to release notes * docs(docs): Add sim_mavlink back to heading * fix(failure_injection): update default battery failure injection severity to Emergency * docs(docs): get away from footnotes * feat(failure_injection): enhance battery failure injection handling and update traffic unit support * feat(failure_injection): add traffic avoidance handling tests and configurations * [AUTO COMMIT] update EKF change indication See .github/workflows/checks.yml for more details * Apply suggestion from @hamishwillee * feat(failure_injection): update failure types and handling for traffic avoidance and ESC telemetry * fix(typo) * [AUTO COMMIT] update EKF change indication See .github/workflows/checks.yml for more details * fix(docs): clarify notes on GPS and airspeed handling in failure injection documentation --------- Co-authored-by: Claudio Chies Co-authored-by: Hamish Willee --- docs/en/debug/failure_injection.md | 63 ++++++++-- docs/en/releases/main.md | 5 + docs/en/smart_batteries/index.md | 4 +- msg/FailureInjection.msg | 2 + msg/versioned/VehicleCommand.msg | 1 + src/drivers/uavcan/sensors/battery.cpp | 10 +- src/lib/battery/battery.cpp | 5 +- .../drivers/rangefinder/PX4Rangefinder.hpp | 2 + .../failure_injection/FailureInjection.cpp | 55 ++++++-- .../failure_injection/FailureInjection.hpp | 13 +- .../FailureInjectionConfigTest.cpp | 110 ++++++++++++++++ .../FailureInjectionManager.hpp | 5 +- .../FailureInjectionManagerTest.cpp | 43 +++++++ .../FailureTable.cpp | 3 +- .../failure_injection_manager_params.yaml | 15 +++ src/modules/mavlink/CMakeLists.txt | 2 + src/modules/mavlink/mavlink_receiver.cpp | 26 +++- src/modules/mavlink/mavlink_receiver.h | 4 + .../navigator/DetectAndAvoid/CMakeLists.txt | 2 +- .../DetectAndAvoid/detect_and_avoid.cpp | 8 ++ .../DetectAndAvoid/detect_and_avoid.h | 3 + .../simulator_mavlink/CMakeLists.txt | 1 + .../simulator_mavlink/SimulatorMavlink.cpp | 117 ++++++++---------- .../simulator_mavlink/SimulatorMavlink.hpp | 14 +-- src/systemcmds/failure/failure.cpp | 1 + 25 files changed, 412 insertions(+), 102 deletions(-) diff --git a/docs/en/debug/failure_injection.md b/docs/en/debug/failure_injection.md index 5b05f45caea..1c91774c6ee 100644 --- a/docs/en/debug/failure_injection.md +++ b/docs/en/debug/failure_injection.md @@ -1,11 +1,53 @@ # System Failure Injection -System failure injection allows you to induce different types of sensor and system failures, either programmatically using the [MAVSDK failure plugin](https://mavsdk.mavlink.io/main/en/cpp/api_reference/classmavsdk_1_1_failure.html), or "manually" via a PX4 console like the [MAVLink shell](../debug/mavlink_shell.md#mavlink-shell). +System failure injection allows you to induce different types of sensor and system failures, either via MAVLink (using [MAV_CMD_INJECT_FAILURE](https://mavlink.io/en/messages/common.html#MAV_CMD_INJECT_FAILURE) or via the [MAVSDK failure plugin](https://mavsdk.mavlink.io/main/en/cpp/api_reference/classmavsdk_1_1_failure.html)), or "manually" via a PX4 console like the [MAVLink shell](../debug/mavlink_shell.md#mavlink-shell). This enables easier testing of [safety failsafe](../config/safety.md) behaviour, and more generally, of how PX4 behaves when systems and sensors stop working correctly. Failure injection is disabled by default, and can be enabled using the [SYS_FAILURE_EN](../advanced_config/parameter_reference.md#SYS_FAILURE_EN) parameter. -Failures can be injected both in simulation and on real hardware. In simulation the available failures depend on the simulator. On hardware the `off` (stop publishing) and `stuck` (freeze the last value) types are supported for the `gyro`, `accel`, `mag`, `baro`, `distance_sensor` and `gps` components; this requires firmware built with the failure-injection module. In addition, the `battery` component supports `off` (report a depleted pack, triggering the battery failsafe), and the `gps` component supports `wrong` (report the fix type selected by [SYS_FAIL_GPS_WRG](../advanced_config/parameter_reference.md#SYS_FAIL_GPS_WRG), leaving the reported position untouched). +Failures can be injected both in simulation and on real hardware; this requires firmware built with the failure-injection module. +The command always goes through the same firmware failure-injection module — whether it arrives over MAVLink or from the console, the accepted combinations are identical. +What differs is whether a _consumer_ applies the failure, and that depends on the environment. + +## Supported Failure Types + +The table lists the failure types that actually take effect per environment: `off`, `stuck`, `wrong` (`ok` is not listed, but clears an active injection on all environments). +A `—` means the module still accepts the command, but no consumer applies it in that environment. + +| Component | [Gazebo] (gz) | [SIH] | `simulator_mavlink` (Gazebo Classic/JMAVSim) | Hardware | +| ----------------- | ----------------------- | ----------------------- | -------------------------------------------- | ----------------------- | +| `gyro` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | +| `accel` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | +| `mag` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | +| `baro` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | +| `distance_sensor` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | `off`, `stuck` | +| `gps` | — | `off`, `stuck`, `wrong` | `off`, `stuck`, `wrong` | `off`, `stuck`, `wrong` | +| `airspeed` | `off`, `stuck`, `wrong` | — | `off`, `wrong` | — | +| `vio` | — | — | `off` | — | +| `battery` | `off`, `wrong` | `off`, `wrong` | `off`, `wrong` | `off`, `wrong` | +| `traffic` | `off` | `off` | `off` | `off` | +| `motor` | `off` | `off` | `off` | `off` | +| `esc` | `off`, `wrong` | `off`, `wrong` | `off`, `wrong` | `off`, `wrong` | + +[SIH]: ../sim_sih/index.md +[Gazebo]: ../sim_gazebo_gz/index.md + +::: info + +- `gps off | stuck | wrong` on Gazebo (Gz): only available if [SIM_GZ_EN_GPS](../advanced_config/parameter_reference.md#SIM_GZ_EN_GPS) is set to `0` to use the injectable simulated-GPS module. + By default Gazebo publishes GPS from the simulator's own GNSS sensor (`SIM_GZ_EN_GPS` = 1), which is not injectable. +- `airspeed off | stuck | wrong` on Gazebo (Gz): only injectable when airspeed is provided by the simulated-airspeed module ([SENS_EN_ARSPDSIM](../advanced_config/parameter_reference.md#SENS_EN_ARSPDSIM)); worlds that model an airspeed sensor directly are not injected. +- `battery wrong` reports the remaining charge just below the [SYS_FAIL_BAT_LVL](../advanced_config/parameter_reference.md#SYS_FAIL_BAT_LVL) warning threshold to trigger the battery failsafe; `off` stops publishing the battery status entirely. +- `traffic off` suppresses incoming reports and marks the ADS-B/FLARM link unhealthy. +- `motor off` also requires [CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE). +- `esc off` reports the addressed ESC as offline and blanks its telemetry; `esc wrong` keeps it online but reports implausible telemetry (voltage and current at 10% of the real value, RPM 10x). ESCs are addressed by motor instance (the ESC's actuator function), so `-i 1` targets the ESC driving motor 1. +- On hardware, ESC injection is applied only by the UAVCAN (DroneCAN) ESC driver; the other ESC drivers (DShot, Cyphal, VOXL, TAP ESC) publish their telemetry unmodified. + +::: + +Sensors delivered through the shared driver layer (IMU, magnetometer, barometer, rangefinder via the `PX4*` sensor wrappers) support `off`/`stuck` in every environment that uses that layer — including the Gazebo and SIH sensor simulators, which feed synthesized measurements through the same wrappers. +The remaining gaps are backend-specific: GPS and airspeed are handled by dedicated simulator code (see the GPS and airspeed notes in the info box above), SIH does not simulate an injectable airspeed. +Components not listed (`optical_flow`, `servo`, `avoidance`, `rc_signal`, `mavlink_signal`) are rejected everywhere (`MAV_RESULT_UNSUPPORTED`); see the note below on NACK behaviour. ::: info PX4 may accept a command to set a particular failure mode even it that mode is not supported by your simulator. @@ -43,8 +85,10 @@ where: - Systems: - `battery`: Battery - `motor`: Motor + - `esc`: ESC telemetry - `servo`: Servo - - `avoidance`: Avoidance + - `avoidance`: Obstacle/collision avoidance system + - `traffic`: Traffic avoidance (ADS-B/transponder) - `rc_signal`: RC Signal - `mavlink_signal`: MAVLink data telemetry connection - _failure_type_: @@ -58,11 +102,12 @@ where: - `intermittent`: Publish intermittently - _instance number_ (optional): Instance number of affected sensor. 0 (default) indicates all sensors of specified type. -- _instance bitmask_ (optional): address several instances at once (bit 0 = first instance, bit 1 = second, …; decimal or `0x` hex). Used only when `-i` is omitted. Example: `-m 0x5` targets instances 1 and 3. +- _instance bitmask_ (optional): address several instances at once (bit 0 = first instance, bit 1 = second, …; decimal or `0x` hex). Used only when `-i` is omitted. + Example: `-m 0x5` targets instances 1 and 3. ::: info GPS implements only the `off`, `stuck`, and `wrong` failure modes; the other failure types have no effect on it. -`gps wrong` makes the addressed receiver report the fix type selected by [SYS_FAIL_GPS_WRG](../advanced_config/parameter_reference.md#SYS_FAIL_GPS_WRG) and leaves the reported position untouched. +`gps wrong` makes the addressed receiver report the fix type selected by [SYS_FAIL_GPS_WRG](../advanced_config/parameter_reference.md#SYS_FAIL_GPS_WRG) and the jamming state selected by [SYS_FAIL_GPS_JAM](../advanced_config/parameter_reference.md#SYS_FAIL_GPS_JAM) (`Unchanged` keeps the receiver's own state), and leaves the reported position untouched. ::: ## RC Switch Trigger @@ -119,10 +164,14 @@ To stop a motor mid-flight without the system anticipating it or excluding it fr To trigger the battery failsafe by reporting a depleted pack: 1. Enable the [SYS_FAILURE_EN](../advanced_config/parameter_reference.md#SYS_FAILURE_EN) parameter. -2. Enter the following commands on the MAVLink console or SITL _pxh shell_: +2. Optionally select the injected warning level with [SYS_FAIL_BAT_LVL](../advanced_config/parameter_reference.md#SYS_FAIL_BAT_LVL): Warn, Critical or Emergency. The reported remaining charge is set just below the matching threshold ([BAT_LOW_THR](../advanced_config/parameter_reference.md#BAT_LOW_THR), [BAT_CRIT_THR](../advanced_config/parameter_reference.md#BAT_CRIT_THR) or [BAT_EMERGEN_THR](../advanced_config/parameter_reference.md#BAT_EMERGEN_THR)). +3. Enter the following commands on the MAVLink console or SITL _pxh shell_: ```sh - # Report the battery as depleted (warning EMERGENCY) -> battery failsafe + # Report the battery as depleted at the SYS_FAIL_BAT_LVL warning level -> battery failsafe + failure battery wrong + + # Stop publishing the battery status entirely failure battery off # Stop injecting the failure diff --git a/docs/en/releases/main.md b/docs/en/releases/main.md index 2041ee01e0c..e2bb0b268d9 100644 --- a/docs/en/releases/main.md +++ b/docs/en/releases/main.md @@ -54,6 +54,11 @@ 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)). +- [Failure injection](../debug/failure_injection.md) ( [SYS_FAILURE_EN](../advanced_config/parameter_reference.md#SYS_FAILURE_EN)) has been significantly extended. (PX4-Autopilot#27572, PX4-Autopilot#27832, PX4-Autopilot#27950) + - Now applied on real hardware, not just simulators (injection hooks live in the shared sensor drivers). + - Command handling is centralized behind a dedicated failure-injection manager module. + - Multiple sensor instances can be failed simultaneously via a bitmask, and failures can be triggered from an RC switch. + - Changed default behaviour of injected WRONG failure for Batteries, to publish a wrong level, and not stop publishing - [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)) - Added `RTL_TYPE=6` for battery-aware home priority return ([PX4-Autopilot#26968](https://github.com/PX4/PX4-Autopilot/pull/26968)). Returns to home if the estimated flight time to home is within the remaining battery time; otherwise returns to the closest rally point. diff --git a/docs/en/smart_batteries/index.md b/docs/en/smart_batteries/index.md index 758aa9f2057..5316e120034 100644 --- a/docs/en/smart_batteries/index.md +++ b/docs/en/smart_batteries/index.md @@ -10,6 +10,6 @@ PX4 supports (at least) following smart batteries: ### Further Information -- [MAVLink Battery Protocol](https://mavlink.io/en/services/battery.html) -- [batt_smbus](../modules/modules_driver.md) - PX4 SMBus Battery Driver docs +- [Mavlink Battery Protocol](https://mavlink.io/en/services/battery.html) +- [batt_smbus](../modules/modules_driver.md#batt_smbus) - PX4 SMBus Battery Driver docs - [Safety > Low Battery Failsafe](../config/safety.md#battery-level-failsafe). diff --git a/msg/FailureInjection.msg b/msg/FailureInjection.msg index 23d91b97979..5a4bf5b588c 100644 --- a/msg/FailureInjection.msg +++ b/msg/FailureInjection.msg @@ -30,6 +30,7 @@ uint8 FAILURE_UNIT_SYSTEM_AVOIDANCE = 103 uint8 FAILURE_UNIT_SYSTEM_RC_SIGNAL = 104 uint8 FAILURE_UNIT_SYSTEM_MAVLINK_SIGNAL = 105 uint8 FAILURE_UNIT_SYSTEM_ESC = 106 +uint8 FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE = 107 uint16[4] instance_mask # Bit i targets instance (i+1); 0xFFFF = all instances @@ -44,3 +45,4 @@ uint8 FAILURE_TYPE_WRONG = 4 uint8 FAILURE_TYPE_SLOW = 5 uint8 FAILURE_TYPE_DELAYED = 6 uint8 FAILURE_TYPE_INTERMITTENT = 7 +uint8 FAILURE_TYPE_DRIFT = 8 diff --git a/msg/versioned/VehicleCommand.msg b/msg/versioned/VehicleCommand.msg index 44964eb88df..2452888c4ed 100644 --- a/msg/versioned/VehicleCommand.msg +++ b/msg/versioned/VehicleCommand.msg @@ -173,6 +173,7 @@ uint8 FAILURE_UNIT_SYSTEM_AVOIDANCE = 103 uint8 FAILURE_UNIT_SYSTEM_RC_SIGNAL = 104 uint8 FAILURE_UNIT_SYSTEM_MAVLINK_SIGNAL = 105 uint8 FAILURE_UNIT_SYSTEM_ESC = 106 +uint8 FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE = 107 uint8 FAILURE_TYPE_OK = 0 uint8 FAILURE_TYPE_OFF = 1 diff --git a/src/drivers/uavcan/sensors/battery.cpp b/src/drivers/uavcan/sensors/battery.cpp index ceba432a2b1..faec61b34c9 100644 --- a/src/drivers/uavcan/sensors/battery.cpp +++ b/src/drivers/uavcan/sensors/battery.cpp @@ -42,10 +42,14 @@ const char *const UavcanBatteryBridge::NAME = "battery"; void UavcanBatteryBridge::publishBattery(int node_id, uint8_t instance) { _failure_config.update(); - const uint8_t id = _battery_status[instance].id; - failure_injection::process_battery(_failure_config, id > 0 ? id : instance + 1, _battery_status[instance]); - publish(node_id, &_battery_status[instance]); + battery_status_s battery_status = _battery_status[instance]; + + if (!failure_injection::process_battery(_failure_config, instance + 1, battery_status)) { + return; + } + + publish(node_id, &battery_status); } UavcanBatteryBridge::UavcanBatteryBridge(uavcan::INode &node, NodeInfoPublisher *node_info_publisher) : diff --git a/src/lib/battery/battery.cpp b/src/lib/battery/battery.cpp index daf37589236..8b952a51e8a 100644 --- a/src/lib/battery/battery.cpp +++ b/src/lib/battery/battery.cpp @@ -212,7 +212,10 @@ void Battery::updateAndPublishBatteryStatus(const hrt_abstime ×tamp) battery_status_s battery_status = getBatteryStatus(); _failure_config.update(); - failure_injection::process_battery(_failure_config, battery_status.id, battery_status); + + if (!failure_injection::process_battery(_failure_config, battery_status.id, battery_status)) { + return; + } publishBatteryStatus(battery_status); } diff --git a/src/lib/drivers/rangefinder/PX4Rangefinder.hpp b/src/lib/drivers/rangefinder/PX4Rangefinder.hpp index 819f3e97e5d..c77641857cc 100644 --- a/src/lib/drivers/rangefinder/PX4Rangefinder.hpp +++ b/src/lib/drivers/rangefinder/PX4Rangefinder.hpp @@ -60,6 +60,8 @@ public: void set_max_distance(const float distance) { _distance_sensor_pub.get().max_distance = distance; } void set_min_distance(const float distance) { _distance_sensor_pub.get().min_distance = distance; } + void set_variance(const float variance) { _distance_sensor_pub.get().variance = variance; } + void set_orientation(const uint8_t device_orientation = distance_sensor_s::ROTATION_DOWNWARD_FACING); void set_mode(const uint8_t mode) { _distance_sensor_pub.get().mode = mode; } diff --git a/src/lib/failure_injection/FailureInjection.cpp b/src/lib/failure_injection/FailureInjection.cpp index c084f691e78..6efb4000122 100644 --- a/src/lib/failure_injection/FailureInjection.cpp +++ b/src/lib/failure_injection/FailureInjection.cpp @@ -74,7 +74,7 @@ Mode Config::mode(uint8_t unit, uint8_t instance) const // instance == 0 matches any instance of the unit; otherwise match the // 1-based instance against the bitmask (0xFFFF covers all instances). - if (instance == 0 || (_instance_mask[i] & (1u << (instance - 1)))) { + if (instance == 0 || (instance <= 16 && (_instance_mask[i] & (1u << (instance - 1))))) { return _failure_type[i]; } } @@ -82,15 +82,56 @@ Mode Config::mode(uint8_t unit, uint8_t instance) const return Mode::Ok; } -void process_battery(const Config &config, uint8_t instance, battery_status_s &battery_status) +bool process_battery(const Config &config, uint8_t instance, battery_status_s &battery_status) { - if (config.mode(failure_injection_s::FAILURE_UNIT_SYSTEM_BATTERY, instance) != Mode::Off) { - return; + const Mode mode = config.mode(failure_injection_s::FAILURE_UNIT_SYSTEM_BATTERY, instance); + static constexpr float trigger_margin = 0.01f; // report remaining charge just below the threshold + + if (mode == Mode::Off) { + // Suppress the publication so the pack reads disconnected. + return false; } - // Report a depleted pack so the low-battery failsafe triggers. - battery_status.remaining = 0.f; - battery_status.warning = battery_status_s::WARNING_EMERGENCY; + if (mode != Mode::Wrong) { + return true; + } + + static const param_t level_handle = param_find("SYS_FAIL_BAT_LVL"); + static const param_t low_thr_handle = param_find("BAT_LOW_THR"); + static const param_t crit_thr_handle = param_find("BAT_CRIT_THR"); + static const param_t emergen_thr_handle = param_find("BAT_EMERGEN_THR"); + + int32_t level = battery_status_s::WARNING_CRITICAL; + param_get(level_handle, &level); + + param_t threshold_handle = crit_thr_handle; + + switch (level) { + case battery_status_s::WARNING_LOW: + threshold_handle = low_thr_handle; + break; + + case battery_status_s::WARNING_EMERGENCY: + threshold_handle = emergen_thr_handle; + break; + + case battery_status_s::WARNING_CRITICAL: + default: + level = battery_status_s::WARNING_CRITICAL; + threshold_handle = crit_thr_handle; + break; + } + + battery_status.warning = level; + + + // Report the remaining charge just below the selected threshold so the + // matching stage of the low-battery failsafe triggers. + float threshold = 0.f; + param_get(threshold_handle, &threshold); + battery_status.remaining = (threshold > trigger_margin) ? (threshold - trigger_margin) : 0.f; + + return true; } bool process_gnss(const Config &config, uint8_t uorb_instance, sensor_gps_s &sensor_gps, diff --git a/src/lib/failure_injection/FailureInjection.hpp b/src/lib/failure_injection/FailureInjection.hpp index 7a0b5046c6a..c7f4df3ba72 100644 --- a/src/lib/failure_injection/FailureInjection.hpp +++ b/src/lib/failure_injection/FailureInjection.hpp @@ -191,11 +191,14 @@ inline bool process(const Config &config, uint8_t unit, uint8_t uorb_instance) } /** - * Battery counterpart to process(): on FAILURE_UNIT_SYSTEM_BATTERY Off for the given 1-based - * instance, report a depleted pack (zero remaining, emergency warning) so the low-battery - * failsafe triggers. Mutates rather than suppresses, so the pack reads empty not disconnected. + * Battery counterpart to process(): on FAILURE_UNIT_SYSTEM_BATTERY for the given 1-based + * instance, Off suppresses the publication (the pack reads disconnected) and Wrong reports the + * warning level selected by SYS_FAIL_BAT_LVL with the remaining charge just below the matching + * threshold, so that stage of the low-battery failsafe triggers. + * + * @return false if the battery_status publication must be suppressed (Off), true otherwise. */ -void process_battery(const Config &config, uint8_t instance, battery_status_s &battery_status); +bool process_battery(const Config &config, uint8_t instance, battery_status_s &battery_status); /** * GNSS counterpart to process(): on FAILURE_UNIT_SENSOR_GPS for the receiver publishing on the @@ -244,7 +247,7 @@ inline bool process(Mode) { return true; } inline bool process(const Config &, uint8_t, uint8_t) { return true; } -inline void process_battery(const Config &, uint8_t, battery_status_s &) {} +inline bool process_battery(const Config &, uint8_t, battery_status_s &) { return true; } inline bool process_gnss(const Config &, uint8_t, sensor_gps_s &, Stuck &) { return true; } diff --git a/src/modules/failure_injection_manager/FailureInjectionConfigTest.cpp b/src/modules/failure_injection_manager/FailureInjectionConfigTest.cpp index d1f204d8b56..d4b956af1f1 100644 --- a/src/modules/failure_injection_manager/FailureInjectionConfigTest.cpp +++ b/src/modules/failure_injection_manager/FailureInjectionConfigTest.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include // FailureInjection.hpp transitively pulls in px4_platform_common/defines.h (via @@ -104,6 +105,8 @@ constexpr uint8_t GYRO = failure_injection_s::FAILURE_UNIT_SENSOR_GYRO; constexpr uint8_t GPS = failure_injection_s::FAILURE_UNIT_SENSOR_GPS; constexpr uint8_t MOTOR = failure_injection_s::FAILURE_UNIT_SYSTEM_MOTOR; constexpr uint8_t ESC = failure_injection_s::FAILURE_UNIT_SYSTEM_ESC; +constexpr uint8_t BATTERY = failure_injection_s::FAILURE_UNIT_SYSTEM_BATTERY; +constexpr uint8_t TRAFFIC = failure_injection_s::FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE; constexpr uint8_t OK = failure_injection_s::FAILURE_TYPE_OK; constexpr uint8_t OFF = failure_injection_s::FAILURE_TYPE_OFF; @@ -487,3 +490,110 @@ TEST(FailureInjectionConfig, ProcessEscWrongScalesTelemetryButStaysOnline) EXPECT_EQ(status.esc[0].esc_rpm, 40000); // 4000 * 10 EXPECT_FLOAT_EQ(status.esc[1].esc_voltage, 16.f); // other ESCs untouched } + +// =========================================================================== +// Traffic avoidance (ADS-B): OFF-only, message-less consumers +// =========================================================================== + +TEST(FailureInjectionConfig, TrafficOffSuppressesAtBothConsumers) +{ + Config config; + config.set(make_config(TRAFFIC, 0xFFFF, OFF)); + + // Both consumers (MavlinkReceiver ADS-B ingestion, DetectAndAvoid queue drain) + // and the ADS-B/FLARM heartbeat check call the message-less overload with + // uORB instance 0, which maps to failure instance 1. + EXPECT_FALSE(process(config, TRAFFIC, 0)); + EXPECT_EQ(config.mode(TRAFFIC, 1), Mode::Off); +} + +TEST(FailureInjectionConfig, TrafficOkLetsReportsThrough) +{ + Config config; + EXPECT_TRUE(process(config, TRAFFIC, 0)); + + config.set(make_config(TRAFFIC, 0xFFFF, OK)); + EXPECT_TRUE(process(config, TRAFFIC, 0)); + EXPECT_EQ(config.mode(TRAFFIC, 1), Mode::Ok); +} + +TEST(FailureInjectionConfig, TrafficOffLeavesOtherUnitsUntouched) +{ + Config config; + config.set(make_config(TRAFFIC, 0xFFFF, OFF)); + + EXPECT_EQ(config.mode(GYRO, 1), Mode::Ok); + EXPECT_TRUE(process(config, GYRO, 0)); +} + +// =========================================================================== +// process_battery(): SYS_FAIL_BAT_LVL severity mapping +// =========================================================================== + +TEST(FailureInjectionConfig, ProcessBatteryWrongMapsSeverityToWarning) +{ + // The test runner has no work queue for the autosave param_set would schedule. + param_control_autosave(false); + + Config config; + config.set(make_config(BATTERY, 0x1, WRONG)); + + const struct { + int32_t level; + uint8_t expected_warning; + const char *threshold_param; + } cases[] = { + {1, battery_status_s::WARNING_LOW, "BAT_LOW_THR"}, + {2, battery_status_s::WARNING_CRITICAL, "BAT_CRIT_THR"}, + {3, battery_status_s::WARNING_EMERGENCY, "BAT_EMERGEN_THR"}, + {99, battery_status_s::WARNING_CRITICAL, "BAT_CRIT_THR"}, // out of range falls back to the default + }; + + for (const auto &c : cases) { + ASSERT_EQ(param_set(param_find("SYS_FAIL_BAT_LVL"), &c.level), 0); + + float threshold{}; + ASSERT_EQ(param_get(param_find(c.threshold_param), &threshold), 0); + + battery_status_s status{}; + status.remaining = 0.8f; + status.warning = battery_status_s::WARNING_NONE; + + EXPECT_TRUE(process_battery(config, 1, status)); + EXPECT_EQ(status.warning, c.expected_warning); + EXPECT_FLOAT_EQ(status.remaining, (threshold > 0.01f) ? (threshold - 0.01f) : 0.f); + EXPECT_LT(status.remaining, threshold); + } + + const int32_t default_level = battery_status_s::WARNING_CRITICAL; + param_set(param_find("SYS_FAIL_BAT_LVL"), &default_level); +} + +TEST(FailureInjectionConfig, ProcessBatteryOffSuppressesPublication) +{ + Config config; + config.set(make_config(BATTERY, 0x1, OFF)); + + battery_status_s status{}; + status.remaining = 0.8f; + status.warning = battery_status_s::WARNING_NONE; + + EXPECT_FALSE(process_battery(config, 1, status)); + // Off suppresses instead of mutating. + EXPECT_FLOAT_EQ(status.remaining, 0.8f); + EXPECT_EQ(status.warning, battery_status_s::WARNING_NONE); +} + +TEST(FailureInjectionConfig, ProcessBatteryLeavesUnselectedInstanceUntouched) +{ + Config config; + config.set(make_config(BATTERY, 0x2, WRONG)); // instance 2 only + + battery_status_s status{}; + status.remaining = 0.8f; + status.warning = battery_status_s::WARNING_NONE; + + EXPECT_TRUE(process_battery(config, 1, status)); + EXPECT_FLOAT_EQ(status.remaining, 0.8f); + EXPECT_EQ(status.warning, battery_status_s::WARNING_NONE); +} diff --git a/src/modules/failure_injection_manager/FailureInjectionManager.hpp b/src/modules/failure_injection_manager/FailureInjectionManager.hpp index 4d63a31c328..5ce4c198017 100644 --- a/src/modules/failure_injection_manager/FailureInjectionManager.hpp +++ b/src/modules/failure_injection_manager/FailureInjectionManager.hpp @@ -103,9 +103,10 @@ private: (ParamInt) _param_sys_fail_rc_unit, (ParamInt) _param_sys_fail_rc_mode, (ParamInt) _param_sys_fail_rc_inst, - // Consumed via param_find() in failure_injection::process_gnss(); registered + // Consumed via param_find() in failure_injection::process_XXXX(); registered // here so it is marked used and shows up in the GCS parameter list. (ParamInt) _param_sys_fail_gps_wrg, - (ParamInt) _param_sys_fail_gps_jam + (ParamInt) _param_sys_fail_gps_jam, + (ParamInt) _param_sys_fail_bat_lvl ) }; diff --git a/src/modules/failure_injection_manager/FailureInjectionManagerTest.cpp b/src/modules/failure_injection_manager/FailureInjectionManagerTest.cpp index dcc5ea6bee1..699d9056551 100644 --- a/src/modules/failure_injection_manager/FailureInjectionManagerTest.cpp +++ b/src/modules/failure_injection_manager/FailureInjectionManagerTest.cpp @@ -49,6 +49,7 @@ constexpr uint8_t GYRO = failure_injection_s::FAILURE_UNIT_SENSOR_GYRO; constexpr uint8_t GPS = failure_injection_s::FAILURE_UNIT_SENSOR_GPS; constexpr uint8_t MOTOR = failure_injection_s::FAILURE_UNIT_SYSTEM_MOTOR; constexpr uint8_t ESC = failure_injection_s::FAILURE_UNIT_SYSTEM_ESC; +constexpr uint8_t TRAFFIC = failure_injection_s::FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE; constexpr uint8_t OK = failure_injection_s::FAILURE_TYPE_OK; constexpr uint8_t OFF = failure_injection_s::FAILURE_TYPE_OFF; @@ -75,10 +76,52 @@ TEST(FailureTable, SupportedCatalogueMatchesInventory) EXPECT_TRUE(FailureTable::isSupported(failure_injection_s::FAILURE_UNIT_SENSOR_DISTANCE_SENSOR, OFF)); EXPECT_TRUE(FailureTable::isSupported(failure_injection_s::FAILURE_UNIT_SENSOR_DISTANCE_SENSOR, STUCK)); EXPECT_FALSE(FailureTable::isSupported(failure_injection_s::FAILURE_UNIT_SENSOR_DISTANCE_SENSOR, WRONG)); + // Traffic avoidance supports OFF (blind) + EXPECT_TRUE(FailureTable::isSupported(TRAFFIC, OK)); + EXPECT_TRUE(FailureTable::isSupported(TRAFFIC, OFF)); + EXPECT_FALSE(FailureTable::isSupported(TRAFFIC, STUCK)); + EXPECT_FALSE(FailureTable::isSupported(TRAFFIC, WRONG)); // Unimplemented units. EXPECT_FALSE(FailureTable::isSupported(failure_injection_s::FAILURE_UNIT_SYSTEM_RC_SIGNAL, OFF)); } +TEST(FailureTable, TrafficStuckIsRejectedWithoutChange) +{ + FailureTable table; + // The traffic picture is a queue of reports from several aircraft, so there is no + // single value to freeze: STUCK must NACK and leave the table untouched. + EXPECT_EQ(table.inject(TRAFFIC, STUCK, 0), AckResult::Unsupported); + EXPECT_FALSE(table.changed()); + EXPECT_EQ(table.count(), 0); +} + +TEST(FailureTable, TrafficOffIsAcceptedForAllInstances) +{ + FailureTable table; + EXPECT_EQ(table.inject(TRAFFIC, OFF, 0), AckResult::Accepted); + EXPECT_TRUE(table.changed()); + + failure_injection_s msg{}; + table.fill(msg); + ASSERT_EQ(msg.count, 1); + EXPECT_EQ(msg.unit[0], TRAFFIC); + EXPECT_EQ(msg.failure_type[0], OFF); + // Both traffic consumers look the unit up with instance 0, which the config + // resolves as failure instance 1, so the entry has to cover it. + EXPECT_EQ(msg.instance_mask[0], 0xFFFF); +} + +TEST(FailureTable, TrafficOkClearsOffEntry) +{ + FailureTable table; + ASSERT_EQ(table.inject(TRAFFIC, OFF, 0), AckResult::Accepted); + table.clearChanged(); + + EXPECT_EQ(table.inject(TRAFFIC, OK, 0), AckResult::Accepted); + EXPECT_TRUE(table.changed()); + EXPECT_EQ(table.count(), 0); +} + TEST(FailureTable, UnsupportedIsRejectedWithoutChange) { FailureTable table; diff --git a/src/modules/failure_injection_manager/FailureTable.cpp b/src/modules/failure_injection_manager/FailureTable.cpp index 4332fd2fa64..26d1838b7b0 100644 --- a/src/modules/failure_injection_manager/FailureTable.cpp +++ b/src/modules/failure_injection_manager/FailureTable.cpp @@ -60,12 +60,13 @@ bool FailureTable::isSupported(uint8_t unit, uint8_t type) || type == failure_injection_s::FAILURE_TYPE_WRONG; case failure_injection_s::FAILURE_UNIT_SENSOR_VIO: - case failure_injection_s::FAILURE_UNIT_SYSTEM_BATTERY: case failure_injection_s::FAILURE_UNIT_SYSTEM_MOTOR: + case failure_injection_s::FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE: // multi-target queue: no single value to freeze return type == failure_injection_s::FAILURE_TYPE_OK || type == failure_injection_s::FAILURE_TYPE_OFF; case failure_injection_s::FAILURE_UNIT_SYSTEM_ESC: + case failure_injection_s::FAILURE_UNIT_SYSTEM_BATTERY: return type == failure_injection_s::FAILURE_TYPE_OK || type == failure_injection_s::FAILURE_TYPE_OFF || type == failure_injection_s::FAILURE_TYPE_WRONG; diff --git a/src/modules/failure_injection_manager/failure_injection_manager_params.yaml b/src/modules/failure_injection_manager/failure_injection_manager_params.yaml index 38bdfdd0a05..bd73990a37a 100644 --- a/src/modules/failure_injection_manager/failure_injection_manager_params.yaml +++ b/src/modules/failure_injection_manager/failure_injection_manager_params.yaml @@ -51,6 +51,7 @@ parameters: 8: Airspeed 100: Battery 101: Motor + 107: Traffic avoidance SYS_FAIL_RC_MODE: description: short: Failure type applied by the RC switch @@ -114,3 +115,17 @@ parameters: 1: OK 2: Mitigated 3: Detected + SYS_FAIL_BAT_LVL: + description: + short: Battery failure injection severity + long: |- + Battery warning level reported while a battery 'wrong' failure + injection is active. The injected remaining charge is set just below + the matching threshold (BAT_LOW_THR, BAT_CRIT_THR or + BAT_EMERGEN_THR). + type: enum + default: 3 + values: + 1: Warn + 2: Critical + 3: Emergency diff --git a/src/modules/mavlink/CMakeLists.txt b/src/modules/mavlink/CMakeLists.txt index c927d3d42b0..80c580afc38 100644 --- a/src/modules/mavlink/CMakeLists.txt +++ b/src/modules/mavlink/CMakeLists.txt @@ -150,6 +150,8 @@ if(CONFIG_DRIVERS_SERIALPASSTHROUGH) target_link_libraries(modules__mavlink PRIVATE drivers__serialpassthrough) endif() +target_link_libraries(modules__mavlink PRIVATE failure_injection) + px4_add_unit_gtest(SRC MavlinkStatustextHandlerTest.cpp INCLUDES ${MAVLINK_LIBRARY_DIR} diff --git a/src/modules/mavlink/mavlink_receiver.cpp b/src/modules/mavlink/mavlink_receiver.cpp index 89e92071f07..4d90ba211c6 100644 --- a/src/modules/mavlink/mavlink_receiver.cpp +++ b/src/modules/mavlink/mavlink_receiver.cpp @@ -2025,6 +2025,12 @@ MavlinkReceiver::handle_message_battery_status(mavlink_message_t *msg) } } + _failure_config.update(); + + if (!failure_injection::process_battery(_failure_config, 1, battery_status)) { + return; + } + _battery_pub.publish(battery_status); } @@ -2645,6 +2651,12 @@ MavlinkReceiver::publish_hil_battery() hil_battery_status.voltage_cell_v[cell_count] = cells_v; } + _failure_config.update(); + + if (!failure_injection::process_battery(_failure_config, 1, hil_battery_status)) { + return; + } + _battery_pub.publish(hil_battery_status); } @@ -2886,6 +2898,12 @@ MavlinkReceiver::handle_message_adsb_vehicle(mavlink_message_t *msg) //PX4_INFO("code: %d callsign: %s, vel: %8.4f, tslc: %d", (int)t.ICAO_address, t.callsign, (double)t.hor_velocity, (int)t.tslc); + _failure_config.update(); + + if (!failure_injection::process(_failure_config, failure_injection_s::FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE, 0)) { + return; + } + _transponder_report_pub.publish(t); } @@ -3480,12 +3498,16 @@ void MavlinkReceiver::CheckHeartbeats(const hrt_abstime &t, bool force) _mavlink.lock_telemetry_status(); telemetry_status_s &tstatus = _mavlink.telemetry_status(); + _failure_config.update(); + const bool traffic_avoidance_ok = failure_injection::process(_failure_config, + failure_injection_s::FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE, 0); + tstatus.heartbeat_type_antenna_tracker = (t <= TIMEOUT + _heartbeat_type_antenna_tracker); tstatus.heartbeat_type_gcs = (t <= TIMEOUT + _heartbeat_type_gcs); tstatus.heartbeat_type_onboard_controller = (t <= TIMEOUT + _heartbeat_type_onboard_controller); tstatus.heartbeat_type_gimbal = (t <= TIMEOUT + _heartbeat_type_gimbal); - tstatus.heartbeat_type_adsb = (t <= TIMEOUT + _heartbeat_type_adsb); - tstatus.heartbeat_type_flarm = (t <= TIMEOUT + _heartbeat_type_flarm); + tstatus.heartbeat_type_adsb = traffic_avoidance_ok && (t <= TIMEOUT + _heartbeat_type_adsb); + tstatus.heartbeat_type_flarm = traffic_avoidance_ok && (t <= TIMEOUT + _heartbeat_type_flarm); tstatus.heartbeat_type_camera = (t <= TIMEOUT + _heartbeat_type_camera); tstatus.heartbeat_type_parachute = (t <= TIMEOUT + _heartbeat_type_parachute); tstatus.heartbeat_type_open_drone_id = (t <= TIMEOUT + _heartbeat_type_open_drone_id); diff --git a/src/modules/mavlink/mavlink_receiver.h b/src/modules/mavlink/mavlink_receiver.h index 16756dc28a9..51e5ae76b89 100644 --- a/src/modules/mavlink/mavlink_receiver.h +++ b/src/modules/mavlink/mavlink_receiver.h @@ -57,6 +57,8 @@ #include #include #include + +#include #include #include #include @@ -411,6 +413,8 @@ private: uORB::Publication _cmd_pub{ORB_ID(vehicle_command)}; uORB::Publication _cmd_ack_pub{ORB_ID(vehicle_command_ack)}; + failure_injection::Config _failure_config; + // ORB subscriptions uORB::Subscription _actuator_armed_sub{ORB_ID(actuator_armed)}; uORB::Subscription _home_position_sub{ORB_ID(home_position)}; diff --git a/src/modules/navigator/DetectAndAvoid/CMakeLists.txt b/src/modules/navigator/DetectAndAvoid/CMakeLists.txt index df65281440a..4b13950f27b 100644 --- a/src/modules/navigator/DetectAndAvoid/CMakeLists.txt +++ b/src/modules/navigator/DetectAndAvoid/CMakeLists.txt @@ -50,7 +50,7 @@ if(CONFIG_NAVIGATOR_ADSB_F3442) set_property(GLOBAL APPEND PROPERTY PX4_MODULE_CONFIG_FILES ${CMAKE_CURRENT_SOURCE_DIR}/detect_and_avoid_f3442_params.yaml) endif() -target_link_libraries(detect_and_avoid PUBLIC adsb) +target_link_libraries(detect_and_avoid PUBLIC adsb PRIVATE failure_injection) # The functional tests use the fake-traffic injector. if(CONFIG_NAVIGATOR_ADSB_FAKE_TRAFFIC) diff --git a/src/modules/navigator/DetectAndAvoid/detect_and_avoid.cpp b/src/modules/navigator/DetectAndAvoid/detect_and_avoid.cpp index db3feb5f6c4..0cf9b95a870 100644 --- a/src/modules/navigator/DetectAndAvoid/detect_and_avoid.cpp +++ b/src/modules/navigator/DetectAndAvoid/detect_and_avoid.cpp @@ -268,12 +268,20 @@ bool DetectAndAvoid::process_transponder_queue(daa_input_s &daa_input) const hrt_abstime traffic_timeout_us = static_cast(_param_daa_traff_tout.get()) * 1_s; + _failure_config.update(); + const bool traffic_blocked = !failure_injection::process(_failure_config, + failure_injection_s::FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE, 0); + for (uint8_t processed_reports = 0; processed_reports < transponder_report_s::ORB_QUEUE_LENGTH; ++processed_reports) { if (!_traffic_sub.update(&transponder_report)) { break; } + if (traffic_blocked) { + continue; + } + #if defined(DEBUG_BUILD) debug_print_transponder_report(transponder_report); #endif diff --git a/src/modules/navigator/DetectAndAvoid/detect_and_avoid.h b/src/modules/navigator/DetectAndAvoid/detect_and_avoid.h index e35f3629d34..74795ddbfdd 100644 --- a/src/modules/navigator/DetectAndAvoid/detect_and_avoid.h +++ b/src/modules/navigator/DetectAndAvoid/detect_and_avoid.h @@ -51,6 +51,7 @@ #include #include #include +#include #include #include #include @@ -202,6 +203,8 @@ private: uORB::Subscription _traffic_sub {ORB_ID(transponder_report)}; AdsbConflict _adsb_conflict_detector; + failure_injection::Config _failure_config; + daa_ownship_ids_s _ownship_ids{}; void refresh_ownship_ids(); diff --git a/src/modules/simulation/simulator_mavlink/CMakeLists.txt b/src/modules/simulation/simulator_mavlink/CMakeLists.txt index 05a28429f55..749cc22cf57 100644 --- a/src/modules/simulation/simulator_mavlink/CMakeLists.txt +++ b/src/modules/simulation/simulator_mavlink/CMakeLists.txt @@ -53,6 +53,7 @@ px4_add_module( drivers_barometer drivers_gyroscope drivers_magnetometer + drivers_rangefinder ) include(sitl_targets_flightgear.cmake) diff --git a/src/modules/simulation/simulator_mavlink/SimulatorMavlink.cpp b/src/modules/simulation/simulator_mavlink/SimulatorMavlink.cpp index 810c4e0dffd..b1b37177289 100644 --- a/src/modules/simulation/simulator_mavlink/SimulatorMavlink.cpp +++ b/src/modules/simulation/simulator_mavlink/SimulatorMavlink.cpp @@ -1467,85 +1467,74 @@ void SimulatorMavlink::updateFailureConfig() _vio_blocked = (_failure_config.mode(failure_injection_s::FAILURE_UNIT_SENSOR_VIO, 1) == failure_injection::Mode::Off); } +static uint8_t distance_sensor_orientation(uint8_t mavlink_orientation) +{ + switch (mavlink_orientation) { + case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_PITCH_270: + return distance_sensor_s::ROTATION_DOWNWARD_FACING; + + case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_PITCH_90: + return distance_sensor_s::ROTATION_UPWARD_FACING; + + case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_PITCH_180: + return distance_sensor_s::ROTATION_BACKWARD_FACING; + + case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_NONE: + return distance_sensor_s::ROTATION_FORWARD_FACING; + + case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_YAW_270: + return distance_sensor_s::ROTATION_LEFT_FACING; + + case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_YAW_90: + return distance_sensor_s::ROTATION_RIGHT_FACING; + + default: + return distance_sensor_s::ROTATION_CUSTOM; + } +} + int SimulatorMavlink::publish_distance_topic(const mavlink_distance_sensor_t *dist_mavlink) { - distance_sensor_s dist{}; - dist.timestamp = hrt_absolute_time(); - dist.min_distance = dist_mavlink->min_distance / 100.0f; - dist.max_distance = dist_mavlink->max_distance / 100.0f; - dist.current_distance = dist_mavlink->current_distance / 100.0f; - dist.type = dist_mavlink->type; - dist.variance = dist_mavlink->covariance * 1e-4f; // cm^2 to m^2 - device::Device::DeviceId device_id {}; device_id.devid_s.bus_type = device::Device::DeviceBusType_SIMULATION; device_id.devid_s.address = dist_mavlink->id; device_id.devid_s.devtype = DRV_DIST_DEVTYPE_SIM; - dist.device_id = device_id.devid; + // Reuse the slot already claimed by this device id, otherwise claim and configure a free one. + PX4Rangefinder *rangefinder = nullptr; - // MAVLink DISTANCE_SENSOR signal_quality value of 0 means unset/unknown - // quality value. Also it comes normalised between 1 and 100 while the uORB - // signal quality is normalised between 0 and 100. - dist.signal_quality = dist_mavlink->signal_quality == 0 ? -1 : 100 * (dist_mavlink->signal_quality - 1) / 99; - - switch (dist_mavlink->orientation) { - case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_PITCH_270: - dist.orientation = distance_sensor_s::ROTATION_DOWNWARD_FACING; - break; - - case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_PITCH_90: - dist.orientation = distance_sensor_s::ROTATION_UPWARD_FACING; - break; - - case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_PITCH_180: - dist.orientation = distance_sensor_s::ROTATION_BACKWARD_FACING; - break; - - case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_NONE: - dist.orientation = distance_sensor_s::ROTATION_FORWARD_FACING; - break; - - case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_YAW_270: - dist.orientation = distance_sensor_s::ROTATION_LEFT_FACING; - break; - - case MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_YAW_90: - dist.orientation = distance_sensor_s::ROTATION_RIGHT_FACING; - break; - - default: - dist.orientation = distance_sensor_s::ROTATION_CUSTOM; - } - - dist.h_fov = dist_mavlink->horizontal_fov; - dist.v_fov = dist_mavlink->vertical_fov; - dist.q[0] = dist_mavlink->quaternion[0]; - dist.q[1] = dist_mavlink->quaternion[1]; - dist.q[2] = dist_mavlink->quaternion[2]; - dist.q[3] = dist_mavlink->quaternion[3]; - - // New publishers will be created based on the sensor ID's being different or not - for (size_t i = 0; i < sizeof(_dist_sensor_ids) / sizeof(_dist_sensor_ids[0]); i++) { - if (_dist_pubs[i] && _dist_sensor_ids[i] == dist.device_id) { - _dist_pubs[i]->publish(dist); + for (size_t i = 0; i < DIST_SENSOR_COUNT_MAX; i++) { + if (_dist_sensor_ids[i] == device_id.devid) { + rangefinder = &_px4_rangefinder[i]; break; - } - if (_dist_pubs[i] == nullptr) { - _dist_pubs[i] = new uORB::PublicationMulti {ORB_ID(distance_sensor)}; - - if (_dist_pubs[i] == nullptr) { - break; - } - - _dist_sensor_ids[i] = dist.device_id; - _dist_pubs[i]->publish(dist); + if (_dist_sensor_ids[i] == 0) { + rangefinder = &_px4_rangefinder[i]; + rangefinder->set_device_id(device_id.devid); + rangefinder->set_orientation(distance_sensor_orientation(dist_mavlink->orientation)); + rangefinder->set_min_distance(dist_mavlink->min_distance / 100.0f); + rangefinder->set_max_distance(dist_mavlink->max_distance / 100.0f); + rangefinder->set_rangefinder_type(dist_mavlink->type); + rangefinder->set_hfov(dist_mavlink->horizontal_fov); + rangefinder->set_vfov(dist_mavlink->vertical_fov); + _dist_sensor_ids[i] = device_id.devid; break; } } + if (rangefinder == nullptr) { + PX4_ERR("No free simulated distance sensor slot. Max: %d", DIST_SENSOR_COUNT_MAX); + return PX4_ERROR; + } + + // MAVLink signal_quality: 0 means unknown (-1 in uORB) and 1..100 remaps to 0..100. + const int8_t signal_quality = dist_mavlink->signal_quality == 0 ? -1 : 100 * (dist_mavlink->signal_quality - 1) / 99; + rangefinder->set_variance(dist_mavlink->covariance * 1e-4f); // cm^2 to m^2 + // update() applies distance-sensor failure injection internally before publishing. + rangefinder->update(hrt_absolute_time(), dist_mavlink->current_distance * 0.01f, signal_quality, + dist_mavlink->quaternion); + return PX4_OK; } diff --git a/src/modules/simulation/simulator_mavlink/SimulatorMavlink.hpp b/src/modules/simulation/simulator_mavlink/SimulatorMavlink.hpp index 9716ca320f8..93c90d32421 100644 --- a/src/modules/simulation/simulator_mavlink/SimulatorMavlink.hpp +++ b/src/modules/simulation/simulator_mavlink/SimulatorMavlink.hpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -156,10 +157,6 @@ public: perf_free(_perf_sim_delay); perf_free(_perf_sim_interval); - for (size_t i = 0; i < sizeof(_dist_pubs) / sizeof(_dist_pubs[0]); i++) { - delete _dist_pubs[i]; - } - px4_lockstep_unregister_component(_lockstep_component); for (size_t i = 0; i < sizeof(_sensor_gps_pubs) / sizeof(_sensor_gps_pubs[0]); i++) { @@ -205,6 +202,12 @@ private: {6620428}, // 6620428: DRV_BARO_DEVTYPE_BAROSIM, BUS: 2, ADDR: 4, TYPE: SIMULATION }; + static constexpr uint8_t DIST_SENSOR_COUNT_MAX = 10; + PX4Rangefinder _px4_rangefinder[DIST_SENSOR_COUNT_MAX] { + {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0} + }; + uint32_t _dist_sensor_ids[DIST_SENSOR_COUNT_MAX] {}; + float _sensors_temperature{0}; perf_counter_t _perf_sim_delay{perf_alloc(PC_ELAPSED, MODULE_NAME": network delay")}; @@ -218,9 +221,6 @@ private: uORB::Publication _visual_odometry_pub{ORB_ID(vehicle_visual_odometry)}; uORB::Publication _mocap_odometry_pub{ORB_ID(vehicle_mocap_odometry)}; - uORB::PublicationMulti *_dist_pubs[ORB_MULTI_MAX_INSTANCES] {}; - uint32_t _dist_sensor_ids[ORB_MULTI_MAX_INSTANCES] {}; - uORB::SubscriptionInterval _parameter_update_sub{ORB_ID(parameter_update), 1_s}; unsigned int _port{14560}; diff --git a/src/systemcmds/failure/failure.cpp b/src/systemcmds/failure/failure.cpp index 90ff9b73147..08afa59a5b8 100644 --- a/src/systemcmds/failure/failure.cpp +++ b/src/systemcmds/failure/failure.cpp @@ -69,6 +69,7 @@ static constexpr FailureUnit failure_units[] = { { "avoidance", vehicle_command_s::FAILURE_UNIT_SYSTEM_AVOIDANCE}, { "rc_signal", vehicle_command_s::FAILURE_UNIT_SYSTEM_RC_SIGNAL}, { "mavlink_signal", vehicle_command_s::FAILURE_UNIT_SYSTEM_MAVLINK_SIGNAL}, + { "traffic", vehicle_command_s::FAILURE_UNIT_SYSTEM_TRAFFIC_AVOIDANCE}, }; struct FailureType {