feat(SIH): Added optical flow sensor continues on #28270 (#29676)

* feat(sih): model the distance sensor range limits, quality and noise

The simulated distance sensor reported a noise free reading with no signal
quality, and saturated only against the upper range limit. Readings below the
minimum range were passed through unchanged, which is not what a range finder
does.

Report the raw saturated value with a zero quality outside of the measurement
range, derate the quality over the last 20% of the range, and add configurable
Gaussian noise (SIH_DISTSNSR_NOI). The quality is decided on the true distance
so that a measurement sitting at a range limit does not flicker in and out of
validity.

The sensor is now enabled with SIH_DISTSNSR_EN instead of by an out of band
value of the override parameter, and the ground distance computation moves into
a helper.

* feat(sih): add optical flow simulation

Simulate a downward facing optical flow sensor in SIH so that flow aided
navigation can be exercised without a rendered camera image. The flow rate is
the sum of the body rates and of the ground relative velocity scaled by the
distance to the ground, integrated over one publication interval and published
on sensor_optical_flow with configurable rate (SIH_OF_RATE) and noise
(SIH_OF_NOISE).

The sensor reports the integrated flow only: the flow module completes the
sample with the vehicle gyro and the downward facing distance sensor, which
therefore has to be enabled as well. Quality drops to zero above
SIH_OF_H_MAX or when the flow rate exceeds what the sensor can correlate.

The topic is advertised before the simulated clock starts, because the sensors
module brings up its flow pipeline on the first appearance of the topic, and
publishing during startup deadlocks the lockstep clock this thread advances.

Add the quadx_flow and standard_vtol_flow models with matching airframes:
SYS_AUTOSTART 10046 flies the multicopter on flow only with no GNSS, 10047
fuses the flow next to GNSS on a VTOL.

* prune configs

Signed-off-by: RomanBapst <bapstroman@gmail.com>

* more config cleanup

Signed-off-by: RomanBapst <bapstroman@gmail.com>

* added EKF2_HGT_REF to vtol flow config

Signed-off-by: RomanBapst <bapstroman@gmail.com>

* feat(simulation): added tests for optical flow for both quadx and stanard vtol
modes and enable them in CI

- for the test we monitor error on ground truth position and velocity

Signed-off-by: RomanBapst <bapstroman@gmail.com>

* feat(docs): document addition of optical flow in SIH

Signed-off-by: RomanBapst <bapstroman@gmail.com>

* fix(mavsdk_tests): unsubscribe flow ground truth comparison on destruction

The ground truth comparison callbacks capture `this` and touch members of
AutopilotTesterFlow. If a REQUIRE fails between start and stop, the tester
is destroyed during unwinding while the subscriptions are still active,
so a callback could run on the destroyed mutex and sample buffers.

Make stop idempotent and call it from the destructor, and stop any running
comparison before starting a new one.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: RomanBapst <bapstroman@gmail.com>

* tests for python

* fix(mavsdk_tests): start the VTOL flow loiter already on its radius

The loiter was centered on the vehicle's position right after the
transition, so it started at the center and had to fly straight out to the commanded
radius before the lateral guidance curved onto the track.

Assisted-by: Claude:claude-sonnet-5

* fix(mavsdk_tests): resend the flow test EKF origin until it is taken

The SITL startup script starts ekf2 after MAVLink. When MAVSDK connected
first, the single SET_GPS_GLOBAL_ORIGIN was published before ekf2 existed
and MAVSDK's RUN_PREARM_CHECKS followed it. Ekf2 then subscribed, saw
only the newest vehicle command and never got an origin. The Coverage
build starts slowly enough to hit this every time.

Assisted-by: Claude:claude-opus-5-5

* ci(sitl_tests): run the VTOL flow test without coverage

As a Coverage job it built with coverage on every PR and uploaded the
sitl-vtol flag from PRs, which replaced main's carried-forward VTOL
coverage with the flow-only flight. The quadx_flow entry also sat
between the Coverage comment and the standard_vtol entry it describes.

Assisted-by: Claude:claude-opus-5-5

* fix(mavsdk_tests): sum the flow test heading sweep with its sign

Adding up the absolute heading changes counted yaw oscillation toward the
360 degrees, so the wait could end before a full orbit was flown.

Assisted-by: Claude:claude-opus-5-5

* refactor(airframes): keep only the non-default params in the SIH flow airframes

SIH_OF_H_MAX, SIH_DISTSNSR_EN and EKF2_OF_CTRL were set to their defaults
and SENS_EN_GPSSIM is already set by the quadx base airframe. The quadx
forced EKF2_RNG_CTRL to 2 while the VTOL used the conditional default for
no stated reason, so both now use the default.

Assisted-by: Claude:claude-opus-5-5

* docs(sim_sih): mark the SIH flow airframes as new in PX4 v2.0

release/1.18 has branched, so these airframes first ship in v2.0, not
v1.17.

Assisted-by: Claude:claude-opus-5-5

---------

Signed-off-by: RomanBapst <bapstroman@gmail.com>
Co-authored-by: RomanBapst <bapstroman@gmail.com>
Co-authored-by: Jacob Dahl <dahl.jakejacob@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-11-09 11:13:16 -07:00
1 parent 7e34e87d3a
commit 440179383a
16 files changed
+833 -15

No files matched your search

@@ -54,8 +54,10 @@ if(PX4_PLATFORM MATCHES "posix")
set(models
airplane
quadx
quadx_flow
xvert
standard_vtol
standard_vtol_flow
hex
rover_ackermann
)
+170 -8
View File
@@ -47,6 +47,7 @@
#include <px4_platform_common/log.h>
#include <drivers/drv_pwm_output.h> // to get PWM flags
#include <drivers/drv_sensor.h> // to get the simulated sensor device types
#include <lib/drivers/device/Device.hpp>
using namespace math;
@@ -58,7 +59,14 @@ ModuleBase::Descriptor Sih::desc{task_spawn, custom_command, print_usage};
Sih::Sih() :
ModuleParams(nullptr)
{
srand(1234); // initialize the random seed once before calling math::generate_wgn()
srand(1234); // initialize the random seed once before calling generate_wgn()
device::Device::DeviceId device_id{};
device_id.devid_s.bus_type = device::Device::DeviceBusType::DeviceBusType_SIMULATION;
device_id.devid_s.bus = 0;
device_id.devid_s.address = 0;
device_id.devid_s.devtype = DRV_FLOW_DEVTYPE_SIM;
_optical_flow_device_id = device_id.devid;
}
Sih::~Sih()
@@ -74,10 +82,19 @@ void Sih::run()
parameters_updated();
if (_sih_optical_flow_en.get()) {
// Advertise before the simulated clock starts running: the sensors module brings up its
// optical flow pipeline when the topic first appears, and it only looks for it while
// updating its parameters. Advertising here makes it visible for the startup scan even
// though the first sample is only published once the control pipeline is alive.
_optical_flow_pub.advertise();
}
const hrt_abstime task_start = hrt_absolute_time();
_last_run = task_start;
_airspeed_time = task_start;
_dist_snsr_time = task_start;
_optical_flow_time = task_start;
_ranging_beacon_time = task_start;
_vehicle = static_cast<VehicleType>(constrain(_sih_vtype.get(),
static_cast<int32_t>(VehicleType::First),
@@ -224,6 +241,8 @@ void Sih::updateFailureConfig()
== failure_injection::Mode::Off);
_distance_sensor_blocked = (_failure_config.mode(failure_injection_s::FAILURE_UNIT_SENSOR_DISTANCE_SENSOR, 1)
== failure_injection::Mode::Off);
_optical_flow_blocked = (_failure_config.mode(failure_injection_s::FAILURE_UNIT_SENSOR_OPTICAL_FLOW, 1)
== failure_injection::Mode::Off);
_accel_blocked = (_failure_config.mode(failure_injection_s::FAILURE_UNIT_SENSOR_ACCEL, 1)
== failure_injection::Mode::Off);
_gyro_blocked = (_failure_config.mode(failure_injection_s::FAILURE_UNIT_SENSOR_GYRO, 1)
@@ -276,12 +295,30 @@ void Sih::sensor_step()
}
// distance sensor published at 50 Hz
if (now - _dist_snsr_time >= 20_ms
&& fabs(_distance_snsr_override) < 10000) {
if (_sih_distance_snsr_en.get() && now - _dist_snsr_time >= 20_ms) {
_dist_snsr_time = now;
send_dist_snsr(now);
}
// The optical flow is integrated every iteration and published at SIH_OF_RATE, but only
// once the control pipeline is alive. Publishing while the system is still starting up
// races with the sensors module bringing up its optical flow pipeline and deadlocks the
// simulation, as this thread is the one advancing the lockstep clock.
if (_sih_optical_flow_en.get()) {
if (_last_actuator_output_time > 0) {
accumulate_optical_flow(dt);
if (now - _optical_flow_time >= _optical_flow_interval_us) {
_optical_flow_time = now;
send_optical_flow(now);
}
} else {
// keep the integration interval aligned with the first publication
_optical_flow_time = now;
}
}
// ranging beacon published at 2 Hz (each beacon at 0.5 Hz)
if (now - _ranging_beacon_time >= 500_ms) {
_ranging_beacon_time = now;
@@ -367,9 +404,12 @@ void Sih::parameters_updated()
_distance_snsr_min = _sih_distance_snsr_min.get();
_distance_snsr_max = _sih_distance_snsr_max.get();
_distance_snsr_override = _sih_distance_snsr_override.get();
_distance_snsr_noise = _sih_distance_snsr_noise.get();
_px4_rangefinder.set_min_distance(_distance_snsr_min);
_px4_rangefinder.set_max_distance(_distance_snsr_max);
_optical_flow_interval_us = static_cast<hrt_abstime>(roundf(1e6f / math::max(_sih_optical_flow_rate.get(), 1.f)));
_T_TAU = _sih_thrust_tau.get();
_v_wind_N = Vector3f(_sih_wind_n.get(), _sih_wind_e.get(), 0.f);
@@ -820,6 +860,21 @@ void Sih::send_airspeed(const hrt_abstime &time_now_us)
_airspeed_pub.publish(airspeed);
}
float Sih::ground_distance() const
{
// the ground is assumed flat at the altitude of the simulation reference (SIH_LOC_H0)
const float cos_tilt = _q.dcm_z()(2);
if (cos_tilt < FLT_EPSILON) {
// the body down axis points away from the ground
return NAN;
}
// the fake ground lets the vehicle settle marginally below the reference altitude, clamp it
// so that a landed vehicle reads zero instead of dropping out of range
return math::max(-_lpos(2), 0.f) / cos_tilt;
}
void Sih::send_dist_snsr(const hrt_abstime &time_now_us)
{
if (_distance_sensor_blocked) {
@@ -827,20 +882,127 @@ void Sih::send_dist_snsr(const hrt_abstime &time_now_us)
}
float current_distance;
int8_t signal_quality;
if (_distance_snsr_override >= 0.f) {
// forced reading, let the driver flag it if it falls outside of the configured range
current_distance = _distance_snsr_override;
signal_quality = -1;
} else {
current_distance = -_lpos(2) / _q.dcm_z()(2);
// the quality is decided on the true distance rather than on the noisy reading, so
// that a measurement sitting at a range limit does not flicker in and out of validity
const float true_distance = ground_distance();
if (current_distance > _distance_snsr_max) {
// this is based on lightware lw20 behaviour
current_distance = UINT16_MAX / 100.f;
if (!PX4_ISFINITE(true_distance) || true_distance > _distance_snsr_max) {
// nothing within reach, the sensor reports its saturated raw reading
current_distance = DISTSNSR_OUT_OF_RANGE;
signal_quality = 0;
} else if (true_distance < _distance_snsr_min) {
// closer than the minimum range: the reading saturates and cannot be trusted
current_distance = _distance_snsr_min;
signal_quality = 0;
} else {
current_distance = math::max(true_distance + generate_wgn() * _distance_snsr_noise, 0.f);
// the returned signal gets weaker as the target moves away
const float derate_start = DISTSNSR_QUALITY_DERATE * _distance_snsr_max;
const float derate_span = _distance_snsr_max - derate_start;
if (true_distance > derate_start && derate_span > FLT_EPSILON) {
const float derated = (true_distance - derate_start) / derate_span;
signal_quality = static_cast<int8_t>(constrain(roundf(100.f - 99.f * derated), 1.f, 100.f));
} else {
signal_quality = 100;
}
}
}
_px4_rangefinder.update(hrt_absolute_time(), current_distance);
_px4_rangefinder.update(time_now_us, current_distance, signal_quality);
}
void Sih::accumulate_optical_flow(const float dt)
{
// An optical flow sensor integrates the angular displacement of the ground image over its
// integration interval. The sign convention of sensor_optical_flow is such that a positive
// value is produced by a right handed rotation of the sensor about the body axis, which
// gives the translation over the ground the opposite sign (see the flow observation model
// in the EKF).
const float distance = ground_distance();
if (!PX4_ISFINITE(distance) || distance > _sih_optical_flow_h_max.get()) {
// too high above the ground, or not looking at it: no image to track
_optical_flow_tracking = false;
_optical_flow_dt += dt;
return;
}
const Vector3f v_B = _q.rotateVectorInverse(_v_N); // ground relative velocity in body frame
// the flow produced by the translation over the ground scales with the inverse of the
// distance, which is kept bounded to stay well behaved when landed
const Vector2f translation_flow = Vector2f(-v_B(1), v_B(0)) / math::max(distance, FLOW_MIN_DISTANCE);
const Vector2f flow_rate = Vector2f(_w_B(0), _w_B(1)) + translation_flow;
if (flow_rate.norm() > FLOW_MAX_RATE) {
// the image moves too fast for the sensor to correlate two consecutive frames
_optical_flow_tracking = false;
}
_optical_flow_integral += flow_rate * dt;
_optical_flow_dt += dt;
}
void Sih::send_optical_flow(const hrt_abstime &time_now_us)
{
Vector2f pixel_flow = _optical_flow_integral;
const float integration_time = _optical_flow_dt;
const bool tracking = _optical_flow_tracking;
// start a new integration interval
_optical_flow_integral.setZero();
_optical_flow_dt = 0.f;
_optical_flow_tracking = true;
if (_optical_flow_blocked || integration_time < FLT_EPSILON) {
return;
}
sensor_optical_flow_s flow{};
flow.timestamp_sample = time_now_us;
flow.device_id = _optical_flow_device_id;
if (tracking) {
// white noise on the flow rate estimate, integrated over the interval
pixel_flow += Vector2f(generate_wgn(), generate_wgn()) * (_sih_optical_flow_noise.get() * integration_time);
flow.quality = UINT8_MAX;
} else {
pixel_flow.setZero();
flow.quality = 0;
}
pixel_flow.copyTo(flow.pixel_flow);
flow.integration_timespan_us = static_cast<uint32_t>(roundf(integration_time * 1e6f));
// the sensor has neither a gyro nor a rangefinder: the flow module completes the sample
// with the vehicle gyro and the downward facing distance sensor
flow.delta_angle[0] = flow.delta_angle[1] = flow.delta_angle[2] = NAN;
flow.delta_angle_available = false;
flow.distance_m = NAN;
flow.distance_available = false;
flow.max_flow_rate = FLOW_MAX_RATE;
flow.min_ground_distance = 0.f;
flow.max_ground_distance = _sih_optical_flow_h_max.get();
flow.mode = sensor_optical_flow_s::MODE_LOWLIGHT;
flow.error_count = 0;
flow.timestamp = hrt_absolute_time();
_optical_flow_pub.publish(flow);
}
void Sih::send_ranging_beacon(const hrt_abstime &time_now_us)
+38 -4
View File
@@ -80,6 +80,7 @@
#include <uORB/topics/failure_injection.h>
#include <uORB/topics/esc_status.h>
#include <uORB/topics/parameter_update.h>
#include <uORB/topics/sensor_optical_flow.h>
#include <uORB/topics/vehicle_angular_velocity.h>
#include <uORB/topics/vehicle_attitude.h>
#include <uORB/topics/vehicle_global_position.h>
@@ -129,9 +130,10 @@ private:
PX4Accelerometer _px4_accel{1310988}; // 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
PX4Gyroscope _px4_gyro{1310988}; // 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
PX4Rangefinder _px4_rangefinder{10092548}; // 10092548: DRV_DIST_DEVTYPE_SIM, BUS: 0, ADDR: 0, TYPE: SIMULATION
uORB::Publication<airspeed_s> _airspeed_pub{ORB_ID(airspeed)};
uORB::Publication<ranging_beacon_s> _ranging_beacon_pub{ORB_ID(ranging_beacon)};
uORB::Publication<esc_status_s> _esc_status_pub{ORB_ID(esc_status)};
uORB::Publication<airspeed_s> _airspeed_pub{ORB_ID(airspeed)};
uORB::Publication<ranging_beacon_s> _ranging_beacon_pub{ORB_ID(ranging_beacon)};
uORB::Publication<esc_status_s> _esc_status_pub{ORB_ID(esc_status)};
uORB::Publication<sensor_optical_flow_s> _optical_flow_pub{ORB_ID(sensor_optical_flow)};
// groundtruth
uORB::Publication<vehicle_angular_velocity_s> _angular_velocity_ground_truth_pub{ORB_ID(vehicle_angular_velocity_groundtruth)};
@@ -145,6 +147,7 @@ private:
bool _airspeed_blocked{false};
bool _distance_sensor_blocked{false};
bool _optical_flow_blocked{false};
bool _accel_blocked{false};
bool _gyro_blocked{false};
uint16_t _stuck_motor_mask{0};
@@ -175,6 +178,16 @@ private:
};
RangingBeaconConfig _ranging_beacons[NUM_RANGING_BEACONS] {};
// Distance sensor simulation constants
// fraction of the measurement range above which the returned signal starts to get weaker
static constexpr float DISTSNSR_QUALITY_DERATE = 0.8f;
// out of range reading, this is based on lightware lw20 behaviour
static constexpr float DISTSNSR_OUT_OF_RANGE = UINT16_MAX / 100.f;
// Optical flow simulation constants, the values are taken from the PAW3902
static constexpr float FLOW_MAX_RATE = 7.4f; // maximum measurable angular flow rate [rad/s]
static constexpr float FLOW_MIN_DISTANCE = 0.1f; // lower bound on the range scaling the flow [m]
static constexpr float T1_C = 15.0f; // ground temperature in Celsius
static constexpr float T1_K = T1_C - atmosphere::kAbsoluteNullCelsius; // ground temperature in Kelvin
static constexpr float TEMP_GRADIENT = -6.5f / 1000.0f; // temperature gradient in degrees per metre
@@ -202,7 +215,14 @@ private:
void reconstruct_sensors_signals(const hrt_abstime &time_now_us);
void send_airspeed(const hrt_abstime &time_now_us);
void send_dist_snsr(const hrt_abstime &time_now_us);
void accumulate_optical_flow(const float dt);
void send_optical_flow(const hrt_abstime &time_now_us);
void send_ranging_beacon(const hrt_abstime &time_now_us);
// distance from the vehicle to the ground measured along the body down axis, NAN if the
// body down axis does not point at the ground anymore
float ground_distance() const;
void publish_ground_truth(const hrt_abstime &time_now_us);
void generate_fw_aerodynamics(const float roll_cmd, const float pitch_cmd, const float yaw_cmd, const float thrust_for_prowash);
void generate_ts_aerodynamics();
@@ -233,6 +253,13 @@ private:
hrt_abstime _ranging_beacon_time{0};
uint8_t _ranging_beacon_idx{0};
// optical flow accumulation over one integration interval
hrt_abstime _optical_flow_time{0};
matrix::Vector2f _optical_flow_integral{};
float _optical_flow_dt{0.f};
bool _optical_flow_tracking{true};
uint32_t _optical_flow_device_id{0};
bool _grounded{true}; // whether the vehicle is on the ground
// Quantities in body frame (FRD)
@@ -310,7 +337,8 @@ private:
matrix::Matrix3f _I; // vehicle inertia matrix
matrix::Matrix3f _Im1; // inverse of the inertia matrix
float _distance_snsr_min, _distance_snsr_max, _distance_snsr_override;
float _distance_snsr_min, _distance_snsr_max, _distance_snsr_override, _distance_snsr_noise;
hrt_abstime _optical_flow_interval_us{20_ms};
esc_status_s _esc_status{};
@@ -335,9 +363,15 @@ private:
(ParamFloat<px4::params::SIH_LOC_LON0>) _sih_lon0,
(ParamFloat<px4::params::SIH_LOC_H0>) _sih_h0,
(ParamFloat<px4::params::SIH_LOC_YAW0>) _sih_yaw0,
(ParamInt<px4::params::SIH_DISTSNSR_EN>) _sih_distance_snsr_en,
(ParamFloat<px4::params::SIH_DISTSNSR_MIN>) _sih_distance_snsr_min,
(ParamFloat<px4::params::SIH_DISTSNSR_MAX>) _sih_distance_snsr_max,
(ParamFloat<px4::params::SIH_DISTSNSR_OVR>) _sih_distance_snsr_override,
(ParamFloat<px4::params::SIH_DISTSNSR_NOI>) _sih_distance_snsr_noise,
(ParamInt<px4::params::SIH_OF_EN>) _sih_optical_flow_en,
(ParamFloat<px4::params::SIH_OF_RATE>) _sih_optical_flow_rate,
(ParamFloat<px4::params::SIH_OF_NOISE>) _sih_optical_flow_noise,
(ParamFloat<px4::params::SIH_OF_H_MAX>) _sih_optical_flow_h_max,
(ParamFloat<px4::params::SIH_T_TAU>) _sih_thrust_tau,
// forward propeller
(ParamFloat<px4::params::SIH_F_T_MAX>) _sih_f_thrust_max,
@@ -227,9 +227,20 @@ parameters:
max: 3.14159
decimal: 3
increment: 0.01
SIH_DISTSNSR_EN:
description:
short: Enable the simulated downward facing distance sensor
type: enum
values:
0: Disabled
1: Enabled
default: 1
SIH_DISTSNSR_MIN:
description:
short: distance sensor minimum range
long: |-
Readings closer than this saturate at the minimum range
and are reported with a zero signal quality.
type: float
default: 0.0
unit: m
@@ -240,6 +251,9 @@ parameters:
SIH_DISTSNSR_MAX:
description:
short: distance sensor maximum range
long: |-
The signal quality degrades over the last 20% of the range. Beyond the maximum range
the sensor reports a saturated reading with a zero signal quality.
type: float
default: 100.0
unit: m
@@ -250,10 +264,67 @@ parameters:
SIH_DISTSNSR_OVR:
description:
short: if >= 0 the distance sensor measures will be overridden by this value
long: Absolute value superior to 10000 will disable distance sensor
long: Set SIH_DISTSNSR_EN to 0 to disable the distance sensor.
type: float
default: -1.0
unit: m
SIH_DISTSNSR_NOI:
description:
short: Distance sensor measurement noise standard deviation
long: |-
Gaussian noise added to the simulated distance sensor measurements.
Set to 0 to disable noise.
type: float
default: 0.01
unit: m
min: 0.0
max: 10.0
decimal: 3
SIH_OF_EN:
description:
short: Enable the simulated optical flow sensor
long: |-
The simulated sensor reports the integrated flow only. The flow module completes the
sample with the vehicle gyro and the downward facing distance sensor, which therefore
has to be enabled as well (SIH_DISTSNSR_EN) for the flow to be usable by the estimator.
type: enum
values:
0: Disabled
1: Enabled
default: 0
SIH_OF_RATE:
description:
short: Optical flow publication rate
long: The simulated sensor integrates the flow over one publication interval.
type: float
default: 12.0
unit: Hz
min: 1.0
max: 100.0
decimal: 1
SIH_OF_NOISE:
description:
short: Optical flow measurement noise standard deviation
long: |-
Gaussian noise added to the simulated flow rate.
Set to 0 to disable noise.
type: float
default: 0.05
unit: rad/s
min: 0.0
max: 5.0
decimal: 3
SIH_OF_H_MAX:
description:
short: Optical flow maximum ground distance
long: |-
Above this distance to the ground the simulated sensor cannot track the ground image
anymore and reports a zero quality.
type: float
default: 30.0
unit: m
min: 1.0
decimal: 1
SIH_T_TAU:
description:
short: thruster time constant tau