diff --git a/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision b/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision index b25f897686e..20a9278463b 100644 --- a/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision +++ b/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision @@ -28,7 +28,6 @@ param set-default EKF2_OF_POS_X 0.055 param set-default EKF2_OF_POS_Y 0.02 param set-default EKF2_OF_POS_Z 0.065 param set-default GNSS_REQ_HDRIFT 0.3 -param set-default EKF2_REQ_SACC 1 param set-default GNSS_REQ_SACC 1 param set-default GNSS_REQ_VDRIFT 0.3 param set-default EKF2_RNG_A_HMAX 8 diff --git a/ROMFS/px4fmu_common/init.d-posix/rcS b/ROMFS/px4fmu_common/init.d-posix/rcS index 9f0671a9f1c..540a28a6186 100644 --- a/ROMFS/px4fmu_common/init.d-posix/rcS +++ b/ROMFS/px4fmu_common/init.d-posix/rcS @@ -167,7 +167,7 @@ param set-default COM_RAM_MAX -1 param set-default COM_RC_IN_MODE 1 # Speedup SITL startup -param set-default EKF2_REQ_GPS_H 0.5 +param set-default EKF2_GPS_YAW_RST 0.5 param set-default GNSS_REQ_TIME 0.5 param set-default IMU_GYRO_FFT_EN 1 diff --git a/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision b/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision index 54820f897ea..bc1bb03b8d2 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision +++ b/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision @@ -27,7 +27,6 @@ param set-default EKF2_OF_POS_X 0.055 param set-default EKF2_OF_POS_Y 0.02 param set-default EKF2_OF_POS_Z 0.065 param set-default GNSS_REQ_HDRIFT 0.3 -param set-default EKF2_REQ_SACC 1 param set-default GNSS_REQ_SACC 1 param set-default GNSS_REQ_VDRIFT 0.3 param set-default EKF2_RNG_A_HMAX 8 diff --git a/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 b/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 index e80f9f6cd2c..58440271e7b 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 +++ b/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 @@ -27,7 +27,6 @@ param set-default EKF2_OF_POS_X 0.055 param set-default EKF2_OF_POS_Y 0.02 param set-default EKF2_OF_POS_Z 0.065 param set-default GNSS_REQ_HDRIFT 0.3 -param set-default EKF2_REQ_SACC 1 param set-default GNSS_REQ_SACC 1 param set-default GNSS_REQ_VDRIFT 0.3 param set-default EKF2_RNG_A_HMAX 8 diff --git a/ROMFS/px4fmu_common/init.d/rc.fw_defaults b/ROMFS/px4fmu_common/init.d/rc.fw_defaults index 77eb8a5a325..e6d55c8ec7f 100644 --- a/ROMFS/px4fmu_common/init.d/rc.fw_defaults +++ b/ROMFS/px4fmu_common/init.d/rc.fw_defaults @@ -29,7 +29,6 @@ param set-default GNSS_REQ_EPH 10 param set-default GNSS_REQ_EPV 10 param set-default GNSS_REQ_HDRIFT 0.5 param set-default GNSS_REQ_PDOP 4 -param set-default EKF2_REQ_SACC 1 param set-default GNSS_REQ_SACC 1 param set-default GNSS_REQ_VDRIFT 1 param set-default EKF2_RNG_QLTY_T 3 diff --git a/docs/en/releases/main.md b/docs/en/releases/main.md index 0209441f756..52e0868aaef 100644 --- a/docs/en/releases/main.md +++ b/docs/en/releases/main.md @@ -43,13 +43,20 @@ Please continue reading for [upgrade instructions](#upgrade-guide). ROS 2 applications must subscribe to `/fmu/out/vehicle_gnss` (`px4_msgs/msg/VehicleGnss`) instead of `/fmu/out/vehicle_gps_position` (`px4_msgs/msg/SensorGps`). Read the timestamps from the top level of `VehicleGnss`: only `timestamp` and `timestamp_sample` are converted to ROS time, while `receiver.timestamp` and `receiver.timestamp_sample` stay on the PX4 boot clock. `timestamp` is now when the sensors module published the sample; use `timestamp_sample` for the measurement time. - `SENS_GPS_MASK`, `SENS_GPS_TAU`, `SENS_GPS_PRIME` and `SENS_GPSn_ID/OFFX/OFFY/OFFZ/DELAY` are now `SENS_GNSS_*` and `SENS_GNSSn_*` (the driver `GPS_*` and `EKF2_*` parameters are unchanged). + `SENS_GPS_MASK`, `SENS_GPS_TAU`, `SENS_GPS_PRIME` and `SENS_GPSn_ID/OFFX/OFFY/OFFZ/DELAY` are now `SENS_GNSS_*` and `SENS_GNSSn_*` (the driver `GPS_*` parameters are unchanged). Saved parameters are migrated automatically, but loading a QGC parameter file with the old names does not restore them. The log analysis scripts in the tree read both the old and the new names. The uORB-over-Cyphal registers are renamed from `uorb.sensor_gps` to `uorb.sensor_gnss` (`uavcan.sub.uorb.sensor_gnss.0.id`, `uavcan.pub.uorb.sensor_gnss.0.id`); `UCAN1_UORB_GPS` and `UCAN1_UORB_GPS_P` are unchanged. ([PX4-Autopilot#24399](https://github.com/PX4/PX4-Autopilot/pull/24399)) +- **The GNSS check parameters moved from EKF2 to the sensors module.** + `EKF2_GPS_CHECK` is now [GNSS_CHECK](../advanced_config/parameter_reference.md#GNSS_CHECK), `EKF2_REQ_EPH`, `EKF2_REQ_EPV`, `EKF2_REQ_NSATS`, `EKF2_REQ_PDOP`, `EKF2_REQ_HDRIFT`, `EKF2_REQ_VDRIFT`, `EKF2_REQ_FIX` and `EKF2_REQ_SACC` are now `GNSS_REQ_*`, and `EKF2_REQ_GPS_H` is now [GNSS_REQ_TIME](../advanced_config/parameter_reference.md#GNSS_REQ_TIME). + Saved parameters are migrated automatically, but loading a QGC parameter file with the old names does not restore them. ([PX4-Autopilot#28520](https://github.com/PX4/PX4-Autopilot/pull/28520), [PX4-Autopilot#28798](https://github.com/PX4/PX4-Autopilot/pull/28798)) - **`DO_JUMP` can only loop back and its repeat count must fit.** A mission is now rejected if a `DO_JUMP` targets itself or a later mission item, even if its repeat count is 0, and if its repeat count is negative, above 65535 or not a number (it is no longer narrowed to a different count). Missions stored on the vehicle with such jumps must be edited and uploaded again. +- **The primary GNSS receiver defaults to Auto.** + [SENS_GNSS_PRIME](../advanced_config/parameter_reference.md#SENS_GNSS_PRIME) now defaults to `-1` (Auto) instead of `0`, and saved values are not changed: with Auto the moving base of a moving base pair is the primary receiver, and without one, a receiver that passes the strict checks ([GNSS_REQ_EPH](../advanced_config/parameter_reference.md#GNSS_REQ_EPH) and the other `GNSS_REQ_*` parameters) is used, then one with an RTK fixed solution. + To keep preferring the receiver on the main serial port, set `SENS_GNSS_PRIME` to `0`. + In flight the primary receiver is now also left when it has failed the strict checks for 10 s while the other receiver passed them. ([PX4-Autopilot#28798](https://github.com/PX4/PX4-Autopilot/pull/28798)) ## Other changes diff --git a/msg/SensorsStatusGnss.msg b/msg/SensorsStatusGnss.msg index 040b82d5273..08cd5277e1c 100644 --- a/msg/SensorsStatusGnss.msg +++ b/msg/SensorsStatusGnss.msg @@ -10,9 +10,11 @@ uint8 MAX_RECEIVERS = 4 # Length of the per-receiver arrays uint32[4] device_ids # [-] One entry per receiver, 0 where unused int8[4] order # [-] Fixed position of the receiver: 0 for the preferred one, otherwise for the first to publish, then in order of first publication. Changes only with the preference, -1 until the receiver publishes -bool[4] healthy # Publishing, and has passed its checks for long enough -uint16[4] failed_checks # [-] Bitmask of the enabled checks that failed, VehicleGnss CHECK_* bits -bool[4] strict # The pre-flight thresholds apply rather than the relaxed in-flight ones +bool[4] healthy # Usable within the last 2 s: passed its checks for long enough and published without gaps. The selection fails over from a receiver that isn't +float32[4] availability # [-] Fraction of recent time the receiver passed its checks and published without gaps, 0 to 1 +uint16[4] failed_strict_checks # [-] Enabled checks the latest sample fails at the strict thresholds, VehicleGnss CHECK_* bits +uint16[4] failed_relaxed_checks # [-] Enabled checks the latest sample fails at the relaxed thresholds, VehicleGnss CHECK_* bits +bool[4] strict # The strict checks decide whether its samples are usable, as VehicleGnss strict float32[4] drift_rate_horizontal # [m/s] Horizontal position drift rate at rest float32[4] drift_rate_vertical # [m/s] Vertical position drift rate at rest float32[4] speed_horizontal_filtered # [m/s] Filtered horizontal speed at rest diff --git a/msg/VehicleGnss.msg b/msg/VehicleGnss.msg index 977517723a3..5a0caeaef2c 100644 --- a/msg/VehicleGnss.msg +++ b/msg/VehicleGnss.msg @@ -11,12 +11,22 @@ SensorGnss receiver # The selected receiver's sensor_gnss sample with the correc float32[3] antenna_offset # [m] [@frame FRD] Antenna position of the selected receiver # Selection state -uint8 selected_instance # [-] sensor_gnss instance of the selected receiver -uint8 selection_count # [-] Increments when the selected receiver changes +uint8 selected_instance # [-] sensor_gnss instance of the selected receiver +uint8 selection_count # [-] Increments when the selected receiver changes +uint8 selection_reason # [@enum SELECTION] Why this receiver is selected +uint8 SELECTION_PREFERRED = 0 # The preferred receiver +uint8 SELECTION_ONLY = 1 # No other receiver has published +uint8 SELECTION_RANKED = 2 # No receiver is preferred, and no other one ranks higher +uint8 SELECTION_TIMEOUT = 3 # The previously selected or the preferred receiver stopped publishing +uint8 SELECTION_UNHEALTHY = 4 # The previously selected or the preferred receiver failed its checks or delivered samples late, continuously or often +uint8 SELECTION_STRICT = 5 # Passes the strict checks, which the previously selected receiver didn't +uint8 SELECTION_RTK_FIXED = 6 # Passes the strict checks with an RTK fixed solution, and the previously selected receiver ranked lower -# Check result for this sample -bool usable # Sample may be used: the receiver has passed its checks for long enough -uint16 failed_checks # [@enum CHECK] Bitmask of the enabled checks that failed +# Check result for this sample. The strict checks are the GNSS_REQ_* thresholds, satellite count, PDOP and drift at rest on the ground; the relaxed checks are fixed, looser limits on fix type, accuracy, spoofing and jamming. +bool usable # Sample may be used: the checks that decide it have passed without a failure for long enough +bool strict # The strict checks decide usable: they haven't passed since the vehicle was disarmed on the ground, or they pass. Otherwise the relaxed checks decide +uint16 failed_strict_checks # [@enum CHECK] Enabled checks this sample fails at the strict thresholds, evaluated on every sample +uint16 failed_relaxed_checks # [@enum CHECK] Enabled checks this sample fails at the relaxed thresholds, evaluated on every sample uint16 CHECK_NSATS = 1 # Too few satellites uint16 CHECK_PDOP = 2 # Position dilution of precision too high uint16 CHECK_EPH = 4 # Horizontal position accuracy too low diff --git a/src/lib/gnss/gnss_checks.cpp b/src/lib/gnss/gnss_checks.cpp index 1117516c958..def4bae773e 100644 --- a/src/lib/gnss/gnss_checks.cpp +++ b/src/lib/gnss/gnss_checks.cpp @@ -33,7 +33,7 @@ /** * @file gnss_checks.cpp - * Perform pre-flight and in-flight GNSS quality checks + * GNSS quality checks: strict ones to qualify a receiver, relaxed ones once armed */ #include "gnss_checks.hpp" @@ -43,9 +43,9 @@ namespace constexpr uint16_t kDriftChecks = vehicle_gnss_s::CHECK_HDRIFT | vehicle_gnss_s::CHECK_VDRIFT | vehicle_gnss_s::CHECK_HSPEED | vehicle_gnss_s::CHECK_VSPEED; -// nsats and PDOP keep their last pre-flight result, so a check enabled in flight must not fail on it. -constexpr uint16_t kSimplifiedChecks = vehicle_gnss_s::CHECK_FIX | vehicle_gnss_s::CHECK_EPH | vehicle_gnss_s::CHECK_EPV - | vehicle_gnss_s::CHECK_SACC | vehicle_gnss_s::CHECK_SPOOFED | vehicle_gnss_s::CHECK_JAMMED; +// The checks that decide while armed, once the strict ones passed since the vehicle was disarmed on the ground +constexpr uint16_t kRelaxedChecks = vehicle_gnss_s::CHECK_FIX | vehicle_gnss_s::CHECK_EPH | vehicle_gnss_s::CHECK_EPV + | vehicle_gnss_s::CHECK_SACC | vehicle_gnss_s::CHECK_SPOOFED | vehicle_gnss_s::CHECK_JAMMED; } bool GnssChecks::run(const gnssChecksSample &gnss, bool armed, bool in_air, bool vehicle_at_rest) @@ -59,34 +59,35 @@ bool GnssChecks::run(const gnssChecksSample &gnss, bool armed, bool in_air, bool _time_last_fail_us = gnss.time_us; } - // Run strict checks while disarmed on the ground if (!armed && !in_air) { - _initial_checks_passed = false; + _initial_strict_checks_passed = false; } + // Both sets run on every sample: both are reported, and the selection ranks receivers on the strict one in flight + const bool strict_checks_pass = runStrictChecks(gnss, in_air, vehicle_at_rest); + const bool relaxed_checks_pass = runRelaxedChecks(gnss); + + _passed_strict = strict_checks_pass + && isTimedOut(_time_last_fail_us, gnss.time_us, getRequiredPassDurationUs(false)); _passed = false; - _strict = !_initial_checks_passed; + _strict = true; - if (_initial_checks_passed) { - clearDriftChecks(); + if (_passed_strict) { + _initial_strict_checks_passed = true; + _passed = true; - if (runSimplifiedChecks(gnss)) { - _passed = isTimedOut(_time_last_fail_us, gnss.time_us, getRequiredPassDurationUs()); + } else if (_initial_strict_checks_passed) { + _strict = false; + + if (relaxed_checks_pass) { + _passed = isTimedOut(_time_last_fail_us, gnss.time_us, getRequiredPassDurationUs(true)); } else { _time_last_fail_us = gnss.time_us; } - } else { - if (runInitialFixChecks(gnss, in_air, vehicle_at_rest)) { - if (isTimedOut(_time_last_fail_us, gnss.time_us, getRequiredPassDurationUs())) { - _initial_checks_passed = true; - _passed = true; - } - - } else { - _time_last_fail_us = gnss.time_us; - } + } else if (!strict_checks_pass) { + _time_last_fail_us = gnss.time_us; } lat_lon_prev.initReference(gnss.lat, gnss.lon, gnss.time_us); @@ -99,57 +100,57 @@ bool GnssChecks::run(const gnssChecksSample &gnss, bool armed, bool in_air, bool return _passed; } -void GnssChecks::setFail(uint16_t check, bool failed) +void GnssChecks::setFail(uint16_t &fail_flags, uint16_t check, bool failed) { if (failed) { - _fail_flags |= check; + fail_flags |= check; } else { - _fail_flags &= ~check; + fail_flags &= ~check; } } -bool GnssChecks::runSimplifiedChecks(const gnssChecksSample &gnss) +bool GnssChecks::runRelaxedChecks(const gnssChecksSample &gnss) { - setFail(vehicle_gnss_s::CHECK_FIX, gnss.fix_type < 3); + setFail(_relaxed_fail_flags, vehicle_gnss_s::CHECK_FIX, gnss.fix_type < 3); // Check the reported horizontal and vertical position accuracy - setFail(vehicle_gnss_s::CHECK_EPH, gnss.hacc > 50.f); - setFail(vehicle_gnss_s::CHECK_EPV, gnss.vacc > 50.f); + setFail(_relaxed_fail_flags, vehicle_gnss_s::CHECK_EPH, gnss.hacc > 50.f); + setFail(_relaxed_fail_flags, vehicle_gnss_s::CHECK_EPV, gnss.vacc > 50.f); // Check the reported speed accuracy - setFail(vehicle_gnss_s::CHECK_SACC, gnss.sacc > 10.f); + setFail(_relaxed_fail_flags, vehicle_gnss_s::CHECK_SACC, gnss.sacc > 10.f); - setFail(vehicle_gnss_s::CHECK_SPOOFED, gnss.spoofed); - setFail(vehicle_gnss_s::CHECK_JAMMED, gnss.jammed); + setFail(_relaxed_fail_flags, vehicle_gnss_s::CHECK_SPOOFED, gnss.spoofed); + setFail(_relaxed_fail_flags, vehicle_gnss_s::CHECK_JAMMED, gnss.jammed); - return enabledChecksPass(kSimplifiedChecks); + return enabledChecksPass(_relaxed_fail_flags, kRelaxedChecks); } -bool GnssChecks::runInitialFixChecks(const gnssChecksSample &gnss, bool in_air, bool vehicle_at_rest) +bool GnssChecks::runStrictChecks(const gnssChecksSample &gnss, bool in_air, bool vehicle_at_rest) { // Check the fix type - setFail(vehicle_gnss_s::CHECK_FIX, gnss.fix_type < _params.req_fix); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_FIX, gnss.fix_type < _params.req_fix); // Check the number of satellites - setFail(vehicle_gnss_s::CHECK_NSATS, gnss.nsats < _params.req_nsats); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_NSATS, gnss.nsats < _params.req_nsats); // Check the position dilution of precision - setFail(vehicle_gnss_s::CHECK_PDOP, gnss.pdop > _params.req_pdop); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_PDOP, gnss.pdop > _params.req_pdop); // Check the reported horizontal and vertical position accuracy - setFail(vehicle_gnss_s::CHECK_EPH, gnss.hacc > _params.req_eph); - setFail(vehicle_gnss_s::CHECK_EPV, gnss.vacc > _params.req_epv); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_EPH, gnss.hacc > _params.req_eph); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_EPV, gnss.vacc > _params.req_epv); // Check the reported speed accuracy - setFail(vehicle_gnss_s::CHECK_SACC, gnss.sacc > _params.req_sacc); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_SACC, gnss.sacc > _params.req_sacc); - setFail(vehicle_gnss_s::CHECK_SPOOFED, gnss.spoofed); - setFail(vehicle_gnss_s::CHECK_JAMMED, gnss.jammed); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_SPOOFED, gnss.spoofed); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_JAMMED, gnss.jammed); runOnGroundGnssChecks(gnss, in_air, vehicle_at_rest); - return enabledChecksPass(UINT16_MAX); + return enabledChecksPass(_strict_fail_flags, UINT16_MAX); } void GnssChecks::runOnGroundGnssChecks(const gnssChecksSample &gnss, bool in_air, bool vehicle_at_rest) @@ -195,11 +196,11 @@ void GnssChecks::runOnGroundGnssChecks(const gnssChecksSample &gnss, bool in_air // hdrift: calculate the horizontal drift speed and fail if too high _horizontal_position_drift_rate_m_s = matrix::Vector2f(_lat_lon_alt_deriv_filt.xy()).norm(); - setFail(vehicle_gnss_s::CHECK_HDRIFT, _horizontal_position_drift_rate_m_s > _params.req_hdrift); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_HDRIFT, _horizontal_position_drift_rate_m_s > _params.req_hdrift); // vdrift: fail if the vertical drift speed is too high _vertical_position_drift_rate_m_s = fabsf(_lat_lon_alt_deriv_filt(2)); - setFail(vehicle_gnss_s::CHECK_VDRIFT, _vertical_position_drift_rate_m_s > _params.req_vdrift); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_VDRIFT, _vertical_position_drift_rate_m_s > _params.req_vdrift); // hspeed: check the magnitude of the filtered horizontal GNSS velocity const matrix::Vector2f vel_ne = matrix::constrain(matrix::Vector2f(gnss.vel.xy()), @@ -207,14 +208,14 @@ void GnssChecks::runOnGroundGnssChecks(const gnssChecksSample &gnss, bool in_air 10.0f * _params.req_hdrift); _vel_ne_filt = vel_ne * filter_coef + _vel_ne_filt * (1.0f - filter_coef); _filtered_horizontal_velocity_m_s = _vel_ne_filt.norm(); - setFail(vehicle_gnss_s::CHECK_HSPEED, _filtered_horizontal_velocity_m_s > _params.req_hdrift); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_HSPEED, _filtered_horizontal_velocity_m_s > _params.req_hdrift); // vspeed: check the magnitude of the filtered vertical GNSS velocity const float gnss_vz_limit = 10.f * _params.req_vdrift; const float gnss_vz = math::constrain(gnss.vel(2), -gnss_vz_limit, gnss_vz_limit); _vel_d_filt = gnss_vz * filter_coef + _vel_d_filt * (1.f - filter_coef); - setFail(vehicle_gnss_s::CHECK_VSPEED, fabsf(_vel_d_filt) > _params.req_vdrift); + setFail(_strict_fail_flags, vehicle_gnss_s::CHECK_VSPEED, fabsf(_vel_d_filt) > _params.req_vdrift); } else { // This is the case where the vehicle is on ground and IMU movement is blocking the drift calculation @@ -224,7 +225,7 @@ void GnssChecks::runOnGroundGnssChecks(const gnssChecksSample &gnss, bool in_air void GnssChecks::clearDriftChecks() { - _fail_flags &= ~kDriftChecks; + _strict_fail_flags &= ~kDriftChecks; resetDriftFilters(); } diff --git a/src/lib/gnss/gnss_checks.hpp b/src/lib/gnss/gnss_checks.hpp index fd0d84dee8a..6ee1ad64e16 100644 --- a/src/lib/gnss/gnss_checks.hpp +++ b/src/lib/gnss/gnss_checks.hpp @@ -74,17 +74,27 @@ public: void setParams(const Params ¶ms) { _params = params; } /* - * Return true if the GNSS solution quality is adequate. The strict checks apply until the first pass and again - * whenever the vehicle is disarmed on the ground; the drift checks run only at rest on the ground. + * Return true if the sample may be used. The strict checks (the GNSS_REQ_* thresholds, satellite count, PDOP, and + * drift at rest on the ground) decide until they pass and again whenever the vehicle is disarmed on the ground. The + * relaxed checks (fixed, looser limits) decide otherwise while the strict ones fail. Both run on every sample. */ bool run(const gnssChecksSample &gnss, bool armed, bool in_air, bool vehicle_at_rest); bool passed() const { return _passed; } - // The last run applied the strict thresholds: never passed yet, or disarmed on the ground + // The strict checks decided the last run: they haven't passed since the vehicle was disarmed on the ground, or they + // pass bool strict() const { return _strict; } - // Failed checks, as vehicle_gnss_s::CHECK_* bits - uint16_t getFailFlags() const { return _fail_flags; } + // The last sample passed the strict checks, and no check that decided passed() failed for the required pass + // duration. Once the relaxed checks decide, a sample that fails only the strict ones doesn't restart that duration, + // so that a single one doesn't drop the receiver's rank for GNSS_REQ_TIME: the selection's own hold rides through it. + bool passedStrict() const { return _passed_strict; } + + // The enabled checks the last sample failed at the strict thresholds, as vehicle_gnss_s::CHECK_* bits + uint16_t getStrictFailFlags() const { return _strict_fail_flags & getEnabledChecks(); } + + // The enabled checks the last sample failed at the relaxed thresholds, as vehicle_gnss_s::CHECK_* bits + uint16_t getRelaxedFailFlags() const { return _relaxed_fail_flags & getEnabledChecks(); } // The checks enabled in GNSS_CHECK, as vehicle_gnss_s::CHECK_* bits uint16_t getEnabledChecks() const { return static_cast(_params.check_mask) & kAllChecks; } @@ -112,17 +122,17 @@ private: } // How long the checks must pass after a failure before passed() is true - uint64_t getRequiredPassDurationUs() const + uint64_t getRequiredPassDurationUs(bool relaxed) const { - return _initial_checks_passed ? math::max((uint64_t)1e6, (uint64_t)_params.min_health_time_us / 10) + return relaxed ? math::max((uint64_t)1e6, (uint64_t)_params.min_health_time_us / 10) : (uint64_t)_params.min_health_time_us; } - void setFail(uint16_t check, bool failed); - bool enabledChecksPass(uint16_t checks) const { return (_fail_flags & checks & getEnabledChecks()) == 0; } + static void setFail(uint16_t &fail_flags, uint16_t check, bool failed); + bool enabledChecksPass(uint16_t fail_flags, uint16_t checks) const { return (fail_flags & checks & getEnabledChecks()) == 0; } - bool runSimplifiedChecks(const gnssChecksSample &gnss); - bool runInitialFixChecks(const gnssChecksSample &gnss, bool in_air, bool vehicle_at_rest); + bool runRelaxedChecks(const gnssChecksSample &gnss); + bool runStrictChecks(const gnssChecksSample &gnss, bool in_air, bool vehicle_at_rest); void runOnGroundGnssChecks(const gnssChecksSample &gnss, bool in_air, bool vehicle_at_rest); void clearDriftChecks(); @@ -133,7 +143,8 @@ private: return (timestamp_to_check_us == 0) || (timestamp_to_check_us + timeout_period < now_us); } - uint16_t _fail_flags{0}; + uint16_t _strict_fail_flags{0}; + uint16_t _relaxed_fail_flags{0}; float _horizontal_position_drift_rate_m_s{NAN}; float _vertical_position_drift_rate_m_s{NAN}; @@ -148,9 +159,10 @@ private: float _vel_d_filt{0.0f}; ///< GNSS filtered Down velocity (m/sec) uint64_t _time_last_fail_us{0}; uint64_t _time_last_pass_us{0}; - bool _initial_checks_passed{false}; + bool _initial_strict_checks_passed{false}; bool _strict{true}; bool _passed{false}; + bool _passed_strict{false}; Params _params{}; }; diff --git a/src/lib/gnss/test/CMakeLists.txt b/src/lib/gnss/test/CMakeLists.txt index ad32ae60477..d82a5ca66e7 100644 --- a/src/lib/gnss/test/CMakeLists.txt +++ b/src/lib/gnss/test/CMakeLists.txt @@ -36,6 +36,7 @@ px4_add_unit_gtest(SRC RtcmParserTest.cpp LINKLIBS gnss) px4_add_unit_gtest(SRC RtcmBustedSenderTest.cpp LINKLIBS gnss) px4_add_unit_gtest(SRC RtcmStressTest.cpp LINKLIBS gnss) px4_add_unit_gtest(SRC UbxFramerTest.cpp LINKLIBS gnss) +px4_add_unit_gtest(SRC GnssChecksTest.cpp LINKLIBS gnss_checks) if(CONFIG_GPS_SPARTN) px4_add_unit_gtest(SRC SpartnFramerTest.cpp LINKLIBS gnss) diff --git a/src/lib/gnss/test/GnssChecksTest.cpp b/src/lib/gnss/test/GnssChecksTest.cpp new file mode 100644 index 00000000000..9adca8c1637 --- /dev/null +++ b/src/lib/gnss/test/GnssChecksTest.cpp @@ -0,0 +1,218 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#include + +#include "../gnss_checks.hpp" + +class GnssChecksTest : public ::testing::Test +{ +public: + void SetUp() override + { + GnssChecks::Params params{}; + params.min_health_time_us = 1'000'000; + setParams(params); + + _sample.lat = 47.0; + _sample.lon = 9.0; + _sample.alt = 800.f; + _sample.hacc = 1.f; + _sample.vacc = 2.f; + _sample.sacc = 0.2f; + _sample.fix_type = 3; + _sample.nsats = 10; + _sample.pdop = 1.f; + } + + void setParams(GnssChecks::Params params) + { + _checks.setParams(params); + } + + void runSeconds(float duration_s, bool armed, bool in_air) + { + for (int k = 0; k < static_cast(duration_s * 10.f); k++) { + _sample.time_us += 100'000; + _checks.run(_sample, armed, in_air, !in_air); + } + } + + GnssChecks _checks; + gnssChecksSample _sample{}; +}; + +TEST_F(GnssChecksTest, passesAfterHealthTime) +{ + // WHEN: a receiver passes the strict checks on the ground + runSeconds(0.5f, false, false); + + // THEN: it passes once they held for the health time + EXPECT_FALSE(_checks.passed()); + + runSeconds(1.f, false, false); + + EXPECT_TRUE(_checks.passed()); + EXPECT_TRUE(_checks.strict()); +} + +TEST_F(GnssChecksTest, relaxedOnlyAfterStrictPass) +{ + // GIVEN: a receiver that starts publishing in flight, within the relaxed thresholds only + _sample.hacc = 10.f; + + // WHEN: it publishes for longer than the health time + runSeconds(5.f, true, true); + + // THEN: the strict checks still apply, and it doesn't pass + EXPECT_FALSE(_checks.passed()); + EXPECT_TRUE(_checks.strict()); + + // WHEN: it passes the strict checks for the health time + _sample.hacc = 1.f; + runSeconds(1.5f, true, true); + + // THEN: it passes, and the relaxed checks apply from then on + EXPECT_TRUE(_checks.passed()); + EXPECT_TRUE(_checks.strict()); + + _sample.hacc = 10.f; + runSeconds(1.f, true, true); + + EXPECT_TRUE(_checks.passed()); + EXPECT_FALSE(_checks.strict()); +} + +TEST_F(GnssChecksTest, relaxedWhileArmedOnGround) +{ + // GIVEN: a receiver that passed the strict checks, on a vehicle that armed and hasn't taken off + runSeconds(2.f, false, false); + runSeconds(1.f, true, false); + + // WHEN: its accuracy degrades beyond the strict threshold but within the relaxed one + _sample.hacc = 10.f; + runSeconds(1.f, true, false); + + // THEN: it still passes + EXPECT_TRUE(_checks.passed()); + EXPECT_FALSE(_checks.strict()); + EXPECT_FALSE(_checks.passedStrict()); +} + +TEST_F(GnssChecksTest, strictFailureOfOneSample) +{ + // GIVEN: a receiver that passed the strict checks, then took off + runSeconds(2.f, false, false); + runSeconds(1.f, true, true); + + // WHEN: a single sample has too few satellites for the strict checks + _sample.nsats = 4; + runSeconds(0.1f, true, true); + + // THEN: that sample doesn't pass the strict checks, but still passes the relaxed ones that decide + EXPECT_FALSE(_checks.passedStrict()); + EXPECT_TRUE(_checks.passed()); + EXPECT_EQ(_checks.getStrictFailFlags(), vehicle_gnss_s::CHECK_NSATS); + EXPECT_EQ(_checks.getRelaxedFailFlags(), 0); + + // WHEN: the next sample has enough again + _sample.nsats = 10; + runSeconds(0.1f, true, true); + + // THEN: it passes them again at once, as only a failure of the relaxed checks restarts the required pass duration + EXPECT_TRUE(_checks.passedStrict()); +} + +TEST_F(GnssChecksTest, strictInFlight) +{ + // GIVEN: a receiver that passed the strict checks, then took off + runSeconds(2.f, false, false); + runSeconds(1.f, true, true); + + EXPECT_TRUE(_checks.passed()); + EXPECT_TRUE(_checks.strict()); + EXPECT_TRUE(_checks.passedStrict()); + + // WHEN: its accuracy degrades beyond the strict threshold but within the relaxed one + _sample.hacc = 10.f; + runSeconds(1.f, true, true); + + // THEN: it still passes, but no longer passes the strict checks + EXPECT_TRUE(_checks.passed()); + EXPECT_FALSE(_checks.strict()); + EXPECT_FALSE(_checks.passedStrict()); +} + +TEST_F(GnssChecksTest, strictFixType) +{ + // GIVEN: a DGPS fix required, and a receiver that passed the strict checks, then took off + GnssChecks::Params params{}; + params.req_fix = 4; + setParams(params); + _sample.fix_type = 4; + + runSeconds(20.f, false, false); + runSeconds(1.f, true, true); + + EXPECT_TRUE(_checks.passedStrict()); + + // WHEN: it drops to a 3D fix, which the relaxed checks accept + _sample.fix_type = 3; + runSeconds(1.f, true, true); + + // THEN: it no longer passes the strict checks + EXPECT_TRUE(_checks.passed()); + EXPECT_FALSE(_checks.passedStrict()); +} + +TEST_F(GnssChecksTest, strictFollowsCheckMask) +{ + // GIVEN: the horizontal accuracy check disabled + GnssChecks::Params params{}; + params.check_mask &= ~vehicle_gnss_s::CHECK_EPH; + setParams(params); + + // WHEN: the horizontal accuracy exceeds its threshold + _sample.hacc = 10.f; + runSeconds(15.f, false, false); + + // THEN: it passes the strict checks + EXPECT_TRUE(_checks.passedStrict()); + + // WHEN: the speed accuracy exceeds its enabled threshold + _sample.sacc = 1.f; + runSeconds(1.f, false, false); + + // THEN: they aren't + EXPECT_FALSE(_checks.passedStrict()); +} diff --git a/src/lib/parameters/param_translation.cpp b/src/lib/parameters/param_translation.cpp index a4bed715167..598dc204b47 100644 --- a/src/lib/parameters/param_translation.cpp +++ b/src/lib/parameters/param_translation.cpp @@ -393,6 +393,8 @@ param_modify_on_import_ret param_modify_on_import(bson_node_t node) {"EKF2_REQ_HDRIFT", "GNSS_REQ_HDRIFT"}, {"EKF2_REQ_VDRIFT", "GNSS_REQ_VDRIFT"}, {"EKF2_REQ_FIX", "GNSS_REQ_FIX"}, + {"EKF2_REQ_SACC", "GNSS_REQ_SACC"}, + {"EKF2_REQ_GPS_H", "GNSS_REQ_TIME"}, }; for (const auto &rename : kRenames) { @@ -404,26 +406,6 @@ param_modify_on_import_ret param_modify_on_import(bson_node_t node) } } - // 2026-09-30: EKF2_REQ_SACC and EKF2_REQ_GPS_H stay EKF2 parameters for EKF2's own thresholds and waits, while the - // GNSS checks use GNSS_REQ_SACC and GNSS_REQ_TIME. A value tuned before the checks moved applied to both, so it is - // copied to the check parameter. Parameters are exported sorted by name, so a GNSS_* value saved alongside is - // imported after this and takes precedence. - { - static constexpr const char *kCopies[][2] { - {"EKF2_REQ_SACC", "GNSS_REQ_SACC"}, - {"EKF2_REQ_GPS_H", "GNSS_REQ_TIME"}, - }; - - for (const auto © : kCopies) { - if ((node->type == bson_type_t::BSON_DOUBLE) && (strcmp(copy[0], node->name) == 0)) { - const float value = static_cast(node->d); - param_set(param_find(copy[1]), &value); - PX4_INFO("copying %s -> %s", copy[0], copy[1]); - return param_modify_on_import_ret::PARAM_NOT_MODIFIED; - } - } - } - // 2026-10-06: translate CBRK_IO_SAFETY -> COM_SAFETY_MODE. Any value but the breaker key had safety enabled, with // both the switch and the MAVLink command able to turn it off. { diff --git a/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp b/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp index 016890fb22f..1e102ff748c 100644 --- a/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp +++ b/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp @@ -79,8 +79,8 @@ void Ekf::controlGnssYawFusion(const imuSample &imu_delayed) 2 * GNSS_YAW_MAX_INTERVAL); // The sensors module marks a heading unusable when its receiver reports spoofing or jamming, with the same effect - // as for position: its samples aren't fused, fusion stops once none has been for the reset timeout, and a reset - // waits for the GNSS health time. The position checks themselves don't gate the heading: it is a separate + // as for position: its samples aren't fused and fusion stops once none has been for the reset timeout; a reset + // also waits for EKF2_GPS_YAW_RST. The position checks themselves don't gate the heading: it is a separate // observation, often from a separate receiver. const bool is_heading_receiver_flagged = !gnss_yaw_sample.usable; @@ -134,8 +134,8 @@ void Ekf::controlGnssYawFusion(const imuSample &imu_delayed) || !isNorthEastAidingActive()) { // A reset takes the heading as is, so after a fusion failure or a spoofing or jamming report the - // receiver gets the GNSS health time to recover before it is trusted again - const bool reset_allowed = isTimedOut(_time_last_gnss_yaw_fail_us, _min_gps_health_time_us); + // receiver gets time to recover before it is trusted again + const bool reset_allowed = isTimedOut(_time_last_gnss_yaw_fail_us, _gnss_yaw_reset_wait_us); // Reset before starting the fusion if (reset_allowed && resetYawToGnss(gnss_yaw_sample.yaw, gnss_yaw_sample.yaw_offset)) { diff --git a/src/modules/ekf2/EKF/aid_sources/gnss/gps_control.cpp b/src/modules/ekf2/EKF/aid_sources/gnss/gps_control.cpp index 3dbe9fd3151..57b4b29cd78 100644 --- a/src/modules/ekf2/EKF/aid_sources/gnss/gps_control.cpp +++ b/src/modules/ekf2/EKF/aid_sources/gnss/gps_control.cpp @@ -151,7 +151,7 @@ void Ekf::controlGnssVelFusion(estimator_aid_source3d_s &aid_src, const bool for && _control_status.flags.yaw_align && !_control_status.flags.gnss_fault && !_control_status.flags.gnss_hgt_fault; - const bool starting_conditions_passing = continuing_conditions_passing && isGnssRestartHoldOffElapsed(); + const bool starting_conditions_passing = continuing_conditions_passing; if (_control_status.flags.gnss_vel) { if (continuing_conditions_passing) { @@ -208,8 +208,7 @@ void Ekf::controlGnssPosFusion(estimator_aid_source2d_s &aid_src, const bool for && _control_status.flags.tilt_align && _control_status.flags.yaw_align && !_control_status.flags.gnss_hgt_fault; - const bool starting_conditions_passing = continuing_conditions_passing && isGnssRestartHoldOffElapsed(); - const bool gpos_init_conditions_passing = gnss_pos_enabled && isGnssRestartHoldOffElapsed(); + const bool starting_conditions_passing = continuing_conditions_passing; // The new receiver can report a position offset from the previous one (different correction source) const bool receiver_changed = (_gps_sample_delayed.selection_count != _gnss_pos_selection_count); @@ -262,8 +261,7 @@ void Ekf::controlGnssPosFusion(estimator_aid_source2d_s &aid_src, const bool for bool reset = false; - if ((!fused && isGnssPosResetAllowed()) - || (gpos_init_conditions_passing && !_local_origin_lat_lon.isInitialized())) { + if ((!fused && isGnssPosResetAllowed()) || !_local_origin_lat_lon.isInitialized()) { resetHorizontalPositionToGnss(aid_src); reset = true; } @@ -275,7 +273,7 @@ void Ekf::controlGnssPosFusion(estimator_aid_source2d_s &aid_src, const bool for _control_status.flags.gnss_fault = false; } - } else if (gpos_init_conditions_passing && !_local_origin_lat_lon.isInitialized()) { + } else if (gnss_pos_enabled && !_local_origin_lat_lon.isInitialized()) { resetHorizontalPositionToGnss(aid_src); } } @@ -359,14 +357,14 @@ void Ekf::updateGnssVel(const imuSample &imu_sample, const gnssSample &gnss_samp getVelocityVariance() + vel_obs_var, // innovation variance innovation_gate); // innovation gate - // vz special case if there is bad vertical acceleration data, then don't reject measurement if GNSS reports velocity accuracy is acceptable, - // but limit innovation to prevent spikes that could destabilise the filter + // vz special case if there is bad vertical acceleration data, then don't reject measurement if the GNSS speed accuracy + // passes the strict check, but limit innovation to prevent spikes that could destabilise the filter bool bad_acc_vz_rejected = _fault_status.flags.bad_acc_vertical && (aid_src.test_ratio[2] > 1.f) // vz rejected && (aid_src.test_ratio[0] < 1.f) && (aid_src.test_ratio[1] < 1.f); // vx & vy accepted if (bad_acc_vz_rejected - && (gnss_sample.sacc < _params.ekf2_req_sacc) + && gnss_sample.sacc_passes_strict ) { const float innov_limit = innovation_gate * sqrtf(aid_src.innovation_variance[2]); aid_src.innovation[2] = math::constrain(aid_src.innovation[2], -innov_limit, innov_limit); @@ -415,7 +413,7 @@ void Ekf::controlGnssYawEstimator(estimator_aid_source3d_s &aid_src_vel) const Vector2f vel_xy(aid_src_vel.observation); if ((vel_var > 0.f) - && (vel_accuracy < _params.ekf2_req_sacc) + && _gps_sample_delayed.sacc_passes_strict && vel_xy.isAllFinite()) { _yawEstimator.fuseVelocity(vel_xy, vel_accuracy, _control_status.flags.in_air); @@ -530,9 +528,6 @@ void Ekf::stopGnssVelFusion() ECL_INFO("stopping GNSS velocity fusion"); _control_status.flags.gnss_vel = false; - if (!_control_status.flags.gnss_pos) { - _time_last_gnss_fusion_stop_us = _time_delayed_us; - } } } @@ -542,9 +537,6 @@ void Ekf::stopGnssPosFusion() ECL_INFO("stopping GNSS position fusion"); _control_status.flags.gnss_pos = false; - if (!_control_status.flags.gnss_vel) { - _time_last_gnss_fusion_stop_us = _time_delayed_us; - } } } diff --git a/src/modules/ekf2/EKF/common.h b/src/modules/ekf2/EKF/common.h index a819a891533..b28bc7a2672 100644 --- a/src/modules/ekf2/EKF/common.h +++ b/src/modules/ekf2/EKF/common.h @@ -204,6 +204,7 @@ struct gnssSample { bool jammed{}; ///< true if GNSS data is jammed Vector3f pos_body{}; ///< position of GPS antenna in body frame (m) bool usable{}; ///< the sample passes the GNSS checks of the sensors module + bool sacc_passes_strict{}; ///< the speed accuracy passes the strict check (GNSS_REQ_SACC), also in flight, or that check is disabled uint8_t selection_count{}; ///< increments when the sensors module selects another receiver }; @@ -380,7 +381,6 @@ struct parameters { float ekf2_gps_p_gate{5.0f}; ///< GPS horizontal position innovation consistency gate size (STD) float ekf2_gps_v_gate{5.0f}; ///< GPS velocity innovation consistency gate size (STD) - float ekf2_req_sacc{1.0f}; ///< speed accuracy below which GNSS vertical velocity is trusted while the accelerometer clips and GNSS velocity feeds the yaw estimator (m/s) # if defined(CONFIG_EKF2_GNSS_YAW) // GNSS heading fusion diff --git a/src/modules/ekf2/EKF/ekf.cpp b/src/modules/ekf2/EKF/ekf.cpp index d89eeeb4e92..9f77f3bcb65 100644 --- a/src/modules/ekf2/EKF/ekf.cpp +++ b/src/modules/ekf2/EKF/ekf.cpp @@ -96,7 +96,6 @@ void Ekf::reset() _gnss_usable = false; _gnss_checks_passed_reported = false; _time_last_gnss_sample_accepted_us = 0; - _time_last_gnss_fusion_stop_us = 0; #endif // CONFIG_EKF2_GNSS _local_origin_alt = NAN; diff --git a/src/modules/ekf2/EKF/ekf.h b/src/modules/ekf2/EKF/ekf.h index bf5e7b4df46..f76b1ca0f25 100644 --- a/src/modules/ekf2/EKF/ekf.h +++ b/src/modules/ekf2/EKF/ekf.h @@ -403,8 +403,8 @@ public: #endif // CONFIG_EKF2_EXTERNAL_VISION #if defined(CONFIG_EKF2_GNSS) - // set minimum continuous period without GPS fail required to mark a healthy GPS status - void set_min_required_gps_health_time(uint32_t time_us) { _min_gps_health_time_us = time_us; } + // After a GNSS heading failure, a yaw reset to the GNSS heading waits this long + void set_gnss_yaw_reset_wait(uint32_t time_us) { _gnss_yaw_reset_wait_us = time_us; } bool gps_checks_passed() const { return _gnss_usable; }; @@ -618,7 +618,6 @@ private: uint64_t _time_last_gnss_sample_accepted_us{0}; ///< last delayed-horizon time a GNSS sample was usable and within the velocity limit (us) bool _gnss_usable{false}; ///< the latest GNSS sample at the fusion time horizon was usable bool _gnss_checks_passed_reported{false}; ///< gps_checks_passed was reported since the last reset - uint64_t _time_last_gnss_fusion_stop_us{0}; ///< when GNSS velocity and position fusion were last both stopped HeightBiasEstimator _gps_hgt_b_est{HeightSensor::GNSS, _height_sensor_ref}; @@ -946,21 +945,6 @@ private: bool isGnssVelResetAllowed() const; bool isGnssPosResetAllowed() const; - // After velocity and position fusion both stop, a restart waits for the GNSS health time while disarmed on the - // ground, where the checks are strict, otherwise for a tenth of it and at least a second. The duration follows the - // current armed/in-air state, so arming during a ground hold-off shortens the remainder to the in-flight value. - // Computed here so the EKF does not depend on the checker's state. - uint64_t gnssRestartHoldOffUs() const - { - const bool disarmed_on_ground = !_control_status.flags.armed && !_control_status.flags.in_air; - return disarmed_on_ground ? (uint64_t)_min_gps_health_time_us - : math::max((uint64_t)1e6, (uint64_t)(_min_gps_health_time_us / 10)); - } - - bool isGnssRestartHoldOffElapsed() const - { - return isTimedOut(_time_last_gnss_fusion_stop_us, gnssRestartHoldOffUs()); - } void controlGnssYawEstimator(estimator_aid_source3d_s &aid_src_vel); bool tryYawEmergencyReset(); void resetVelocityToGnss(estimator_aid_source3d_s &aid_src); diff --git a/src/modules/ekf2/EKF/estimator_interface.h b/src/modules/ekf2/EKF/estimator_interface.h index 1abd6349c44..9cd1c963eec 100644 --- a/src/modules/ekf2/EKF/estimator_interface.h +++ b/src/modules/ekf2/EKF/estimator_interface.h @@ -405,7 +405,7 @@ protected: gnssSample _gps_sample_delayed{}; - uint32_t _min_gps_health_time_us{10000000}; ///< GPS is marked as healthy only after this amount of time + uint32_t _gnss_yaw_reset_wait_us{10000000}; # if defined(CONFIG_EKF2_GNSS_YAW) TimestampedRingBuffer *_gnss_yaw_buffer {nullptr}; diff --git a/src/modules/ekf2/EKF2.cpp b/src/modules/ekf2/EKF2.cpp index 26b1170df13..e1c17f95dc4 100644 --- a/src/modules/ekf2/EKF2.cpp +++ b/src/modules/ekf2/EKF2.cpp @@ -120,7 +120,6 @@ EKF2::EKF2(bool multi_mode, const px4::wq_config_t &config, bool replay_mode): _param_ekf2_gps_p_noise(_params->ekf2_gps_p_noise), _param_ekf2_gps_p_gate(_params->ekf2_gps_p_gate), _param_ekf2_gps_v_gate(_params->ekf2_gps_v_gate), - _param_ekf2_req_sacc(_params->ekf2_req_sacc), _param_ekf2_gsf_tas(_params->ekf2_gsf_tas), #endif // CONFIG_EKF2_GNSS #if defined(CONFIG_EKF2_BAROMETER) @@ -496,7 +495,7 @@ void EKF2::Run() AdvertiseTopics(); #if defined(CONFIG_EKF2_GNSS) - _ekf.set_min_required_gps_health_time(_param_ekf2_req_gps_h.get() * 1_s); + _ekf.set_gnss_yaw_reset_wait(_param_ekf2_gps_yaw_rst.get() * 1_s); #endif // CONFIG_EKF2_GNSS const matrix::Vector3f imu_pos_body(_param_ekf2_imu_pos_x.get(), @@ -2633,7 +2632,7 @@ void EKF2::UpdateGnssSample(ekf2_timestamps_s &ekf2_timestamps) if (_vehicle_gnss_sub.update(&vehicle_gnss)) { - _gnss_failed_checks = vehicle_gnss.failed_checks; + _gnss_failed_checks = vehicle_gnss.strict ? vehicle_gnss.failed_strict_checks : vehicle_gnss.failed_relaxed_checks; Vector3f vel_ned; @@ -2669,6 +2668,7 @@ void EKF2::UpdateGnssSample(ekf2_timestamps_s &ekf2_timestamps) vehicle_gnss.antenna_offset[1], vehicle_gnss.antenna_offset[2]), .usable = vehicle_gnss.usable, + .sacc_passes_strict = !(vehicle_gnss.failed_strict_checks & vehicle_gnss_s::CHECK_SACC), .selection_count = vehicle_gnss.selection_count, }; diff --git a/src/modules/ekf2/EKF2.hpp b/src/modules/ekf2/EKF2.hpp index f8c276ead6c..a1fb2c67652 100644 --- a/src/modules/ekf2/EKF2.hpp +++ b/src/modules/ekf2/EKF2.hpp @@ -491,7 +491,7 @@ private: float _last_gnss_hgt_bias_published{}; - uint16_t _gnss_failed_checks{0}; ///< failed_checks of the latest vehicle_gnss sample + uint16_t _gnss_failed_checks{0}; ///< failed checks of the latest vehicle_gnss sample, among those that decide usable uORB::Subscription _vehicle_gnss_sub{ORB_ID(vehicle_gnss)}; @@ -561,8 +561,7 @@ private: (ParamExtFloat) _param_ekf2_gps_p_gate, (ParamExtFloat) _param_ekf2_gps_v_gate, - (ParamExtFloat) _param_ekf2_req_sacc, - (ParamFloat) _param_ekf2_req_gps_h, + (ParamFloat) _param_ekf2_gps_yaw_rst, // Used by EKF-GSF experimental yaw estimator (ParamExtFloat) _param_ekf2_gsf_tas, diff --git a/src/modules/ekf2/params_gnss.yaml b/src/modules/ekf2/params_gnss.yaml index 96bd0c58bb5..038f386e638 100644 --- a/src/modules/ekf2/params_gnss.yaml +++ b/src/modules/ekf2/params_gnss.yaml @@ -78,27 +78,13 @@ parameters: unit: m/s max: 100.0 decimal: 1 - EKF2_REQ_GPS_H: + EKF2_GPS_YAW_RST: description: - short: GNSS fusion restart and heading reset wait - long: After EKF2 stops GNSS velocity and position fusion, it restarts it only - after this time while disarmed on the ground, and after a tenth of it, at - least 1 s, otherwise. After a GNSS heading failure, a yaw reset to the GNSS - heading also waits this long. The GNSS checks use GNSS_REQ_TIME. + short: GNSS heading reset wait + long: After GNSS heading fusion fails, or the heading receiver reports spoofing + or jamming, EKF2 waits this long before resetting yaw to the GNSS heading. type: float default: 10.0 min: 0.1 decimal: 1 unit: s - EKF2_REQ_SACC: - description: - short: GNSS speed accuracy for vertical velocity and yaw estimator - long: Below this speed accuracy EKF2 trusts the GNSS vertical velocity while the - accelerometer clips, and feeds the GNSS velocity to the EKF-GSF yaw estimator. - The GNSS checks use GNSS_REQ_SACC. - type: float - default: 0.5 - min: 0.5 - max: 5.0 - unit: m/s - decimal: 2 diff --git a/src/modules/ekf2/test/sensor_simulator/gps.cpp b/src/modules/ekf2/test/sensor_simulator/gps.cpp index 382fdf436a6..86b9095f910 100644 --- a/src/modules/ekf2/test/sensor_simulator/gps.cpp +++ b/src/modules/ekf2/test/sensor_simulator/gps.cpp @@ -56,6 +56,7 @@ void Gps::send(const uint64_t time) const auto &control_status = _ekf->control_status_flags(); _gps_data.usable = _checks.run(sample, control_status.armed, control_status.in_air, control_status.vehicle_at_rest); + _gps_data.sacc_passes_strict = !(_checks.getStrictFailFlags() & vehicle_gnss_s::CHECK_SACC); _ekf->setGpsData(_gps_data); } @@ -64,7 +65,7 @@ void Gps::setMinRequiredGnssHealthTime(uint64_t time_us) { _check_params.min_health_time_us = time_us; _checks.setParams(_check_params); - _ekf->set_min_required_gps_health_time(time_us); + _ekf->set_gnss_yaw_reset_wait(time_us); } void Gps::setCheckMask(int32_t check_mask) diff --git a/src/modules/ekf2/test/sensor_simulator/gps.h b/src/modules/ekf2/test/sensor_simulator/gps.h index b6eea96acb9..49bfa0e8ef4 100644 --- a/src/modules/ekf2/test/sensor_simulator/gps.h +++ b/src/modules/ekf2/test/sensor_simulator/gps.h @@ -53,7 +53,7 @@ public: Gps(std::shared_ptr ekf); ~Gps(); - // Sets both the health time of the checks (GNSS_REQ_TIME) and the EKF's waits (EKF2_REQ_GPS_H) + // Sets both the health time of the checks (GNSS_REQ_TIME) and the EKF's heading reset wait (EKF2_GPS_YAW_RST) void setMinRequiredGnssHealthTime(uint64_t time_us); void setCheckMask(int32_t check_mask); void setData(const gnssSample &gps); diff --git a/src/modules/ekf2/test/test_EKF_gnss_yaw.cpp b/src/modules/ekf2/test/test_EKF_gnss_yaw.cpp index 079358b745f..1f729cd2b97 100644 --- a/src/modules/ekf2/test/test_EKF_gnss_yaw.cpp +++ b/src/modules/ekf2/test/test_EKF_gnss_yaw.cpp @@ -432,7 +432,7 @@ TEST_F(EkfGpsHeadingTest, unusableHeading) _sensor_simulator._gnss_yaw.setUsable(true); _sensor_simulator.runSeconds(5); - // THEN: the heading is trusted for a reset only after EKF2_REQ_GPS_H (10 s) + // THEN: the heading is trusted for a reset only after EKF2_GPS_YAW_RST (10 s) EXPECT_FALSE(_ekf_wrapper.isIntendingGpsHeadingFusion()); _sensor_simulator.runSeconds(6); EXPECT_TRUE(_ekf_wrapper.isIntendingGpsHeadingFusion()); diff --git a/src/modules/ekf2/test/test_EKF_gps.cpp b/src/modules/ekf2/test/test_EKF_gps.cpp index 79b942c12e5..6b4a0ed40b0 100644 --- a/src/modules/ekf2/test/test_EKF_gps.cpp +++ b/src/modules/ekf2/test/test_EKF_gps.cpp @@ -107,7 +107,7 @@ TEST_F(EkfGpsTest, gpsTimeout) EXPECT_TRUE(_ekf_wrapper.isIntendingGpsFusion()); } -TEST_F(EkfGpsTest, gnssRestartHeldOffAfterFusionStop) +TEST_F(EkfGpsTest, gnssRestartWithoutWaitAfterFusionStop) { // GIVEN: an EKF fusing GNSS in flight _ekf->set_in_air_status(true); @@ -121,10 +121,8 @@ TEST_F(EkfGpsTest, gnssRestartHeldOffAfterFusionStop) EXPECT_FALSE(_ekf_wrapper.isIntendingGpsFusion()); _ekf_wrapper.enableGpsFusion(); - // THEN: fusion restarts only once the in-flight restart hold-off (1 s) has passed since the stop - _sensor_simulator.runSeconds(0.3); - EXPECT_FALSE(_ekf_wrapper.isIntendingGpsFusion()); - _sensor_simulator.runSeconds(1.5); + // THEN: fusion restarts with the next samples, as they already passed the checks for GNSS_REQ_TIME + _sensor_simulator.runSeconds(0.5); EXPECT_TRUE(_ekf_wrapper.isIntendingGpsFusion()); } diff --git a/src/modules/ekf2/test/test_EKF_height_fusion.cpp b/src/modules/ekf2/test/test_EKF_height_fusion.cpp index 269bda9d8b8..0cdf560b48c 100644 --- a/src/modules/ekf2/test/test_EKF_height_fusion.cpp +++ b/src/modules/ekf2/test/test_EKF_height_fusion.cpp @@ -252,7 +252,7 @@ TEST_F(EkfHeightFusionTest, gpsHeightFusionContinuesThroughHorizontalStop) _sensor_simulator.runSeconds(0.5); EXPECT_FALSE(_ekf_wrapper.isIntendingGpsFusion()); - // THEN: height fusion continues, both during the horizontal restart hold-off (1 s) and after it + // THEN: height fusion continues while horizontal fusion is stopped EXPECT_TRUE(_ekf_wrapper.isIntendingGpsHeightFusion()); EXPECT_GT(_ekf->aid_src_gnss_hgt().time_last_fuse, time_stopped); _sensor_simulator.runSeconds(1.5); diff --git a/src/modules/sensors/vehicle_gps_position/CMakeLists.txt b/src/modules/sensors/vehicle_gps_position/CMakeLists.txt index 36daf0bd55d..5c1a29c3e94 100644 --- a/src/modules/sensors/vehicle_gps_position/CMakeLists.txt +++ b/src/modules/sensors/vehicle_gps_position/CMakeLists.txt @@ -35,8 +35,8 @@ px4_add_library(vehicle_gps_position VehicleGPSPosition.cpp VehicleGPSPosition.hpp GnssHeadingBaseline.hpp - gps_blending.cpp - gps_blending.hpp + GnssSelector.cpp + GnssSelector.hpp PpsTimeSync.cpp PpsTimeSync.hpp ) @@ -47,5 +47,5 @@ target_link_libraries(vehicle_gps_position px4_work_queue ) -px4_add_unit_gtest(SRC gps_blending_test.cpp LINKLIBS vehicle_gps_position) +px4_add_unit_gtest(SRC GnssSelectorTest.cpp LINKLIBS vehicle_gps_position) px4_add_unit_gtest(SRC GnssHeadingBaselineTest.cpp) diff --git a/src/modules/sensors/vehicle_gps_position/GnssSelector.cpp b/src/modules/sensors/vehicle_gps_position/GnssSelector.cpp new file mode 100644 index 00000000000..e443ed8a440 --- /dev/null +++ b/src/modules/sensors/vehicle_gps_position/GnssSelector.cpp @@ -0,0 +1,385 @@ +/**************************************************************************** + * + * Copyright (c) 2021 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * @file GnssSelector.cpp + */ + +#include "GnssSelector.hpp" + +#include + +GnssSelector::GnssSelector() +{ + for (AlphaFilter &availability : _availability) { + availability = AlphaFilter(AVAILABILITY_TIME_CONSTANT_US); + } +} + +void GnssSelector::update(uint64_t hrt_now_us) +{ + updateReceiverTimeouts(hrt_now_us); + updateAvailability(hrt_now_us); + + _selected_instance = selectReceiver(hrt_now_us); + _selection_reason = selectionReason(); + _selected_has_new_sample = _updated[_selected_instance]; + + if (_selected_has_new_sample) { + if ((_output_instance >= 0) && (_output_instance != _selected_instance)) { + _selection_count++; + } + + _output_instance = _selected_instance; + } + + for (uint8_t i = 0; i < GNSS_MAX_RECEIVERS; i++) { + _updated[i] = false; + _time_prev_us[i] = _sample[i].timestamp; + } +} + +uint8_t GnssSelector::selectionReason() const +{ + bool other_has_published = false; + + for (int i = 0; i < GNSS_MAX_RECEIVERS; i++) { + if ((i != _selected_instance) && _has_published[i]) { + other_has_published = true; + } + } + + if (!other_has_published) { + return vehicle_gnss_s::SELECTION_ONLY; + } + + if (_switch_reason != REASON_INITIAL) { + return _switch_reason; + } + + if (hasPreferred() && (_selected_instance == _preferred_instance)) { + return vehicle_gnss_s::SELECTION_PREFERRED; + } + + if (hasPreferred()) { + return isSilent(_preferred_instance) ? vehicle_gnss_s::SELECTION_TIMEOUT : vehicle_gnss_s::SELECTION_UNHEALTHY; + } + + return vehicle_gnss_s::SELECTION_RANKED; +} + +void GnssSelector::updateReceiverTimeouts(uint64_t hrt_now_us) +{ + for (uint8_t i = 0; i < GNSS_MAX_RECEIVERS; i++) { + const uint64_t timestamp = _sample[i].timestamp; + UpdateInterval &interval = _interval[i]; + + if (timestamp > _time_prev_us[i]) { + // the first sample of a receiver has no previous one to compute an interval from + if ((_time_prev_us[i] > 0) && (timestamp - _time_prev_us[i] < GNSS_TIMEOUT_US)) { + const uint64_t interval_us = timestamp - _time_prev_us[i]; + interval.late = interval_us > lateIntervalUs(i); + + const float dt = 1e-6f * interval_us; + interval.filtered_s = (interval.filtered_s > 0.f) + ? interval.filtered_s + dt / (INTERVAL_TIME_CONSTANT_S + dt) * (dt - interval.filtered_s) + : dt; + + if (interval.samples < INTERVAL_SETTLE_SAMPLES) { + interval.samples++; + } + } + + } else if ((timestamp > 0) && (hrt_now_us >= timestamp + GNSS_TIMEOUT_US)) { + resetReceiver(i); + } + } +} + +void GnssSelector::updateAvailability(uint64_t hrt_now_us) +{ + // A gap longer than a second means that updates stalled. It is weighted as one second, so that the update after it + // doesn't overwrite the history. + uint64_t dt_us = 0; + + if ((_time_last_update_us > 0) && (hrt_now_us > _time_last_update_us)) { + dt_us = math::min(hrt_now_us - _time_last_update_us, static_cast(1_s)); + } + + _time_last_update_us = hrt_now_us; + + for (int i = 0; i < GNSS_MAX_RECEIVERS; i++) { + const bool usable = isUsable(i, hrt_now_us); + + if (usable) { + _time_last_usable_us[i] = hrt_now_us; + } + + const bool failed = hasFailed(i, hrt_now_us); + + if (_armed && !failed) { + _working_while_armed[i] = true; + } + + if (failed) { + _strict_qualified[i] = false; + + } else if (_sample[i].passed_strict) { + _strict_qualified[i] = true; + } + + if (usable && !_has_passed[i]) { + // A receiver first passes after the strict checks held for GNSS_REQ_TIME, which already proves it + _availability[i].reset(1.f); + _has_passed[i] = true; + + } else { + _availability[i].update(usable ? 1.f : 0.f, dt_us); + } + } +} + +hrt_abstime GnssSelector::lateIntervalUs(int instance) const +{ + if (_interval[instance].samples >= INTERVAL_SETTLE_SAMPLES) { + return math::constrain(static_cast(LATE_INTERVAL_RATIO * _interval[instance].filtered_s * 1e6f), + LATE_MIN_US, GNSS_TIMEOUT_US); + } + + return GNSS_TIMEOUT_US; +} + +bool GnssSelector::isUsable(int instance, uint64_t hrt_now_us) const +{ + if (isSilent(instance) || !_sample[instance].checks_passed || _interval[instance].late) { + return false; + } + + return hrt_now_us <= _sample[instance].timestamp + lateIntervalUs(instance); +} + +GnssSelector::Rank GnssSelector::rank(int instance, uint64_t hrt_now_us) const +{ + if (!isUsable(instance, hrt_now_us)) { + return RANK_UNUSABLE; + } + + if (!_sample[instance].strict_checks_pass || !_strict_qualified[instance]) { + return RANK_USABLE; + } + + return (_sample[instance].rtk_fixed && !hasPreferred()) ? RANK_RTK_FIXED : RANK_STRICT; +} + +int GnssSelector::bestReplacement(int current, bool usable_only, uint64_t hrt_now_us) const +{ + int best = -1; + + for (int i = 0; i < GNSS_MAX_RECEIVERS; i++) { + if ((i == current) || isSilent(i) || (usable_only && !isUsable(i, hrt_now_us))) { + continue; + } + + if ((best < 0) || isBetterReceiver(i, best, hrt_now_us)) { + best = i; + } + } + + return best; +} + +int GnssSelector::bestCandidate(uint64_t hrt_now_us) const +{ + int best = -1; + + for (int i = 0; i < GNSS_MAX_RECEIVERS; i++) { + if (!isUsable(i, hrt_now_us)) { + continue; + } + + if ((best < 0) || isBetterReceiver(i, best, hrt_now_us, AVAILABILITY_MARGIN)) { + best = i; + } + } + + return best; +} + +bool GnssSelector::isBetterReceiver(int instance, int other, uint64_t hrt_now_us, float tiebreaker_availability_margin) const +{ + if (instance < 0) { + return false; + } + + if (other < 0) { + return true; + } + + const Rank instance_rank = rank(instance, hrt_now_us); + const Rank other_rank = rank(other, hrt_now_us); + + // A receiver that failed while armed is never better than a usable one that didn't + if (other_rank >= RANK_USABLE && !_failed_while_armed[other] && _failed_while_armed[instance]) { + return false; + } + + // One that is clearly more available is better whatever its rank, as something is wrong with the other one + const float instance_availability = _availability[instance].getState(); + const float other_availability = _availability[other].getState(); + + if (instance_rank >= RANK_USABLE && (instance_availability > other_availability + AVAILABILITY_MARGIN)) { + return true; + } + + if (other_rank >= RANK_USABLE && (other_availability > instance_availability + AVAILABILITY_MARGIN)) { + return false; + } + + if (instance_rank != other_rank) { + return instance_rank > other_rank; + } + + // The preferred receiver is better only while it passes the strict checks: when neither does, moving to it is a + // reset for nothing + if (hasPreferred() && (instance_rank >= RANK_STRICT) + && ((instance == _preferred_instance) || (other == _preferred_instance))) { + return instance == _preferred_instance; + } + + return instance_availability > other_availability + tiebreaker_availability_margin; +} + +hrt_abstime GnssSelector::switchHoldUs() const +{ + return _armed ? (SWITCH_HOLD_ARMED_US << math::min(_rank_switches_while_armed, SWITCH_HOLD_MAX_DOUBLINGS)) + : SWITCH_HOLD_DISARMED_US; +} + +int GnssSelector::switchTo(int instance, uint8_t reason) +{ + _switch_reason = reason; + _switch_candidate = -1; + return instance; +} + +int GnssSelector::failOver(int instance, uint8_t reason) +{ + if (_armed && _working_while_armed[_selected_instance]) { + _failed_while_armed[_selected_instance] = true; + } + + return switchTo(instance, reason); +} + +int GnssSelector::selectReceiver(uint64_t hrt_now_us) +{ + const int current = _selected_instance; + const int preferred = hasPreferred() ? _preferred_instance : -1; + + // While disarmed the preferred receiver is used whenever it publishes, even while it fails its checks, so that the + // vehicle doesn't take off on the other one + if (!_armed && (preferred >= 0) && !isSilent(preferred)) { + _switch_candidate = -1; + return (current == preferred) ? current : switchTo(preferred, vehicle_gnss_s::SELECTION_PREFERRED); + } + + // A receiver that stopped publishing is replaced by any one that publishes, so that samples keep coming + if (isSilent(current)) { + const int best = bestReplacement(current, false, hrt_now_us); + + if (best < 0) { + _switch_candidate = -1; + return current; + } + + // Before the first output no selected receiver stopped publishing + return (_output_instance >= 0) ? failOver(best, vehicle_gnss_s::SELECTION_TIMEOUT) : switchTo(best, REASON_INITIAL); + } + + // A failed receiver is replaced by any usable one, however available that one was recently + if (hasFailed(current, hrt_now_us)) { + const int best = bestReplacement(current, true, hrt_now_us); + + if (best >= 0) { + return failOver(best, vehicle_gnss_s::SELECTION_UNHEALTHY); + } + } + + // The best receiver replaces the selected one once it has been clearly better through the hold time, so that + // shorter changes in either one ride through + const int best_candidate = bestCandidate(hrt_now_us); + + if (best_candidate < 0 || best_candidate == current) { + _switch_candidate = -1; + return current; + } + + // Only switch if the best candidate is significantly better + if (!isBetterReceiver(best_candidate, current, hrt_now_us, AVAILABILITY_MARGIN)) { + _switch_candidate = -1; + return current; + } + + if (best_candidate != _switch_candidate) { + _switch_candidate = best_candidate; + _switch_candidate_since_us = hrt_now_us; + return current; + } + + if (hrt_now_us < _switch_candidate_since_us + switchHoldUs()) { + return current; + } + + if (_armed) { + _rank_switches_while_armed++; + } + + if (best_candidate == preferred) { + return switchTo(best_candidate, vehicle_gnss_s::SELECTION_PREFERRED); + } + + uint8_t switch_reason = vehicle_gnss_s::SELECTION_RANKED; + Rank best_rank = rank(best_candidate, hrt_now_us); + + if (_availability[best_candidate].getState() > _availability[current].getState() + AVAILABILITY_MARGIN) { + switch_reason = vehicle_gnss_s::SELECTION_UNHEALTHY; + + } else if (best_rank == RANK_RTK_FIXED) { + switch_reason = vehicle_gnss_s::SELECTION_RTK_FIXED; + + } else if (best_rank == RANK_STRICT) { + switch_reason = vehicle_gnss_s::SELECTION_STRICT; + } + + return switchTo(best_candidate, switch_reason); +} diff --git a/src/modules/sensors/vehicle_gps_position/GnssSelector.hpp b/src/modules/sensors/vehicle_gps_position/GnssSelector.hpp new file mode 100644 index 00000000000..eb2cd335c90 --- /dev/null +++ b/src/modules/sensors/vehicle_gps_position/GnssSelector.hpp @@ -0,0 +1,278 @@ +/**************************************************************************** + * + * Copyright (c) 2021 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * @file GnssSelector.hpp + */ + +#pragma once + +#include +#include +#include +#include +#include + +using namespace time_literals; + +/* + * Selects the receiver whose samples vehicle_gnss carries; the caller keeps the samples and publishes the selected + * receiver's. Every switch makes EKF2 reset or restart its GNSS position, so short changes in either receiver ride + * through a hold before the selection moves. + * + * A receiver is usable while its latest sample passed its checks and came without a gap in its output. It has failed + * when it had no usable sample for FAIL_TIME_US, which covers a lost fix, sustained check failures, a receiver that + * stopped publishing and an update rate that dropped below about 1 Hz. A failed receiver is replaced at once, and while + * armed it is selected again only when the selected one fails, as one that failed is likely to fail again in the same + * flight. Intermittent failures are caught by the availability: the fraction of recent time a receiver was usable. + * + * Receivers rank by being usable, then by passing the strict checks (GNSS_REQ_* and the other pre-arm thresholds), + * then, without a preferred receiver, by an RTK fixed solution. A receiver gains the strict rank once its strict checks + * held for GNSS_REQ_TIME, and keeps it while its samples pass them until it fails. In flight a failed sample restarts + * GNSS_REQ_TIME, as long as the switch hold, so without this a one-second failure would still switch. The selection + * moves to the best receiver once it has been clearly better than the selected one through the hold time. A receiver + * more available by AVAILABILITY_MARGIN is better whatever its rank; otherwise the higher rank is better, then the + * preferred receiver while it passes the strict checks. So the preferred receiver is kept while it passes them and is + * about as available as the other one, and left when it has failed them through the hold while the other one passed + * them. A moving-base rover reports a better fix and accuracy while being the + * worse position source, so an RTK fixed solution never outranks the preferred receiver. While disarmed the preferred + * receiver is selected whenever it publishes: a vehicle whose preferred receiver fails its checks shouldn't take off + * on the other one. + */ +class GnssSelector +{ +public: + // A receiver that hasn't published for this long is dropped + static constexpr hrt_abstime GNSS_TIMEOUT_US = 2_s; + + // Without a usable sample for this long the selected receiver has failed, and any usable receiver replaces it + static constexpr hrt_abstime FAIL_TIME_US = 2_s; + + // A single failed sample makes a receiver unusable for about a second in flight, which costs it 0.1 availability + // with this time constant; a receiver usable a third of the time costs the margin within a few seconds. It counts + // from arming, as while disarmed the strict checks keep a receiver unusable for GNSS_REQ_TIME after every failure. + static constexpr hrt_abstime AVAILABILITY_TIME_CONSTANT_US = 10_s; + // A usable receiver more available by this margin is better whatever its rank, as something is wrong with the other + static constexpr float AVAILABILITY_MARGIN = 0.2f; + + // How long a receiver must rank higher before the selection moves to it. While disarmed a receiver is usable only + // once the strict checks held for GNSS_REQ_TIME. While armed the hold doubles with every such switch, so that + // receivers passing and failing the strict checks for longer than the hold can't keep resetting EKF2. + static constexpr hrt_abstime SWITCH_HOLD_ARMED_US = 10_s; + static constexpr hrt_abstime SWITCH_HOLD_DISARMED_US = 2_s; + static constexpr uint8_t SWITCH_HOLD_MAX_DOUBLINGS = 4; + + // A sample is late, a gap in the receiver's output, when its interval exceeds this many times the receiver's recent + // interval, and at least LATE_MIN_US. The recent interval follows a lower rate within a sample, as receivers slow + // down for reasons that don't make their samples worse, such as processing corrections: only the first sample at + // the lower rate is late. Below about 1 Hz, the first two intervals at the lower rate add up to FAIL_TIME_US. + static constexpr float LATE_INTERVAL_RATIO = 3.f; + static constexpr hrt_abstime LATE_MIN_US = 300_ms; + // The recent interval filter is used once it has this many samples. It weights intervals by their duration, so + // that samples delivered in bursts don't shorten it. + static constexpr float INTERVAL_TIME_CONSTANT_S = 1.f; + static constexpr uint8_t INTERVAL_SETTLE_SAMPLES = 10; + + static constexpr int GNSS_MAX_RECEIVERS = 2; + + GnssSelector(); + ~GnssSelector() = default; + + // The results of the receiver's own GnssChecks for this sample: checks_passed decides usable, strict_checks_pass is + // whether the sample is within the strict thresholds, and passed_strict whether they also held for GNSS_REQ_TIME + void setGnssData(const sensor_gnss_s &gnss_data, bool checks_passed, bool strict_checks_pass, bool passed_strict, + uint8_t instance) + { + if (instance < GNSS_MAX_RECEIVERS) { + _sample[instance] = {gnss_data.timestamp, checks_passed, strict_checks_pass, passed_strict, + gnss_data.fix_type == sensor_gnss_s::FIX_TYPE_RTK_FIXED + }; + _updated[instance] = true; + _has_published[instance] = true; + } + } + + // -1 for no preferred receiver + void setPreferredInstance(int instance) { _preferred_instance = instance; } + void setArmed(bool armed) + { + if (armed && !_armed) { + for (int i = 0; i < GNSS_MAX_RECEIVERS; i++) { + if (_has_passed[i]) { + _availability[i].reset(1.f); + } + } + } + + _armed = armed; + + if (!armed) { + for (int i = 0; i < GNSS_MAX_RECEIVERS; i++) { + _failed_while_armed[i] = false; + _working_while_armed[i] = false; + } + + _rank_switches_while_armed = 0; + } + } + + // Also call it periodically while no receiver publishes, so that receivers time out and lose availability + void update(uint64_t hrt_now_us); + + int getSelectedInstance() const { return _selected_instance; } + + // The selected receiver delivered a sample since the previous update, for the caller to publish + bool selectedHasNewSample() const { return _selected_has_new_sample; } + + // Increments when the published samples change to another receiver, which steps the position that consumers see + uint8_t getSelectionCount() const { return _selection_count; } + + // Why the selected receiver is selected, as vehicle_gnss_s::SELECTION_* + uint8_t getSelectionReason() const { return _selection_reason; } + + // The latest sample passed its checks and neither it nor the next one is late + bool isUsable(int instance, uint64_t hrt_now_us) const; + + // No usable sample for FAIL_TIME_US, or never one: the selection fails over from it + bool hasFailed(int instance, uint64_t hrt_now_us) const + { + return isSilent(instance) || (_time_last_usable_us[instance] == 0) + || (hrt_now_us >= _time_last_usable_us[instance] + FAIL_TIME_US); + } + + float getAvailability(int instance) const + { + return ((instance >= 0) && (instance < GNSS_MAX_RECEIVERS)) ? _availability[instance].getState() : 0.f; + } + +private: + // What the selection uses of a receiver's latest sample + struct Sample { + uint64_t timestamp{0}; ///< 0 when never published or timed out + bool checks_passed{false}; + bool strict_checks_pass{false}; + bool passed_strict{false}; + bool rtk_fixed{false}; + }; + + struct UpdateInterval { + float filtered_s{0.f}; ///< 0 until measured + uint8_t samples{0}; ///< up to INTERVAL_SETTLE_SAMPLES + bool late{false}; ///< the latest sample came late + }; + + // Track each receiver's update interval, and reset a receiver that stopped publishing + void updateReceiverTimeouts(uint64_t hrt_now_us); + + // A receiver that timed out may come back at another rate. Its availability and the time it was last usable are + // kept, so that the outage counts against it. + void resetReceiver(int instance) + { + _sample[instance] = {}; + _interval[instance] = {}; + } + + void updateAvailability(uint64_t hrt_now_us); + + int selectReceiver(uint64_t hrt_now_us); + + uint8_t selectionReason() const; + + // Never published, or timed out + bool isSilent(int instance) const { return _sample[instance].timestamp == 0; } + + + hrt_abstime lateIntervalUs(int instance) const; + + enum Rank : int8_t { + RANK_UNUSABLE = -1, + RANK_USABLE = 0, + RANK_STRICT = 1, ///< passes the strict checks and has qualified for them + RANK_RTK_FIXED = 2, ///< passes the strict checks with an RTK fixed solution, without a preferred receiver + }; + + Rank rank(int instance, uint64_t hrt_now_us) const; + + // The receiver to replace a failed or silent current one with, -1 if none: any one that publishes, or only usable + // ones + int bestReplacement(int current, bool usable_only, uint64_t hrt_now_us) const; + + // The best usable receiver, possibly the selected one, -1 if none + int bestCandidate(uint64_t hrt_now_us) const; + + // instance is better than other. The margin applies to the availability that decides between otherwise equal ones. + bool isBetterReceiver(int instance, int other, uint64_t hrt_now_us, float tiebreaker_availability_margin = 0.f) const; + + hrt_abstime switchHoldUs() const; + + bool hasPreferred() const { return (_preferred_instance >= 0) && (_preferred_instance < GNSS_MAX_RECEIVERS); } + + // Records the vehicle_gnss_s::SELECTION_* reason for switching to instance + int switchTo(int instance, uint8_t reason); + + // Switches away from the selected receiver because it failed. One that had already failed when the vehicle armed + // didn't fail in flight: it is still qualifying, like one that starts publishing after arming, and stays eligible. + int failOver(int instance, uint8_t reason); + + // No switch led to the selected receiver: it was the first one selected + static constexpr uint8_t REASON_INITIAL = UINT8_MAX; + + Sample _sample[GNSS_MAX_RECEIVERS] {}; + UpdateInterval _interval[GNSS_MAX_RECEIVERS] {}; + bool _updated[GNSS_MAX_RECEIVERS] {}; + bool _has_published[GNSS_MAX_RECEIVERS] {}; + bool _has_passed[GNSS_MAX_RECEIVERS] {}; + AlphaFilter _availability[GNSS_MAX_RECEIVERS]; + uint64_t _time_last_update_us{0}; + + uint64_t _time_last_usable_us[GNSS_MAX_RECEIVERS] {}; + bool _strict_qualified[GNSS_MAX_RECEIVERS] {}; ///< strict checks held for GNSS_REQ_TIME, and it hasn't failed since + + uint64_t _time_prev_us[GNSS_MAX_RECEIVERS] {}; ///< timestamp of the previous sample, to detect new data + + int _selected_instance{0}; + int _output_instance{-1}; ///< receiver of the last published sample, -1 before the first one + uint8_t _selection_count{0}; + uint8_t _switch_reason{REASON_INITIAL}; ///< why the last switch happened + uint8_t _selection_reason{vehicle_gnss_s::SELECTION_ONLY}; + int _preferred_instance{-1}; + + int _switch_candidate{-1}; ///< higher ranked receiver, waiting for the hold time + uint64_t _switch_candidate_since_us{0}; + bool _armed{false}; + uint8_t _rank_switches_while_armed{0}; + bool _failed_while_armed[GNSS_MAX_RECEIVERS] {}; ///< left because it failed, until disarmed + bool _working_while_armed[GNSS_MAX_RECEIVERS] {}; ///< not failed at some point since arming + + bool _selected_has_new_sample{false}; +}; diff --git a/src/modules/sensors/vehicle_gps_position/GnssSelectorTest.cpp b/src/modules/sensors/vehicle_gps_position/GnssSelectorTest.cpp new file mode 100644 index 00000000000..76f165d1bd1 --- /dev/null +++ b/src/modules/sensors/vehicle_gps_position/GnssSelectorTest.cpp @@ -0,0 +1,1374 @@ +/**************************************************************************** + * + * Copyright (C) 2021 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * Test code for the GPS receiver selection logic + * Run this test only using make tests TESTFILTER=GnssSelector + * + */ + +#include +#include + +#include "GnssSelector.hpp" + +class GnssSelectorTest : public ::testing::Test +{ +public: + sensor_gnss_s getDefaultGnssData(); + void runSeconds(float duration_s, GnssSelector &selector, sensor_gnss_s &gnss_data, int instance); + void runSeconds(float duration_s, GnssSelector &selector, sensor_gnss_s &gnss_data0, sensor_gnss_s &gnss_data1); + + // Runs both receivers at 10 Hz, except that gps0 only publishes every gps0_divider-th step + void runSecondsSlowGps0(float duration_s, GnssSelector &selector, sensor_gnss_s &gnss_data0, sensor_gnss_s &gnss_data1, + int gps0_divider); + + uint64_t _time_now_us{1000000}; + + // Results of each receiver's checks, which the sensors module passes along with every sample + bool _checks_passed[2] {true, true}; + bool _passed_strict[2] {true, true}; + + // The sample is within the strict thresholds, but they haven't held for GNSS_REQ_TIME since the last failure + bool _strict_requalifying[2] {false, false}; + + bool strictChecksPass(int instance) const { return _passed_strict[instance] || _strict_requalifying[instance]; } +}; + +sensor_gnss_s GnssSelectorTest::getDefaultGnssData() +{ + sensor_gnss_s gnss_data{}; + gnss_data.timestamp = _time_now_us - 10e3; + gnss_data.time_utc_usec = 0; + gnss_data.latitude = 47.0; + gnss_data.longitude = 9.0; + gnss_data.altitude_msl = 800.0; + gnss_data.altitude_ellipsoid = 800.0; + gnss_data.speed_accuracy = 0.2f; + gnss_data.course_accuracy = 0.5f; + gnss_data.eph = 0.7f; + gnss_data.epv = 1.2f; + gnss_data.hdop = 1.f; + gnss_data.vdop = 1.f; + gnss_data.noise = 20; + gnss_data.jamming_indicator = 40; + gnss_data.ground_speed = 1.f; + gnss_data.vel_north = 1.f; + gnss_data.vel_east = 1.f; + gnss_data.vel_down = 1.f; + gnss_data.course = 0.f; + gnss_data.timestamp_time_relative = 0; + gnss_data.fix_type = 4; + gnss_data.vel_ned_valid = true; + gnss_data.satellites_used = 8; + + return gnss_data; +} + +void GnssSelectorTest::runSeconds(float duration_s, GnssSelector &selector, sensor_gnss_s &gnss_data, int instance) +{ + const float dt = 0.1; + const uint64_t dt_us = static_cast(dt * 1e6f); + + for (int k = 0; k < lroundf(duration_s / dt); k++) { + selector.setGnssData(gnss_data, _checks_passed[instance], strictChecksPass(instance), _passed_strict[instance], instance); + selector.update(_time_now_us); + + _time_now_us += dt_us; + gnss_data.timestamp += dt_us; + } +} + +void GnssSelectorTest::runSeconds(float duration_s, GnssSelector &selector, sensor_gnss_s &gnss_data0, + sensor_gnss_s &gnss_data1) +{ + runSecondsSlowGps0(duration_s, selector, gnss_data0, gnss_data1, 1); +} + +void GnssSelectorTest::runSecondsSlowGps0(float duration_s, GnssSelector &selector, sensor_gnss_s &gnss_data0, + sensor_gnss_s &gnss_data1, int gps0_divider) +{ + const float dt = 0.1; + const uint64_t dt_us = static_cast(dt * 1e6f); + + for (int k = 0; k < lroundf(duration_s / dt); k++) { + if ((k % gps0_divider) == 0) { + selector.setGnssData(gnss_data0, _checks_passed[0], strictChecksPass(0), _passed_strict[0], 0); + } + + selector.setGnssData(gnss_data1, _checks_passed[1], strictChecksPass(1), _passed_strict[1], 1); + + selector.update(_time_now_us); + + _time_now_us += dt_us; + gnss_data0.timestamp += dt_us; + gnss_data1.timestamp += dt_us; + } +} + +TEST_F(GnssSelectorTest, noData) +{ + GnssSelector selector; + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_FALSE(selector.selectedHasNewSample()); + + selector.update(_time_now_us); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_FALSE(selector.selectedHasNewSample()); +} + +TEST_F(GnssSelectorTest, singleReceiver) +{ + GnssSelector selector; + + sensor_gnss_s gnss_data = getDefaultGnssData(); + + selector.setGnssData(gnss_data, true, true, true, 1); + selector.update(_time_now_us); + + _time_now_us += 200e3; + gnss_data.timestamp = _time_now_us - 10e3; + selector.setGnssData(gnss_data, true, true, true, 1); + selector.update(_time_now_us); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_TRUE(selector.selectedHasNewSample()); + + // BUT IF: a second update is called without data + selector.update(_time_now_us); + + // THEN: no new data should be available + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_FALSE(selector.selectedHasNewSample()); +} + +TEST_F(GnssSelectorTest, timeoutWithoutAnyPublisher) +{ + GnssSelector selector; + + // GIVEN: a single receiver that is usable + sensor_gnss_s gnss_data = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data, 0); + + EXPECT_FLOAT_EQ(selector.getAvailability(0), 1.f); + + // WHEN: it stops publishing, and the selector keeps updating without samples + for (int k = 0; k < 10; k++) { + _time_now_us += 300e3; + selector.update(_time_now_us); + } + + // THEN: its availability fell + EXPECT_FALSE(selector.selectedHasNewSample()); + EXPECT_LT(selector.getAvailability(0), 0.8f); + + // WHEN: it publishes again + _time_now_us += 100e3; + gnss_data.timestamp = _time_now_us - 10e3; + + runSeconds(0.1f, selector, gnss_data, 0); + + // THEN: its output resumes, and its availability keeps the outage + EXPECT_TRUE(selector.selectedHasNewSample()); + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_LT(selector.getAvailability(0), 0.8f); +} + +TEST_F(GnssSelectorTest, preferredWhateverTheOtherReports) +{ + GnssSelector selector; + + // GIVEN: gps0 preferred, only gps1 publishing + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(10.f, selector, gnss_data1, 1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_ONLY); + + // WHEN: gps0 starts publishing and passes its checks + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + gnss_data0.timestamp = gnss_data1.timestamp; + + runSeconds(0.2f, selector, gnss_data0, gnss_data1); + + // THEN: it is selected right away while disarmed + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps1 reports a better fix type and accuracy + gnss_data1.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FIXED; + gnss_data1.eph = 0.02f; + gnss_data1.epv = 0.03f; + + runSeconds(20.f, selector, gnss_data0, gnss_data1); + + // THEN: the preferred receiver is kept, also while armed + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 1); + + selector.setArmed(true); + runSeconds(30.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, timeoutSwitchesImmediately) +{ + GnssSelector selector; + + // GIVEN: gps0 preferred and selected + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + + // WHEN: gps0 stops publishing + runSeconds(1.5f, selector, gnss_data1, 1); + + // THEN: it is kept until it times out, without output + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_FALSE(selector.selectedHasNewSample()); + + runSeconds(1.f, selector, gnss_data1, 1); + + // THEN: the receiver that still publishes is selected + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_TIMEOUT); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps0 publishes again + gnss_data0.timestamp = gnss_data1.timestamp; + + runSeconds(0.2f, selector, gnss_data0, gnss_data1); + + // THEN: the selection returns at once, as the vehicle is disarmed + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + EXPECT_EQ(selector.getSelectionCount(), 2); +} + +TEST_F(GnssSelectorTest, timeoutToFailingReceiver) +{ + GnssSelector selector; + + // GIVEN: gps0 preferred, both receivers failing their checks + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + _checks_passed[0] = false; + _checks_passed[1] = false; + + runSeconds(10.f, selector, gnss_data0, gnss_data1); + + // THEN: the preferred receiver is kept + EXPECT_EQ(selector.getSelectedInstance(), 0); + + // WHEN: gps0 stops publishing + runSeconds(2.5f, selector, gnss_data1, 1); + + // THEN: the receiver that still publishes is selected, so that its samples keep coming + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_TRUE(selector.selectedHasNewSample()); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_TIMEOUT); +} + +TEST_F(GnssSelectorTest, continuousFailure) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 fails its checks + _checks_passed[0] = false; + + runSeconds(1.5f, selector, gnss_data0, gnss_data1); + + // THEN: it is left once it had no usable sample for 2 s + EXPECT_EQ(selector.getSelectedInstance(), 0); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_UNHEALTHY); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, continuousFailureWithFlakyStandby) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver, and gps1 that failed its checks for 5 s + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + _checks_passed[1] = false; + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + EXPECT_LT(selector.getAvailability(1), 0.7f); + + // WHEN: gps1 recovers as gps0 fails its checks + _checks_passed[0] = false; + _checks_passed[1] = true; + + runSeconds(2.5f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 replaces it after the same 2 s, although it was recently less available than gps0 + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_UNHEALTHY); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, noReturnToFailedReceiverOnSingleSample) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle without a preferred receiver that left gps0 for gps1, which failed recently itself + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + _checks_passed[1] = false; + runSeconds(5.f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = false; + _checks_passed[1] = true; + runSeconds(2.5f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: gps0 passes a single sample every second, still more available than gps1 + for (int cycle = 0; cycle < 10; cycle++) { + _checks_passed[0] = true; + runSeconds(0.1f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = false; + runSeconds(0.9f, selector, gnss_data0, gnss_data1); + } + + // THEN: gps1 is kept + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, intermittentFailure) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 fails one sample every 1.5 s, which makes it unusable for 1 s each time: it never fails continuously + // for long, but only a third of its samples can be fused + for (int cycle = 0; cycle < 10; cycle++) { + _checks_passed[0] = false; + runSeconds(1.f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = true; + runSeconds(0.5f, selector, gnss_data0, gnss_data1); + } + + // THEN: the selection moves to the receiver whose samples can all be fused + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_UNHEALTHY); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, occasionalFailureDoesNotSwitch) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 fails one sample every 10 s, unusable 10% of the time. Each failure restarts GNSS_REQ_TIME, so its strict + // checks never hold for it again. + for (int cycle = 0; cycle < 6; cycle++) { + _checks_passed[0] = false; + _passed_strict[0] = false; + _strict_requalifying[0] = false; + runSeconds(1.f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = true; + _strict_requalifying[0] = true; + runSeconds(9.f, selector, gnss_data0, gnss_data1); + } + + // THEN: it is kept. A switch would reset the EKF2 position. + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, lowerRateLearned) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver, both at 10 Hz + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 drops to 1 Hz for good, its samples still passing their checks + runSecondsSlowGps0(30.f, selector, gnss_data0, gnss_data1, 10); + + // THEN: it is kept, as only its first sample at 1 Hz is late + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); + EXPECT_GT(selector.getAvailability(0), 0.9f); +} + +TEST_F(GnssSelectorTest, rateCollapse) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver, both at 10 Hz + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 drops to 0.7 Hz, its samples still passing their checks + runSecondsSlowGps0(3.f, selector, gnss_data0, gnss_data1, 14); + + // THEN: it has failed, as it had no usable sample for 2 s before its rate was learned + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_UNHEALTHY); +} + +TEST_F(GnssSelectorTest, halfRateStillUsable) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver, both at 10 Hz + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 drops to 5 Hz, or has a single 1 s gap + runSecondsSlowGps0(20.f, selector, gnss_data0, gnss_data1, 2); + runSecondsSlowGps0(1.f, selector, gnss_data0, gnss_data1, 20); + runSeconds(10.f, selector, gnss_data0, gnss_data1); + + // THEN: it is kept + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, bothFailingKeepsSelection) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + + // WHEN: both fail their checks + _checks_passed[0] = false; + _checks_passed[1] = false; + + runSeconds(20.f, selector, gnss_data0, gnss_data1); + + // THEN: neither is usable, so the selection stays + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, noReturnToFailedPreferred) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle that failed over from gps0, the preferred receiver + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + _checks_passed[0] = false; + runSeconds(3.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: gps0 passes its checks again + _checks_passed[0] = true; + + runSeconds(30.f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 is kept, as gps0 is likely to fail again + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps1 fails its checks + _checks_passed[1] = false; + + runSeconds(2.5f, selector, gnss_data0, gnss_data1); + + // THEN: the selection returns to gps0 + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_UNHEALTHY); + EXPECT_EQ(selector.getSelectionCount(), 2); +} + +TEST_F(GnssSelectorTest, preferredStartingWhileArmed) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps1, as gps0, the preferred receiver, didn't publish yet + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data1, 1); + selector.setArmed(true); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: gps0 starts publishing and passes its checks + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + gnss_data0.timestamp = gnss_data1.timestamp; + + runSeconds(9.5f, selector, gnss_data0, gnss_data1); + + // THEN: the selection moves to it once it has been usable for the hold time, as it never failed + EXPECT_EQ(selector.getSelectedInstance(), 1); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, preferredLeftWhenFailingStrict) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 passes only the relaxed checks for less than the hold time, a few times + for (int cycle = 0; cycle < 5; cycle++) { + _passed_strict[0] = false; + runSeconds(9.f, selector, gnss_data0, gnss_data1); + _passed_strict[0] = true; + runSeconds(0.2f, selector, gnss_data0, gnss_data1); + } + + // THEN: it is kept + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); + + // WHEN: it fails the strict checks through the hold time, while gps1 passes them + _passed_strict[0] = false; + runSeconds(9.5f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + // THEN: the selection moves to gps1 + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_STRICT); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, preferredReturnsOncePassingStrict) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle that left gps0, the preferred receiver, as it failed the strict checks + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + _passed_strict[0] = false; + runSeconds(10.5f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: gps0 passes them again, for example after the corrections came back + _passed_strict[0] = true; + runSeconds(19.5f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + // THEN: the selection returns to it, as it never failed, after twice the hold time + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + EXPECT_EQ(selector.getSelectionCount(), 2); +} + +TEST_F(GnssSelectorTest, preferredNotRetakenWhileFailingStrict) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle that left gps0, the preferred receiver, as it failed the strict checks + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + _passed_strict[0] = false; + runSeconds(10.5f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: gps1 fails them too + _passed_strict[1] = false; + runSeconds(60.f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 is kept, as moving back to gps0 gains nothing + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, rankSwitchHoldDoubles) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 passes the strict checks for 15 s, then fails them for 15 s, for 2 minutes + for (int cycle = 0; cycle < 4; cycle++) { + _passed_strict[0] = false; + runSeconds(15.f, selector, gnss_data0, gnss_data1); + _passed_strict[0] = true; + runSeconds(15.f, selector, gnss_data0, gnss_data1); + } + + // THEN: the selection left it once; with the 10 s hold it would have switched twice per cycle + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: it passes them through the doubled hold + runSeconds(10.f, selector, gnss_data0, gnss_data1); + + // THEN: the selection returns to it + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 2); + + // WHEN: the vehicle disarms and arms again + selector.setArmed(false); + runSeconds(1.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // THEN: the hold is back to 10 s + _passed_strict[0] = false; + runSeconds(10.5f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 3); +} + +TEST_F(GnssSelectorTest, preferredReturnAfterDisarm) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle that failed over from gps0, the preferred receiver, which passes its checks again + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + _checks_passed[0] = false; + runSeconds(5.f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = true; + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: the vehicle disarms while gps0 is still clearly less available + selector.setArmed(false); + + runSeconds(0.2f, selector, gnss_data0, gnss_data1); + + // THEN: gps0 is selected at once + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + EXPECT_EQ(selector.getSelectionCount(), 2); +} + +TEST_F(GnssSelectorTest, preferredSelectedWhileDisarmed) +{ + GnssSelector selector; + + // GIVEN: gps0 preferred, only gps1 publishing + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(1.f, selector, gnss_data1, 1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_ONLY); + + // WHEN: gps0 publishes, but hasn't passed its checks yet + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + gnss_data0.timestamp = gnss_data1.timestamp; + _checks_passed[0] = false; + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + // THEN: it is selected, so that the vehicle doesn't take off on gps1 + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: the vehicle arms anyway + selector.setArmed(true); + + runSeconds(0.2f, selector, gnss_data0, gnss_data1); + + // THEN: gps0 has failed, and gps1 replaces it + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_UNHEALTHY); + EXPECT_EQ(selector.getSelectionCount(), 2); + +} + +TEST_F(GnssSelectorTest, preferenceRemoved) +{ + GnssSelector selector; + + // GIVEN: the selection moved to gps1, the preferred receiver, once it published + selector.setPreferredInstance(1); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(1.f, selector, gnss_data0, 0); + gnss_data1.timestamp = gnss_data0.timestamp; + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + + // WHEN: no receiver is preferred anymore + selector.setPreferredInstance(-1); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 is kept, as the other one is no more accurate + // No update on SelectionReason because no switch happening + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, rankedIgnoresFloatSatellitesAndRate) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps1 selected + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(1.f, selector, gnss_data1, 1); + gnss_data0.timestamp = gnss_data1.timestamp; + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: gps0 reports an RTK float solution, more satellites and a better accuracy, and gps1 publishes at twice + // gps0's rate + gnss_data0.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FLOAT; + gnss_data0.satellites_used = gnss_data1.satellites_used + 10; + gnss_data0.eph = 0.1f; + gnss_data0.epv = 0.2f; + + runSecondsSlowGps0(20.f, selector, gnss_data0, gnss_data1, 2); + + // THEN: gps1 is kept, none of them ranks a receiver higher + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_RANKED); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, rankedSwitchOnFailure) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_RANKED); + + // WHEN: gps0 fails its checks + _checks_passed[0] = false; + + runSeconds(3.f, selector, gnss_data0, gnss_data1); + + // THEN: the receiver that passes them is selected + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_UNHEALTHY); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps0 passes them again + _checks_passed[0] = true; + + runSeconds(30.f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 is kept, as gps0 doesn't rank higher + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, rankedStrict) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected, on an armed vehicle + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 no longer passes the strict checks, which gps1 does + _passed_strict[0] = false; + + runSeconds(9.5f, selector, gnss_data0, gnss_data1); + + // THEN: the switch waits for the hold time + EXPECT_EQ(selector.getSelectedInstance(), 0); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_STRICT); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps0 passes them again + _passed_strict[0] = true; + + runSeconds(20.f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 is kept, as gps0 doesn't rank higher + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps1 no longer passes them + _passed_strict[1] = false; + + runSeconds(19.5f, selector, gnss_data0, gnss_data1); + + // THEN: the selection moves back to gps0, which ranked lower but never failed, after twice the hold time + EXPECT_EQ(selector.getSelectedInstance(), 1); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_STRICT); + EXPECT_EQ(selector.getSelectionCount(), 2); +} + +TEST_F(GnssSelectorTest, rankedHoldRestarts) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected, on an armed vehicle, and gps0 failing the strict + // checks + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + _passed_strict[0] = false; + + // WHEN: gps1 passes them for 9 s at a time + for (int cycle = 0; cycle < 5; cycle++) { + _passed_strict[1] = true; + runSeconds(9.f, selector, gnss_data0, gnss_data1); + _passed_strict[1] = false; + runSeconds(0.2f, selector, gnss_data0, gnss_data1); + } + + // THEN: gps0 is kept + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, rankedRtkFixed) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected, on an armed vehicle + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps1 gets an RTK fixed solution + gnss_data1.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FIXED; + + runSeconds(10.5f, selector, gnss_data0, gnss_data1); + + // THEN: it is selected after the hold time + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_RTK_FIXED); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps0 gets one too, reporting a better accuracy + gnss_data0.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FIXED; + gnss_data0.eph = 0.01f; + gnss_data0.epv = 0.015f; + + runSeconds(20.f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 is kept + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: gps1 drops to RTK float + gnss_data1.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FLOAT; + + runSeconds(20.5f, selector, gnss_data0, gnss_data1); + + // THEN: the RTK fixed receiver is selected, after twice the hold time + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_RTK_FIXED); + EXPECT_EQ(selector.getSelectionCount(), 2); +} + +TEST_F(GnssSelectorTest, higherRankedWaitsForAvailabilityRecovery) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected, and gps1 recently failing its checks + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + _checks_passed[1] = false; + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + ASSERT_EQ(selector.getSelectedInstance(), 0); + ASSERT_GT(selector.getAvailability(0), selector.getAvailability(1) + GnssSelector::AVAILABILITY_MARGIN); + + // WHEN: gps1 recovers with an RTK fixed solution for longer than the disarmed switch hold + _checks_passed[1] = true; + gnss_data1.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FIXED; + runSeconds(2.5f, selector, gnss_data0, gnss_data1); + + // THEN: gps0 is kept, as gps1 still has substantially worse availability despite its higher rank + ASSERT_GT(selector.getAvailability(0), selector.getAvailability(1) + GnssSelector::AVAILABILITY_MARGIN); + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); + + // WHEN: gps1 stays usable long enough to recover its availability and complete the switch hold + runSeconds(20.f, selector, gnss_data0, gnss_data1); + + // THEN: its higher rank wins + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_RTK_FIXED); + EXPECT_EQ(selector.getSelectionCount(), 1); +} + +TEST_F(GnssSelectorTest, rankedRtkFixedFlickerDoesNotSwitch) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected, on an armed vehicle + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: their RTK fixed solutions come and go in turn every second + for (int cycle = 0; cycle < 60; cycle++) { + gnss_data0.fix_type = (cycle % 2) ? sensor_gnss_s::FIX_TYPE_RTK_FIXED : sensor_gnss_s::FIX_TYPE_RTK_FLOAT; + gnss_data1.fix_type = (cycle % 2) ? sensor_gnss_s::FIX_TYPE_RTK_FLOAT : sensor_gnss_s::FIX_TYPE_RTK_FIXED; + runSeconds(1.f, selector, gnss_data0, gnss_data1); + } + + // THEN: the selection stays + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, rankedRtkFixedNeedsStrict) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + // WHEN: gps1 reports an RTK fixed solution, but fails the strict checks + gnss_data1.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FIXED; + _passed_strict[1] = false; + + runSeconds(20.f, selector, gnss_data0, gnss_data1); + + // THEN: gps0 is kept + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, rankedNoReturnToFailedReceiver) +{ + GnssSelector selector; + + // GIVEN: two receivers without a preferred one, gps0 selected with an RTK fixed solution, on an armed vehicle + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + gnss_data0.fix_type = sensor_gnss_s::FIX_TYPE_RTK_FIXED; + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + + // WHEN: gps0 fails its checks, then recovers + _checks_passed[0] = false; + runSeconds(3.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + + _checks_passed[0] = true; + runSeconds(30.f, selector, gnss_data0, gnss_data1); + + // THEN: gps1 is kept, although gps0 ranks higher + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionCount(), 1); + + // WHEN: the vehicle disarms + selector.setArmed(false); + + runSeconds(1.5f, selector, gnss_data0, gnss_data1); + + // THEN: gps0 ranks again, with the shorter hold time + EXPECT_EQ(selector.getSelectedInstance(), 1); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_RTK_FIXED); + EXPECT_EQ(selector.getSelectionCount(), 2); +} + +TEST_F(GnssSelectorTest, noOutputWithoutNewData) +{ + GnssSelector selector; + + // GIVEN: two receivers, gps1 selected as it published first + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + selector.setGnssData(gnss_data1, true, true, true, 1); + selector.update(_time_now_us); + + _time_now_us += 100e3; + gnss_data0.timestamp = _time_now_us - 10e3; + gnss_data1.timestamp = _time_now_us - 10e3; + selector.setGnssData(gnss_data0, true, true, true, 0); + selector.setGnssData(gnss_data1, true, true, true, 1); + selector.update(_time_now_us); + + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_TRUE(selector.selectedHasNewSample()); + + // WHEN: an update runs without new data from either receiver + selector.update(_time_now_us); + + // THEN: no output is reported. The updated flag of the receiver that isn't selected must be cleared as well + EXPECT_FALSE(selector.selectedHasNewSample()); +} + +TEST_F(GnssSelectorTest, availability) +{ + GnssSelector selector; + + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + // GIVEN: gps1 hasn't passed its checks yet + _checks_passed[1] = false; + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + + // THEN: a receiver starts fully available once it first passes, and has no availability before + EXPECT_FLOAT_EQ(selector.getAvailability(0), 1.f); + EXPECT_FLOAT_EQ(selector.getAvailability(1), 0.f); + + // WHEN: gps0 fails its checks for one time constant + _checks_passed[0] = false; + + runSeconds(10.f, selector, gnss_data0, gnss_data1); + + // THEN: its availability decays like a first order filter + EXPECT_NEAR(selector.getAvailability(0), expf(-1.f), 0.01f); +} + +TEST_F(GnssSelectorTest, relaxedFailureDoesNotSwitch) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle using gps0, the preferred receiver + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + + // WHEN: gps0 fails its checks for a second, which restarts GNSS_REQ_TIME for its strict checks, as long as the hold + _checks_passed[0] = false; + _passed_strict[0] = false; + runSeconds(1.f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = true; + _strict_requalifying[0] = true; + runSeconds(10.f, selector, gnss_data0, gnss_data1); + _passed_strict[0] = true; + _strict_requalifying[0] = false; + runSeconds(30.f, selector, gnss_data0, gnss_data1); + + // THEN: it keeps the strict rank, as it didn't fail, and stays selected + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, strictRankRequalifiesAfterFailure) +{ + GnssSelector selector; + + // GIVEN: an armed vehicle without a preferred receiver on gps0, which fails the strict checks but stays usable + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(5.f, selector, gnss_data0, gnss_data1); + selector.setArmed(true); + EXPECT_EQ(selector.getSelectedInstance(), 0); + + _passed_strict[0] = false; + + // WHEN: gps1 fails for 3 s, then passes its checks again, but its strict checks haven't held for GNSS_REQ_TIME + _checks_passed[1] = false; + _passed_strict[1] = false; + runSeconds(3.f, selector, gnss_data0, gnss_data1); + _checks_passed[1] = true; + _strict_requalifying[1] = true; + runSeconds(20.f, selector, gnss_data0, gnss_data1); + + // THEN: it doesn't rank higher until they have + EXPECT_EQ(selector.getSelectedInstance(), 0); + + _passed_strict[1] = true; + _strict_requalifying[1] = false; + runSeconds(9.5f, selector, gnss_data0, gnss_data1); + EXPECT_EQ(selector.getSelectedInstance(), 0); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + EXPECT_EQ(selector.getSelectedInstance(), 1); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_STRICT); +} + +TEST_F(GnssSelectorTest, lateSampleDoesNotFail) +{ + GnssSelector selector; + + // GIVEN: a receiver publishing at 10 Hz + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + runSeconds(5.f, selector, gnss_data0, 0); + + // WHEN: one sample comes 400 ms after the previous one + _time_now_us += 250_ms; + selector.update(_time_now_us); + + // THEN: it is unusable during the gap and for the late sample, but hasn't failed + EXPECT_FALSE(selector.isUsable(0, _time_now_us)); + EXPECT_FALSE(selector.hasFailed(0, _time_now_us)); + + gnss_data0.timestamp += 300_ms; + _time_now_us += 50_ms; + selector.setGnssData(gnss_data0, true, true, true, 0); + selector.update(_time_now_us); + + EXPECT_FALSE(selector.isUsable(0, _time_now_us)); + EXPECT_FALSE(selector.hasFailed(0, _time_now_us)); + + gnss_data0.timestamp += 100_ms; + _time_now_us += 100_ms; + runSeconds(0.2f, selector, gnss_data0, 0); + + EXPECT_TRUE(selector.isUsable(0, _time_now_us - 100_ms)); +} + +TEST_F(GnssSelectorTest, groundOutageDoesNotCountInFlight) +{ + GnssSelector selector; + + // GIVEN: gps0, the preferred receiver, was unusable for a minute on the ground and passes its checks again + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + runSeconds(15.f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = false; + _passed_strict[0] = false; + runSeconds(60.f, selector, gnss_data0, gnss_data1); + _checks_passed[0] = true; + _passed_strict[0] = true; + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + // WHEN: the vehicle arms right after + selector.setArmed(true); + runSeconds(60.f, selector, gnss_data0, gnss_data1); + + // THEN: gps0 stays selected, as availability counts from arming + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionCount(), 0); +} + +TEST_F(GnssSelectorTest, preferredQualifyingAtArmingIsTakenLater) +{ + GnssSelector selector; + + // GIVEN: gps0, the preferred receiver, publishes but hasn't passed its checks yet when the vehicle arms + selector.setPreferredInstance(0); + + sensor_gnss_s gnss_data0 = getDefaultGnssData(); + sensor_gnss_s gnss_data1 = getDefaultGnssData(); + + _checks_passed[0] = false; + _passed_strict[0] = false; + runSeconds(5.f, selector, gnss_data0, gnss_data1); + EXPECT_EQ(selector.getSelectedInstance(), 0); + + selector.setArmed(true); + runSeconds(0.1f, selector, gnss_data0, gnss_data1); + + // THEN: the selection moves to gps1 at once + EXPECT_EQ(selector.getSelectedInstance(), 1); + + // WHEN: gps0 passes its checks + _checks_passed[0] = true; + _passed_strict[0] = true; + runSeconds(9.5f, selector, gnss_data0, gnss_data1); + + // THEN: it is taken once it has been usable for the hold time, as it never failed in flight + EXPECT_EQ(selector.getSelectedInstance(), 1); + + runSeconds(1.f, selector, gnss_data0, gnss_data1); + + EXPECT_EQ(selector.getSelectedInstance(), 0); + EXPECT_EQ(selector.getSelectionReason(), vehicle_gnss_s::SELECTION_PREFERRED); +} diff --git a/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.cpp b/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.cpp index e17b35a3e75..4e218ef511c 100644 --- a/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.cpp +++ b/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.cpp @@ -156,12 +156,6 @@ void VehicleGPSPosition::ParametersUpdate(bool force) checks.setParams(checks_params); } - const int gnss_prime = _param_sens_gnss_prime.get(); - - if (math::isInRange(gnss_prime, -1, 1)) { - _gps_blending.setPrimaryInstance(gnss_prime); - } - _gnss_param_slots[0] = { static_cast(_param_sens_gnss0_id.get()), {_param_sens_gnss0_offx.get(), _param_sens_gnss0_offy.get(), _param_sens_gnss0_offz.get()}, @@ -191,6 +185,11 @@ void VehicleGPSPosition::ParametersUpdate(bool force) _gnss_param_slots[1].heading_enabled = (_param_sens_gnss1_hdg.get() != static_cast (gnss_heading::BaselineType::Disabled)); + // The moving base is the receiver in the other slot of a moving base rover + const bool rover0 = (_param_sens_gnss0_hdg.get() == static_cast(gnss_heading::BaselineType::MovingBase)); + const bool rover1 = (_param_sens_gnss1_hdg.get() == static_cast(gnss_heading::BaselineType::MovingBase)); + _moving_base_slot = (rover0 != rover1) ? (rover0 ? 1 : 0) : -1; + #endif // CONFIG_SENSORS_VEHICLE_GNSS_HEADING } } @@ -210,34 +209,26 @@ void VehicleGPSPosition::Run() // Check all GPS instance bool any_gnss_updated = false; - const int32_t gnss_prime = _param_sens_gnss_prime.get(); for (uint8_t i = 0; i < GPS_MAX_RECEIVERS; i++) { - sensor_gnss_s gnss_data; + sensor_gnss_s &gnss_data = _latest_sample[i]; if (_sensor_gnss_sub[i].update(&gnss_data)) { any_gnss_updated = true; const GpsParamSlot *slot = findParamSlot(gnss_data.device_id, i); - const matrix::Vector3f antenna_offset = slot ? slot->offset : matrix::Vector3f{}; const hrt_abstime delay_us = slot ? slot->delay_us : kDefaultDelay; gnss_data.timestamp_sample = resolveSampleTimestamp(gnss_data.timestamp_sample, gnss_data.timestamp, delay_us); - _gnss_checks[i].run(toChecksSample(gnss_data), _armed, _in_air, _at_rest); - _receiver_device_id[i] = gnss_data.device_id; - _receiver_timestamp[i] = gnss_data.timestamp; + const bool checks_passed = _gnss_checks[i].run(toChecksSample(gnss_data), _armed, _in_air, _at_rest); if (_first_publication[i] == 0) { _first_publication[i] = ++_receivers_published; } - _gps_blending.setAntennaOffset(antenna_offset, i); - _gps_blending.setGnssData(gnss_data, i); - - if (nodeIdMatches(gnss_prime, gnss_data.device_id)) { - _gps_blending.setPrimaryInstance(i); - } + _gnss_selector.setGnssData(gnss_data, checks_passed, _gnss_checks[i].getStrictFailFlags() == 0, + _gnss_checks[i].passedStrict(), i); if (!_sensor_gnss_sub[i].registered()) { _sensor_gnss_sub[i].registerCallback(); @@ -247,14 +238,20 @@ void VehicleGPSPosition::Run() if (any_gnss_updated) { _preferred_instance = resolvePreferredInstance(); - _gps_blending.update(hrt_absolute_time()); + _gnss_selector.setPreferredInstance(_preferred_instance); + _gnss_selector.update(hrt_absolute_time()); + + if (_gnss_selector.selectedHasNewSample()) { + const int selected = _gnss_selector.getSelectedInstance(); - if (_gps_blending.isNewOutputDataAvailable()) { vehicle_gnss_s gnss_output{}; - gnss_output.receiver = _gps_blending.getOutputGnssData(); + gnss_output.receiver = _latest_sample[selected]; - const matrix::Vector3f &out_offset = _gps_blending.getOutputAntennaOffset(); - out_offset.copyTo(gnss_output.antenna_offset); + const GpsParamSlot *slot = findParamSlot(gnss_output.receiver.device_id, selected); + + if (slot) { + slot->offset.copyTo(gnss_output.antenna_offset); + } const uint64_t pps_timestamp = _pps_time_sync.correct_gnss_timestamp(gnss_output.receiver.timestamp, gnss_output.receiver.time_utc_usec); @@ -264,13 +261,16 @@ void VehicleGPSPosition::Run() gnss_output.receiver.timestamp_sample = pps_timestamp; } - gnss_output.selected_instance = _gps_blending.getSelectedGps(); - gnss_output.selection_count = _gps_blending.getSelectionCount(); + gnss_output.selected_instance = selected; + gnss_output.selection_count = _gnss_selector.getSelectionCount(); + gnss_output.selection_reason = _gnss_selector.getSelectionReason(); // The selected receiver's checker ran on this sample - const GnssChecks &checks = _gnss_checks[_gps_blending.getSelectedGps()]; + const GnssChecks &checks = _gnss_checks[selected]; gnss_output.usable = checks.passed(); - gnss_output.failed_checks = checks.getFailFlags() & checks.getEnabledChecks(); + gnss_output.strict = checks.strict(); + gnss_output.failed_strict_checks = checks.getStrictFailFlags(); + gnss_output.failed_relaxed_checks = checks.getRelaxedFailFlags(); gnss_output.timestamp_sample = gnss_output.receiver.timestamp_sample; gnss_output.timestamp = hrt_absolute_time(); @@ -280,6 +280,11 @@ void VehicleGPSPosition::Run() } PublishStatus(); + + } else if (_receivers_published > 0) { + // A receiver that stopped publishing still has to time out and lose availability when no other one publishes + _gnss_selector.update(hrt_absolute_time()); + PublishStatus(); } #if defined(CONFIG_SENSORS_VEHICLE_GNSS_HEADING) @@ -303,8 +308,8 @@ void VehicleGPSPosition::UpdateGnssHeading() // sensor_gnss_relative instances are numbered by advertise order, not by receiver, so the receiver's // sensor_gnss instance is looked up by device_id for the parameter slot and the receiver state. - sensor_gnss_s receiver{}; - const GpsParamSlot *slot = findParamSlot(gnss_rel.device_id, findGnssInstance(gnss_rel.device_id, receiver)); + const int instance = findGnssInstance(gnss_rel.device_id); + const GpsParamSlot *slot = findParamSlot(gnss_rel.device_id, instance); HeadingSample sample{}; sample.timestamp_sample = resolveSampleTimestamp(gnss_rel.timestamp_sample, gnss_rel.timestamp, @@ -320,8 +325,12 @@ void VehicleGPSPosition::UpdateGnssHeading() sample.heading_accuracy = gnss_rel.heading_accuracy; sample.baseline_length = gnss_rel.position_length; sample.baseline_down = gnss_rel.position[2]; - sample.jamming_state = receiver.jamming_state; - sample.spoofing_state = receiver.spoofing_state; + + if (instance >= 0) { + sample.jamming_state = _latest_sample[instance].jamming_state; + sample.spoofing_state = _latest_sample[instance].spoofing_state; + } + handleHeadingSample(sample, slot); } } @@ -434,6 +443,7 @@ void VehicleGPSPosition::UpdateVehicleState() if (_vehicle_status_sub.update(&vehicle_status)) { _armed = (vehicle_status.arming_state == vehicle_status_s::ARMING_STATE_ARMED); + _gnss_selector.setArmed(_armed); } vehicle_land_detected_s vehicle_land_detected; @@ -474,11 +484,13 @@ void VehicleGPSPosition::PublishStatus() for (int i = 0; i < GPS_MAX_RECEIVERS; i++) { const GnssChecks &checks = _gnss_checks[i]; - const bool publishing = (_receiver_timestamp[i] != 0) && (now < _receiver_timestamp[i] + GpsBlending::GPS_TIMEOUT_US); + const sensor_gnss_s &sample = _latest_sample[i]; - status.device_ids[i] = _receiver_device_id[i]; - status.healthy[i] = publishing && checks.passed(); - status.failed_checks[i] = checks.getFailFlags() & checks.getEnabledChecks(); + status.device_ids[i] = sample.device_id; + status.healthy[i] = !_gnss_selector.hasFailed(i, now); + status.availability[i] = _gnss_selector.getAvailability(i); + status.failed_strict_checks[i] = checks.getStrictFailFlags(); + status.failed_relaxed_checks[i] = checks.getRelaxedFailFlags(); status.strict[i] = checks.strict(); status.drift_rate_horizontal[i] = checks.horizontal_position_drift_rate_m_s(); status.drift_rate_vertical[i] = checks.vertical_position_drift_rate_m_s(); @@ -498,17 +510,40 @@ int VehicleGPSPosition::resolvePreferredInstance() const } for (int i = 0; i < GPS_MAX_RECEIVERS; i++) { - if ((_receiver_device_id[i] != 0) && nodeIdMatches(gnss_prime, _receiver_device_id[i])) { + if ((_latest_sample[i].device_id != 0) && nodeIdMatches(gnss_prime, _latest_sample[i].device_id)) { return i; } } +#if defined(CONFIG_SENSORS_VEHICLE_GNSS_HEADING) + + // Without a preferred receiver, the moving base of a moving base pair is preferred: the rover reports the quality of + // its relative solution, and its position depends on the corrections the moving base sends it + if ((gnss_prime == -1) && (_moving_base_slot >= 0)) { + for (int i = 0; i < GPS_MAX_RECEIVERS; i++) { + if ((_latest_sample[i].timestamp != 0) + && (findParamSlot(_latest_sample[i].device_id, i) == &_gnss_param_slots[_moving_base_slot])) { + return i; + } + } + } + +#endif // CONFIG_SENSORS_VEHICLE_GNSS_HEADING + return -1; } bool VehicleGPSPosition::hasConfiguredPreference() const { - return _param_sens_gnss_prime.get() != -1; + if (_param_sens_gnss_prime.get() != -1) { + return true; + } + +#if defined(CONFIG_SENSORS_VEHICLE_GNSS_HEADING) + return _moving_base_slot >= 0; +#else + return false; +#endif // CONFIG_SENSORS_VEHICLE_GNSS_HEADING } const VehicleGPSPosition::GpsParamSlot *VehicleGPSPosition::findParamSlot(uint32_t device_id, int instance) const @@ -529,15 +564,14 @@ const VehicleGPSPosition::GpsParamSlot *VehicleGPSPosition::findParamSlot(uint32 } #if defined(CONFIG_SENSORS_VEHICLE_GNSS_HEADING) -int VehicleGPSPosition::findGnssInstance(uint32_t device_id, sensor_gnss_s &gnss_data) +int VehicleGPSPosition::findGnssInstance(uint32_t device_id) const { for (int i = 0; i < GPS_MAX_RECEIVERS; i++) { - if (_sensor_gnss_sub[i].copy(&gnss_data) && (gnss_data.device_id == device_id)) { + if ((_latest_sample[i].timestamp != 0) && (_latest_sample[i].device_id == device_id)) { return i; } } - gnss_data = {}; return -1; } #endif // CONFIG_SENSORS_VEHICLE_GNSS_HEADING @@ -556,7 +590,7 @@ uint64_t VehicleGPSPosition::resolveSampleTimestamp(uint64_t driver_timestamp_sa void VehicleGPSPosition::PrintStatus() { - PX4_INFO_RAW("[vehicle_gps_position] selected GPS: %d\n", _gps_blending.getSelectedGps()); + PX4_INFO_RAW("[vehicle_gps_position] selected GPS: %d\n", _gnss_selector.getSelectedInstance()); } }; // namespace sensors diff --git a/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.hpp b/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.hpp index 83fb25ac0c2..81364243155 100644 --- a/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.hpp +++ b/src/modules/sensors/vehicle_gps_position/VehicleGPSPosition.hpp @@ -55,7 +55,7 @@ #include #include "GnssHeadingBaseline.hpp" -#include "gps_blending.hpp" +#include "GnssSelector.hpp" #include "PpsTimeSync.hpp" using namespace time_literals; @@ -83,8 +83,8 @@ private: // define max number of GPS receivers supported static constexpr int GPS_MAX_RECEIVERS = 2; - static_assert(GPS_MAX_RECEIVERS == GpsBlending::GPS_MAX_RECEIVERS_BLEND, - "GPS_MAX_RECEIVERS must match to GPS_MAX_RECEIVERS_BLEND"); + static_assert(GPS_MAX_RECEIVERS == GnssSelector::GNSS_MAX_RECEIVERS, + "GPS_MAX_RECEIVERS must match to GNSS_MAX_RECEIVERS"); static constexpr hrt_abstime kDefaultDelay{110_ms}; // matches SENS_GNSS*_DELAY default static constexpr hrt_abstime kHeadingSourceTimeout{3_s}; @@ -102,10 +102,10 @@ private: // SENS_GNSSn_* slot for a receiver, by device_id or (when no IDs are configured) by sensor_gnss instance const GpsParamSlot *findParamSlot(uint32_t device_id, int instance) const; - // sensor_gnss instance of the receiver SENS_GNSS_PRIME designates, -1 for none or not yet published + // sensor_gnss instance of the receiver SENS_GNSS_PRIME designates, or of the moving base with -1; -1 for none int resolvePreferredInstance() const; - // SENS_GNSS_PRIME names a receiver, whether or not it has published yet + // SENS_GNSS_PRIME names a receiver, or a moving base pair is configured, whether or not it has published yet bool hasConfiguredPreference() const; #if defined(CONFIG_SENSORS_VEHICLE_GNSS_HEADING) @@ -123,8 +123,8 @@ private: void UpdateGnssHeading(); void handleHeadingSample(const HeadingSample &sample, const GpsParamSlot *slot); - // sensor_gnss instance publishing this device_id, or -1, with its latest sample in gnss_data (zeroed when not found) - int findGnssInstance(uint32_t device_id, sensor_gnss_s &gnss_data); + // sensor_gnss instance publishing this device_id, or -1 + int findGnssInstance(uint32_t device_id) const; #endif // CONFIG_SENSORS_VEHICLE_GNSS_HEADING static uint64_t resolveSampleTimestamp(uint64_t driver_timestamp_sample, uint64_t driver_timestamp, @@ -161,21 +161,23 @@ private: bool _heading_unconfigured_reported{false}; bool _heading_no_baseline_reported{false}; + + int _moving_base_slot{-1}; ///< SENS_GNSSn_* slot of the moving base of a moving base pair, or -1 #endif // CONFIG_SENSORS_VEHICLE_GNSS_HEADING perf_counter_t _cycle_perf{perf_alloc(PC_ELAPSED, MODULE_NAME": cycle")}; - GpsBlending _gps_blending; + GnssSelector _gnss_selector; GnssChecks _gnss_checks[GPS_MAX_RECEIVERS] {}; - uint32_t _receiver_device_id[GPS_MAX_RECEIVERS] {}; - hrt_abstime _receiver_timestamp[GPS_MAX_RECEIVERS] {}; + sensor_gnss_s _latest_sample[GPS_MAX_RECEIVERS] {}; ///< timestamp_sample corrected, timestamp 0 until it publishes uint32_t _selected_device_id{0}; int8_t _preferred_instance{-1}; uint8_t _first_publication[GPS_MAX_RECEIVERS] {}; ///< 1 for the first receiver to publish, 2 for the next, 0 before uint8_t _receivers_published{0}; - // The checks run the strict thresholds while disarmed on the ground and the drift checks only at rest + // The checks run the strict thresholds while disarmed on the ground and the drift checks only at rest; while + // disarmed, the selection stays on the preferred receiver bool _armed{false}; bool _in_air{false}; bool _at_rest{false}; diff --git a/src/modules/sensors/vehicle_gps_position/gps_blending.cpp b/src/modules/sensors/vehicle_gps_position/gps_blending.cpp deleted file mode 100644 index b0a7904910d..00000000000 --- a/src/modules/sensors/vehicle_gps_position/gps_blending.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -/** - * @file gps_blending.cpp - */ - -#include "gps_blending.hpp" - - -void GpsBlending::update(uint64_t hrt_now_us) -{ - _is_new_output_data_available = false; - - updateReceiverTimeouts(hrt_now_us); - - // Only use selected receiver data if it has been updated - uint8_t gps_select_index = 0; - - // Find the single "best" GPS from the data we have - // First, find the GPS(s) with the best fix - uint8_t best_fix = 0; - - for (uint8_t i = 0; i < GPS_MAX_RECEIVERS_BLEND; i++) { - if (_gnss_state[i].fix_type > best_fix) { - best_fix = _gnss_state[i].fix_type; - } - } - - // Second, compare GPS's with best fix and take the one with most satellites - uint8_t max_sats = 0; - - for (uint8_t i = 0; i < GPS_MAX_RECEIVERS_BLEND; i++) { - if (_gnss_state[i].fix_type == best_fix && _gnss_state[i].satellites_used > max_sats) { - max_sats = _gnss_state[i].satellites_used; - gps_select_index = i; - } - } - - // Only use a secondary instance if the fallback is allowed - if ((_primary_instance > -1) - && (gps_select_index != _primary_instance) - && _primary_instance_available - && (_gnss_state[_primary_instance].fix_type >= 3)) { - gps_select_index = _primary_instance; - } - - _selected_gps = gps_select_index; - _output_antenna_offset = _antenna_offset[gps_select_index]; - _is_new_output_data_available = _gps_updated[gps_select_index]; - - if (_is_new_output_data_available) { - if ((_output_instance >= 0) && (_output_instance != _selected_gps)) { - _selection_count++; - } - - _output_instance = _selected_gps; - } - - for (uint8_t i = 0; i < GPS_MAX_RECEIVERS_BLEND; i++) { - // clear updated flags - _gps_updated[i] = false; - _time_prev_us[i] = _gnss_state[i].timestamp; - } -} - -void GpsBlending::updateReceiverTimeouts(uint64_t hrt_now_us) -{ - for (uint8_t i = 0; i < GPS_MAX_RECEIVERS_BLEND; i++) { - const uint64_t timestamp = _gnss_state[i].timestamp; - - if ((timestamp > _time_prev_us[i]) && (timestamp - _time_prev_us[i] < GPS_TIMEOUT_US)) { - if (i == _primary_instance) { - _primary_instance_available = true; - } - - } else if ((timestamp > 0) && (hrt_now_us >= timestamp + GPS_TIMEOUT_US)) { - // Timed out - kill the stored fix for this receiver - _gnss_state[i].timestamp = 0; - _gnss_state[i].fix_type = 0; - _gnss_state[i].satellites_used = 0; - _gnss_state[i].vel_ned_valid = 0; - - if (i == _primary_instance) { - // Allow using a secondary instance when the primary receiver has timed out - _primary_instance_available = false; - } - } - } -} diff --git a/src/modules/sensors/vehicle_gps_position/gps_blending.hpp b/src/modules/sensors/vehicle_gps_position/gps_blending.hpp deleted file mode 100644 index 088aaccaf79..00000000000 --- a/src/modules/sensors/vehicle_gps_position/gps_blending.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -/** - * @file gps_blending.hpp - */ - -#pragma once - -#include -#include -#include -#include - -using matrix::Vector3f; - -using namespace time_literals; - -class GpsBlending -{ -public: - // Set the GPS timeout to 2s, after which a receiver will be ignored - static constexpr hrt_abstime GPS_TIMEOUT_US = 2_s; - - GpsBlending() = default; - ~GpsBlending() = default; - - // define max number of GPS receivers supported - static constexpr int GPS_MAX_RECEIVERS_BLEND = 2; - - void setGnssData(const sensor_gnss_s &gnss_data, uint8_t instance) - { - if (instance < GPS_MAX_RECEIVERS_BLEND) { - _gnss_state[instance] = gnss_data; - _gps_updated[instance] = true; - } - } - void setPrimaryInstance(int primary) { _primary_instance = primary; } - void setAntennaOffset(const Vector3f &offset, uint8_t instance) - { - if (instance < GPS_MAX_RECEIVERS_BLEND) { _antenna_offset[instance] = offset; } - } - const Vector3f &getOutputAntennaOffset() const { return _output_antenna_offset; } - - void update(uint64_t hrt_now_us); - - bool isNewOutputDataAvailable() const { return _is_new_output_data_available; } - const sensor_gnss_s &getOutputGnssData() const { return _gnss_state[_selected_gps]; } - int getSelectedGps() const { return _selected_gps; } - - // Increments when the output changes to another receiver, which steps the position that consumers see - uint8_t getSelectionCount() const { return _selection_count; } - -private: - // Drop the stored fix of a receiver that stopped publishing, and track whether the primary one is publishing - void updateReceiverTimeouts(uint64_t hrt_now_us); - - sensor_gnss_s _gnss_state[GPS_MAX_RECEIVERS_BLEND] {}; ///< internal state data for the physical GPS - bool _gps_updated[GPS_MAX_RECEIVERS_BLEND] {}; - int _selected_gps{0}; - int _output_instance{-1}; ///< receiver of the last output, -1 before the first one - uint8_t _selection_count{0}; - int _primary_instance{0}; ///< if -1, there is no primary isntance and the best receiver is used // TODO: use device_id - bool _primary_instance_available{false}; - - bool _is_new_output_data_available{false}; - - uint64_t _time_prev_us[GPS_MAX_RECEIVERS_BLEND] {}; ///< the previous value of time_us for that GPS instance - used to detect new data. - - Vector3f _antenna_offset[GPS_MAX_RECEIVERS_BLEND] {}; - Vector3f _output_antenna_offset {}; -}; diff --git a/src/modules/sensors/vehicle_gps_position/gps_blending_test.cpp b/src/modules/sensors/vehicle_gps_position/gps_blending_test.cpp deleted file mode 100644 index bae6c9e477b..00000000000 --- a/src/modules/sensors/vehicle_gps_position/gps_blending_test.cpp +++ /dev/null @@ -1,340 +0,0 @@ -/**************************************************************************** - * - * Copyright (C) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -/** - * Test code for the GPS receiver selection logic - * Run this test only using make tests TESTFILTER=GpsBlending - * - * @author Mathieu Bresciani - */ - -#include -#include - -#include "gps_blending.hpp" - -using matrix::Vector3f; - -class GpsBlendingTest : public ::testing::Test -{ -public: - sensor_gnss_s getDefaultGnssData(); - void runSeconds(float duration_s, GpsBlending &gps_blending, sensor_gnss_s &gnss_data, int instance); - void runSeconds(float duration_s, GpsBlending &gps_blending, sensor_gnss_s &gnss_data0, sensor_gnss_s &gnss_data1); - - uint64_t _time_now_us{1000000}; -}; - -sensor_gnss_s GpsBlendingTest::getDefaultGnssData() -{ - sensor_gnss_s gnss_data{}; - gnss_data.timestamp = _time_now_us - 10e3; - gnss_data.time_utc_usec = 0; - gnss_data.latitude = 47.0; - gnss_data.longitude = 9.0; - gnss_data.altitude_msl = 800.0; - gnss_data.altitude_ellipsoid = 800.0; - gnss_data.speed_accuracy = 0.2f; - gnss_data.course_accuracy = 0.5f; - gnss_data.eph = 0.7f; - gnss_data.epv = 1.2f; - gnss_data.hdop = 1.f; - gnss_data.vdop = 1.f; - gnss_data.noise = 20; - gnss_data.jamming_indicator = 40; - gnss_data.ground_speed = 1.f; - gnss_data.vel_north = 1.f; - gnss_data.vel_east = 1.f; - gnss_data.vel_down = 1.f; - gnss_data.course = 0.f; - gnss_data.timestamp_time_relative = 0; - gnss_data.fix_type = 4; - gnss_data.vel_ned_valid = true; - gnss_data.satellites_used = 8; - - return gnss_data; -} - -void GpsBlendingTest::runSeconds(float duration_s, GpsBlending &gps_blending, sensor_gnss_s &gnss_data, int instance) -{ - const float dt = 0.1; - const uint64_t dt_us = static_cast(dt * 1e6f); - - for (int k = 0; k < static_cast(duration_s / dt); k++) { - gps_blending.setGnssData(gnss_data, instance); - gps_blending.update(_time_now_us); - - _time_now_us += dt_us; - gnss_data.timestamp += dt_us; - } -} - -void GpsBlendingTest::runSeconds(float duration_s, GpsBlending &gps_blending, sensor_gnss_s &gnss_data0, - sensor_gnss_s &gnss_data1) -{ - const float dt = 0.1; - const uint64_t dt_us = static_cast(dt * 1e6f); - - for (int k = 0; k < static_cast(duration_s / dt); k++) { - gps_blending.setGnssData(gnss_data0, 0); - gps_blending.setGnssData(gnss_data1, 1); - - gps_blending.update(_time_now_us); - - _time_now_us += dt_us; - gnss_data0.timestamp += dt_us; - gnss_data1.timestamp += dt_us; - } -} - -TEST_F(GpsBlendingTest, noData) -{ - GpsBlending gps_blending; - - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_FALSE(gps_blending.isNewOutputDataAvailable()); - - gps_blending.update(_time_now_us); - - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_FALSE(gps_blending.isNewOutputDataAvailable()); -} - -TEST_F(GpsBlendingTest, singleReceiver) -{ - GpsBlending gps_blending; - - gps_blending.setPrimaryInstance(-1); - sensor_gnss_s gnss_data = getDefaultGnssData(); - - gps_blending.setGnssData(gnss_data, 1); - gps_blending.update(_time_now_us); - - _time_now_us += 200e3; - gnss_data.timestamp = _time_now_us - 10e3; - gps_blending.setGnssData(gnss_data, 1); - gps_blending.update(_time_now_us); - - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - - // BUT IF: a second update is called without data - gps_blending.update(_time_now_us); - - // THEN: no new data should be available - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_FALSE(gps_blending.isNewOutputDataAvailable()); -} - -TEST_F(GpsBlendingTest, dualReceiverNoBlending) -{ - GpsBlending gps_blending; - - // GIVEN: two receivers with the same prioity - gps_blending.setPrimaryInstance(-1); - sensor_gnss_s gnss_data0 = getDefaultGnssData(); - sensor_gnss_s gnss_data1 = getDefaultGnssData(); - - gnss_data1.satellites_used = gnss_data0.satellites_used + 2; // gps1 has more satellites than gps0 - gps_blending.setGnssData(gnss_data0, 0); - gps_blending.setGnssData(gnss_data1, 1); - gps_blending.update(_time_now_us); - - // THEN: gps1 should be selected because it has more satellites - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - - gnss_data1.satellites_used = gnss_data0.satellites_used - 2; // gps1 has less satellites than gps0 - gps_blending.setGnssData(gnss_data0, 0); - gps_blending.setGnssData(gnss_data1, 1); - gps_blending.update(_time_now_us); - - // THEN: gps0 should be selected because it has more satellites - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); -} - -TEST_F(GpsBlendingTest, dualReceiverFailover) -{ - GpsBlending gps_blending; - - // GIVEN: a dual GPS setup with the first instance (0) - // set as primary - gps_blending.setPrimaryInstance(0); - - // WHEN: only the secondary receiver is available - sensor_gnss_s gnss_data1 = getDefaultGnssData(); - - const float duration_s = 10.f; - runSeconds(duration_s, gps_blending, gnss_data1, 1); - - // THEN: the secondary instance as the primary one is not available - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - EXPECT_EQ(gps_blending.getSelectionCount(), 0); - - // BUT WHEN: the data of the primary receiver is avaialbe - sensor_gnss_s gnss_data0 = getDefaultGnssData(); - runSeconds(1.f, gps_blending, gnss_data0, gnss_data1); - - // THEN: the primary instance is selected and the data - // is available, as the output of another receiver - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - EXPECT_EQ(gps_blending.getSelectionCount(), 1); - - runSeconds(duration_s, gps_blending, gnss_data0, gnss_data1); - - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - - // BUT WHEN: the primary receiver isn't available anymore - runSeconds(duration_s, gps_blending, gnss_data1, 1); - - // THEN: the data of the secondary receiver can be used - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - EXPECT_EQ(gps_blending.getSelectionCount(), 2); - - // AND IF: the primary receiver is available again and has - // better metrics than the secondary one - gnss_data0.timestamp = gnss_data1.timestamp; - gnss_data0.satellites_used = gnss_data1.satellites_used + 2; - - runSeconds(1.f, gps_blending, gnss_data0, gnss_data1); - - // THEN: the primary receiver should be used again - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - - // BUT IF: the secondary receiver has better metrics than the primary one - gnss_data1.satellites_used = gnss_data0.satellites_used + 2; - - runSeconds(1.f, gps_blending, gnss_data0, gnss_data1); - - // THEN: the selector shouldn't switch again as the primary one is available - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - - // BUT IF: the primary receiver looses its fix - gnss_data0.fix_type = 1; - - runSeconds(1.f, gps_blending, gnss_data0, gnss_data1); - - // THEN: the selector should switch as the primary one is unable to provide correct data - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); -} - -TEST_F(GpsBlendingTest, singleReceiverAntennaOffset) -{ - GpsBlending gps_blending; - - gps_blending.setPrimaryInstance(-1); - sensor_gnss_s gnss_data = getDefaultGnssData(); - - const Vector3f offset0(0.1f, 0.0f, -0.05f); - gps_blending.setAntennaOffset(offset0, 1); - - gps_blending.setGnssData(gnss_data, 1); - gps_blending.update(_time_now_us); - - _time_now_us += 200e3; - gnss_data.timestamp = _time_now_us - 10e3; - gps_blending.setGnssData(gnss_data, 1); - gps_blending.update(_time_now_us); - - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - - const Vector3f &out = gps_blending.getOutputAntennaOffset(); - EXPECT_FLOAT_EQ(out(0), offset0(0)); - EXPECT_FLOAT_EQ(out(1), offset0(1)); - EXPECT_FLOAT_EQ(out(2), offset0(2)); -} - -TEST_F(GpsBlendingTest, failoverAntennaOffset) -{ - GpsBlending gps_blending; - - gps_blending.setPrimaryInstance(0); - - const Vector3f offset0(0.1f, 0.0f, 0.0f); - const Vector3f offset1(-0.1f, 0.0f, 0.0f); - gps_blending.setAntennaOffset(offset0, 0); - gps_blending.setAntennaOffset(offset1, 1); - - // Only secondary available - sensor_gnss_s gnss_data1 = getDefaultGnssData(); - runSeconds(10.f, gps_blending, gnss_data1, 1); - - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_FLOAT_EQ(gps_blending.getOutputAntennaOffset()(0), offset1(0)); - - // Now primary becomes available - sensor_gnss_s gnss_data0 = getDefaultGnssData(); - gnss_data0.timestamp = gnss_data1.timestamp; - runSeconds(1.f, gps_blending, gnss_data0, gnss_data1); - - EXPECT_EQ(gps_blending.getSelectedGps(), 0); - EXPECT_FLOAT_EQ(gps_blending.getOutputAntennaOffset()(0), offset0(0)); -} - -TEST_F(GpsBlendingTest, dualReceiverNoBlendingStaleFlag) -{ - GpsBlending gps_blending; - - // GIVEN: two receivers - gps_blending.setPrimaryInstance(-1); - - sensor_gnss_s gnss_data0 = getDefaultGnssData(); - sensor_gnss_s gnss_data1 = getDefaultGnssData(); - - gnss_data1.satellites_used = gnss_data0.satellites_used + 2; // gps1 wins selection - - // First update: both receivers provide data, gps1 is selected - gps_blending.setGnssData(gnss_data0, 0); - gps_blending.setGnssData(gnss_data1, 1); - gps_blending.update(_time_now_us); - - EXPECT_EQ(gps_blending.getSelectedGps(), 1); - EXPECT_TRUE(gps_blending.isNewOutputDataAvailable()); - - // Second update: NO new data from either receiver - // With the bug (_gps_updated[gps_select_index] instead of [i]), - // the non-selected instance's flag was never cleared, so this - // would spuriously report new data available. - gps_blending.update(_time_now_us); - - EXPECT_FALSE(gps_blending.isNewOutputDataAvailable()); -} diff --git a/src/modules/sensors/vehicle_gps_position/module.yaml b/src/modules/sensors/vehicle_gps_position/module.yaml index be55f932974..2dc5dac8e85 100644 --- a/src/modules/sensors/vehicle_gps_position/module.yaml +++ b/src/modules/sensors/vehicle_gps_position/module.yaml @@ -8,22 +8,13 @@ parameters: SENS_GNSS_PRIME: description: short: Multi GPS primary instance - long: | - Preferred GPS receiver instance. - The GPS selection logic waits until the primary receiver is available to - send data to the EKF even if a secondary instance is already available. - The secondary instance is then only used if the primary one times out. - - To select a DroneCAN GPS, set this to the node ID. - - GPS_RAW_INT reports the preferred receiver, or without one the first receiver - to publish, and GPS2_RAW the other one. Neither follows the selection. + long: "The primary receiver is used while it passes the strict checks (GNSS_REQ_*), and while disarmed whenever it publishes. In flight, the other receiver is used when the primary fails its checks (GNSS_CHECK) or stops publishing for 2 s, and then for the rest of the flight unless it fails too. The other receiver is also used once it has been better through a hold: when the primary failed the strict checks while the other passed them, or when the primary was usable for a clearly smaller share of the last 10 s or so (availability lower by 0.2). The primary is used again once it has been better through the hold. The hold is 10 s and doubles with every such switch in a flight, so the first return takes 20 s. With Auto, the moving base of a moving base pair (SENS_GNSSn_HDG) is the primary. Without a primary, a receiver that passes the strict checks is preferred, and among those one with an RTK fixed solution. To make a DroneCAN receiver the primary, set its node ID (2 to 127). GPS_RAW_INT reports the primary receiver, or the first receiver to publish if there is no primary." type: int32 - default: 0 + default: -1 min: -1 max: 127 values: - -1: Auto (equal priority) + -1: Auto 0: Main serial GPS 1: Secondary serial GPS SENS_GNSS${i}_ID: @@ -141,6 +132,9 @@ parameters: GNSS_REQ_SACC: description: short: Required speed accuracy to use GNSS + long: EKF2 also feeds GNSS velocity to the EKF-GSF yaw estimator, and trusts the GNSS vertical velocity + while the accelerometer clips, only below this speed accuracy, in flight too. With the speed accuracy + check disabled in GNSS_CHECK, it does both whatever the speed accuracy. type: float default: 0.5 min: 0.5