diff --git a/src/modules/sensors/vehicle_magnetometer/CMakeLists.txt b/src/modules/sensors/vehicle_magnetometer/CMakeLists.txt index 0fad202f501..a3ce9f8fc90 100644 --- a/src/modules/sensors/vehicle_magnetometer/CMakeLists.txt +++ b/src/modules/sensors/vehicle_magnetometer/CMakeLists.txt @@ -42,3 +42,7 @@ target_link_libraries(vehicle_magnetometer px4_work_queue sensor_calibration ) + +if(BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.cpp b/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.cpp index d7bd15373f1..02b11180160 100644 --- a/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.cpp +++ b/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.cpp @@ -497,34 +497,37 @@ void VehicleMagnetometer::Run() _priority[uorb_index] = _calibration[uorb_index].priority(); } - if (_calibration[uorb_index].enabled()) { - - if (!was_advertised) { - if (uorb_index > 0) { - /* the first always exists, but for each further sensor, add a new validator */ - if (!_voter.add_new_validator()) { - PX4_ERR("failed to add validator for %s %i", _calibration[uorb_index].SensorString(), uorb_index); - } + if (!was_advertised) { + if (uorb_index > 0) { + /* the first always exists, but for each further sensor, add a new validator */ + if (!_voter.add_new_validator()) { + PX4_ERR("failed to add validator for %s %i", _calibration[uorb_index].SensorString(), uorb_index); } - - if (_selected_sensor_sub_index < 0) { - _sensor_sub[uorb_index].registerCallback(); - } - - ParametersUpdate(true); } - const Vector3f vect{_calibration[uorb_index].Correct(Vector3f{report.x, report.y, report.z}) - _calibration_estimator_bias[uorb_index]}; + // callbacks are only cleared on a selection change, which never comes while every + // sensor is disabled, so a disabled one must not drive Run() at its sample rate + if ((_selected_sensor_sub_index < 0) && (_priority[uorb_index] > 0)) { + _sensor_sub[uorb_index].registerCallback(); + } - float mag_array[3] {vect(0), vect(1), vect(2)}; - _voter.put(uorb_index, report.timestamp, mag_array, report.error_count, _priority[uorb_index]); + ParametersUpdate(true); + } + const Vector3f vect{_calibration[uorb_index].Correct(Vector3f{report.x, report.y, report.z}) - _calibration_estimator_bias[uorb_index]}; + + float mag_array[3] {vect(0), vect(1), vect(2)}; + + // a priority of 0 keeps the sensor tracked but excluded from selection + _voter.put(uorb_index, report.timestamp, mag_array, report.error_count, _priority[uorb_index]); + + _last_data[uorb_index] = vect; + + if (_calibration[uorb_index].enabled()) { _timestamp_sample_sum[uorb_index] += report.timestamp_sample; _data_sum[uorb_index] += vect; _data_sum_count[uorb_index]++; - _last_data[uorb_index] = vect; - updated[uorb_index] = true; } } @@ -535,22 +538,28 @@ void VehicleMagnetometer::Run() int best_index = 0; _voter.get_best(time_now_us, &best_index); - if (best_index >= 0) { - // handle selection change (don't process on same iteration as parameter update) - if ((_selected_sensor_sub_index != best_index) && !parameter_update) { - // clear all registered callbacks - for (auto &sub : _sensor_sub) { - sub.unregisterCallback(); - } + // handle selection change (don't process on same iteration as parameter update) + // best_index is -1 when every magnetometer is disabled, which has to clear the selection + if ((_selected_sensor_sub_index != best_index) && !parameter_update) { + // clear all registered callbacks + for (auto &sub : _sensor_sub) { + sub.unregisterCallback(); + } - if (_param_sens_mag_mode.get()) { - if (_selected_sensor_sub_index >= 0) { - PX4_INFO("%s switch from #%" PRId8 " -> #%d", _calibration[_selected_sensor_sub_index].SensorString(), - _selected_sensor_sub_index, best_index); - } - } + if (_param_sens_mag_mode.get() && (_selected_sensor_sub_index >= 0)) { + if (best_index >= 0) { + PX4_INFO("%s switch from #%" PRId8 " -> #%d", _calibration[_selected_sensor_sub_index].SensorString(), + _selected_sensor_sub_index, best_index); - _selected_sensor_sub_index = best_index; + } else { + PX4_INFO("%s #%" PRId8 " deselected, no magnetometer available", + _calibration[_selected_sensor_sub_index].SensorString(), _selected_sensor_sub_index); + } + } + + _selected_sensor_sub_index = best_index; + + if (_selected_sensor_sub_index >= 0) { _sensor_sub[_selected_sensor_sub_index].registerCallback(); } } @@ -677,8 +686,10 @@ void VehicleMagnetometer::CheckFailover(const hrt_abstime &time_now_us) _last_error_message = time_now_us; } - // reduce priority of failed sensor to the minimum - _priority[failover_index] = 1; + // reduce priority of failed sensor to the minimum, without re-enabling a disabled one + if (_priority[failover_index] > 0) { + _priority[failover_index] = 1; + } } } @@ -732,44 +743,60 @@ void VehicleMagnetometer::calcMagInconsistency() void VehicleMagnetometer::UpdateStatus() { - if (_selected_sensor_sub_index >= 0) { - sensors_status_s sensors_status{}; - sensors_status.device_id_primary = _calibration[_selected_sensor_sub_index].device_id(); + sensors_status_s sensors_status{}; + sensors_status.device_id_primary = (_selected_sensor_sub_index >= 0) ? + _calibration[_selected_sensor_sub_index].device_id() : 0; - matrix::Vector3f mean{}; - int sensor_count = 0; + matrix::Vector3f mean{}; + int sensor_count = 0; + int known_count = 0; - for (int sensor_index = 0; sensor_index < MAX_SENSOR_COUNT; sensor_index++) { - if ((_calibration[sensor_index].device_id() != 0) && (_calibration[sensor_index].enabled())) { + for (int sensor_index = 0; sensor_index < MAX_SENSOR_COUNT; sensor_index++) { + if (_calibration[sensor_index].device_id() != 0) { + known_count++; + + // the mean is the reference the inconsistency is measured against, so only + // the sensors actually eligible for use contribute to it + if (_calibration[sensor_index].enabled()) { sensor_count++; mean += _last_data[sensor_index]; } } + } - if (sensor_count > 0) { - mean /= sensor_count; - } + if (known_count == 0) { + return; + } - for (int sensor_index = 0; sensor_index < MAX_SENSOR_COUNT; sensor_index++) { - if (_calibration[sensor_index].device_id() != 0) { + if (sensor_count > 0) { + mean /= sensor_count; + } + for (int sensor_index = 0; sensor_index < MAX_SENSOR_COUNT; sensor_index++) { + if (_calibration[sensor_index].device_id() != 0) { + + if (sensor_count > 0) { _sensor_diff[sensor_index] = 0.95f * _sensor_diff[sensor_index] + 0.05f * (_last_data[sensor_index] - mean); - - sensors_status.device_ids[sensor_index] = _calibration[sensor_index].device_id(); sensors_status.inconsistency[sensor_index] = _sensor_diff[sensor_index].norm(); - sensors_status.healthy[sensor_index] = (_voter.get_sensor_state(sensor_index) == DataValidator::ERROR_FLAG_NO_ERROR); - sensors_status.priority[sensor_index] = _voter.get_sensor_priority(sensor_index); - sensors_status.enabled[sensor_index] = _calibration[sensor_index].enabled(); - sensors_status.external[sensor_index] = _calibration[sensor_index].external(); } else { + // with nothing enabled there is no reference to measure against sensors_status.inconsistency[sensor_index] = NAN; } - } - sensors_status.timestamp = hrt_absolute_time(); - _sensors_status_mag_pub.publish(sensors_status); + sensors_status.device_ids[sensor_index] = _calibration[sensor_index].device_id(); + sensors_status.healthy[sensor_index] = (_voter.get_sensor_state(sensor_index) == DataValidator::ERROR_FLAG_NO_ERROR); + sensors_status.priority[sensor_index] = _voter.get_sensor_priority(sensor_index); + sensors_status.enabled[sensor_index] = _calibration[sensor_index].enabled(); + sensors_status.external[sensor_index] = _calibration[sensor_index].external(); + + } else { + sensors_status.inconsistency[sensor_index] = NAN; + } } + + sensors_status.timestamp = hrt_absolute_time(); + _sensors_status_mag_pub.publish(sensors_status); } void VehicleMagnetometer::PrintStatus() diff --git a/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.hpp b/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.hpp index c90398fe1f6..6642c474d69 100644 --- a/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.hpp +++ b/src/modules/sensors/vehicle_magnetometer/VehicleMagnetometer.hpp @@ -77,9 +77,16 @@ public: void PrintStatus(); -private: +protected: void Run() override; + // read access for the functional test, unused by the module itself + int8_t selectedSensorIndex() const { return _selected_sensor_sub_index; } + uint8_t sensorPriority(int index) const { return _priority[index]; } + unsigned voterFailoverCount() { return _voter.failover_count(); } + bool callbackRegistered(int index) const { return _sensor_sub[index].registered(); } + +private: void CheckFailover(const hrt_abstime &time_now_us); bool ParametersUpdate(bool force = false); void UpdateStatus(); diff --git a/src/modules/sensors/vehicle_magnetometer/test/CMakeLists.txt b/src/modules/sensors/vehicle_magnetometer/test/CMakeLists.txt new file mode 100644 index 00000000000..e26a378788b --- /dev/null +++ b/src/modules/sensors/vehicle_magnetometer/test/CMakeLists.txt @@ -0,0 +1,35 @@ +############################################################################ +# +# 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. +# +############################################################################ + +px4_add_functional_gtest(SRC VehicleMagnetometerTest.cpp LINKLIBS vehicle_magnetometer uORB sensor_calibration) diff --git a/src/modules/sensors/vehicle_magnetometer/test/VehicleMagnetometerTest.cpp b/src/modules/sensors/vehicle_magnetometer/test/VehicleMagnetometerTest.cpp new file mode 100644 index 00000000000..e6abb931392 --- /dev/null +++ b/src/modules/sensors/vehicle_magnetometer/test/VehicleMagnetometerTest.cpp @@ -0,0 +1,332 @@ +/**************************************************************************** + * + * 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. + * + ****************************************************************************/ + +/** + * Test for VehicleMagnetometer + */ + +#include + +#include "../VehicleMagnetometer.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using matrix::Vector3f; + +class VehicleMagnetometerTest : public ::testing::Test +{ +public: + class VehicleMagnetometerTestable : public sensors::VehicleMagnetometer + { + public: + // Run() re-arms itself through the hrt callout worker, cleared again so the cycle stays + // in the test's hands + void RunPublic() + { + Run(); + ScheduleClear(); + } + int selectedIndex() const { return selectedSensorIndex(); } + unsigned failoverCount() { return voterFailoverCount(); } + bool callbackRegistered(int index) const { return VehicleMagnetometer::callbackRegistered(index); } + uint8_t priority(int index) const { return sensorPriority(index); } + }; + + static constexpr int kSensorCount = 3; + + // device i publishes on sensor_mag instance i and is calibrated in slot CAL_MAGi for the whole suite + static constexpr uint32_t kDeviceIds[kSensorCount] {0x1a2b01, 0x1a2b02, 0x1a2b03}; + + // uORB nodes outlive a manager restart, so the suite brings the manager up once and keeps its topics + static void SetUpTestSuite() + { + // the gtest harness does not bring up the hrt: Run() schedules its next cycle through it, + // and without hrt_init() the callout lock is not recursive, so the worker deadlocks on + // its own nested lock on Linux the first time a callout is due + hrt_init(); + hrt_work_queue_init(); + uORB::Manager::initialize(); + + for (int i = 0; i < kSensorCount; i++) { + ASSERT_TRUE(_sensor_mag_pubs[i].advertise()); + ASSERT_EQ(_sensor_mag_pubs[i].get_instance(), i); + } + } + + // every test starts with all three devices disabled and enables the ones it uses + void SetUp() override + { + for (int i = 0; i < kSensorCount; i++) { + setPriority(i, 0); + } + } + + static void setParam(const char *name, int32_t value) + { + const param_t handle = param_find(name); + ASSERT_NE(handle, PARAM_INVALID) << name; + ASSERT_EQ(param_set_no_notification(handle, &value), 0) << name; + } + + static void setPriority(int device, int32_t priority) + { + char name[20] {}; + snprintf(name, sizeof(name), "CAL_MAG%d_ID", device); + setParam(name, static_cast(kDeviceIds[device])); + snprintf(name, sizeof(name), "CAL_MAG%d_PRIO", device); + setParam(name, priority); + } + + static void publishSample(int device, const Vector3f &field) + { + sensor_mag_s sample{}; + sample.timestamp_sample = hrt_absolute_time(); + sample.timestamp = sample.timestamp_sample; + sample.device_id = kDeviceIds[device]; + sample.is_external = true; + sample.x = field(0); + sample.y = field(1); + sample.z = field(2); + _sensor_mag_pubs[device].publish(sample); + } + + static void publishParameterUpdate() + { + parameter_update_s update{}; + update.timestamp = hrt_absolute_time(); + _parameter_update_pub.publish(update); + } + + // run the module at its own 50 ms cadence for the given time, feeding it the given samples + template + static void runFor(VehicleMagnetometerTestable &module, hrt_abstime duration, Feed feed) + { + const hrt_abstime start = hrt_absolute_time(); + + do { + feed(); + module.RunPublic(); + px4_usleep(50_ms); + } while (hrt_absolute_time() < start + duration); + } + + bool readStatus(sensors_status_s &status) { return _sensors_status_mag_sub.copy(&status); } + + bool readPreflight(sensor_preflight_mag_s &preflight) { return _sensor_preflight_mag_sub.copy(&preflight); } + + // consumes everything published since the last call + bool magnetometerPublished() + { + bool published = false; + vehicle_magnetometer_s unused; + + while (_vehicle_magnetometer_sub.update(&unused)) { + published = true; + } + + return published; + } + + static uORB::PublicationMulti _sensor_mag_pubs[kSensorCount]; + static uORB::Publication _parameter_update_pub; + + uORB::Subscription _sensors_status_mag_sub{ORB_ID(sensors_status_mag)}; + uORB::Subscription _sensor_preflight_mag_sub{ORB_ID(sensor_preflight_mag)}; + uORB::Subscription _vehicle_magnetometer_sub{ORB_ID(vehicle_magnetometer)}; + + const Vector3f _field{0.2f, 0.f, 0.4f}; +}; + +constexpr uint32_t VehicleMagnetometerTest::kDeviceIds[]; +uORB::PublicationMulti VehicleMagnetometerTest::_sensor_mag_pubs[kSensorCount] { + {ORB_ID(sensor_mag)}, {ORB_ID(sensor_mag)}, {ORB_ID(sensor_mag)} +}; +uORB::Publication VehicleMagnetometerTest::_parameter_update_pub{ORB_ID(parameter_update)}; + +TEST_F(VehicleMagnetometerTest, DisabledAtRuntimeHandsOverWithoutFailover) +{ + setPriority(0, 75); + setPriority(1, 50); + + VehicleMagnetometerTestable module; + + runFor(module, 500_ms, [&]() { + publishSample(0, _field); + publishSample(1, _field); + }); + + ASSERT_EQ(module.selectedIndex(), 0); + ASSERT_EQ(module.failoverCount(), 0u); + + // the operator disables device 0 while it is selected, and it keeps publishing + setPriority(0, 0); + publishParameterUpdate(); + + // long enough for the module's throttled parameter subscription to pick up the change + runFor(module, 1200_ms, [&]() { + publishSample(0, _field); + publishSample(1, _field); + }); + + EXPECT_EQ(module.selectedIndex(), 1); + EXPECT_EQ(module.priority(0), 0); + EXPECT_EQ(module.failoverCount(), 0u) << "leaving a disabled magnetometer is not a failure"; + + sensors_status_s status{}; + ASSERT_TRUE(readStatus(status)); + EXPECT_EQ(status.device_id_primary, kDeviceIds[1]); + EXPECT_EQ(status.priority[0], 0); + EXPECT_FALSE(status.enabled[0]); + EXPECT_TRUE(status.enabled[1]); + + // device 0 now reports the opposite field, which must not count against the consistency check + runFor(module, 500_ms, [&]() { + publishSample(0, -_field); + publishSample(1, _field); + }); + + EXPECT_EQ(module.priority(0), 0); + + sensor_preflight_mag_s preflight{}; + ASSERT_TRUE(readPreflight(preflight)); + EXPECT_LT(preflight.mag_inconsistency_angle, 0.01f); +} + +TEST_F(VehicleMagnetometerTest, MagnetometerAfterDisabledSlotIsVotedOn) +{ + // device 1 is disabled before the module ever sees it, and device 2 sits after it in instance order + setPriority(0, 75); + setPriority(2, 75); + + VehicleMagnetometerTestable module; + + runFor(module, 500_ms, [&]() { + publishSample(0, _field); + publishSample(1, _field); + publishSample(2, _field); + }); + + ASSERT_EQ(module.selectedIndex(), 0); + EXPECT_EQ(module.priority(1), 0); + + // device 0 stops, so the voter has to hand over to device 2 past the disabled one + runFor(module, 600_ms, [&]() { + publishSample(1, _field); + publishSample(2, _field); + }); + + EXPECT_EQ(module.selectedIndex(), 2); + EXPECT_EQ(module.priority(1), 0); + + sensors_status_s status{}; + ASSERT_TRUE(readStatus(status)); + EXPECT_EQ(status.device_id_primary, kDeviceIds[2]); + EXPECT_FALSE(status.enabled[1]); + EXPECT_TRUE(status.healthy[2]); +} + +TEST_F(VehicleMagnetometerTest, OnlyMagnetometerDisabledClearsSelectionAndComesBack) +{ + setPriority(0, 75); + + VehicleMagnetometerTestable module; + + runFor(module, 500_ms, [&]() { publishSample(0, _field); }); + + ASSERT_EQ(module.selectedIndex(), 0); + ASSERT_TRUE(magnetometerPublished()); + + setPriority(0, 0); + publishParameterUpdate(); + + runFor(module, 1200_ms, [&]() { publishSample(0, _field); }); + + EXPECT_EQ(module.selectedIndex(), -1); + EXPECT_EQ(module.failoverCount(), 0u); + + // the status keeps reporting with no primary, so the ground station sees the disabled sensor + sensors_status_s status{}; + ASSERT_TRUE(readStatus(status)); + EXPECT_EQ(status.device_id_primary, 0u); + EXPECT_FALSE(status.enabled[0]); + EXPECT_EQ(status.priority[0], 0); + EXPECT_TRUE(status.healthy[0]); + + (void)magnetometerPublished(); + runFor(module, 300_ms, [&]() { publishSample(0, _field); }); + EXPECT_FALSE(magnetometerPublished()) << "a disabled magnetometer is not published as vehicle_magnetometer"; + + // re-enabled at an explicit priority, the sensor comes back at exactly that priority + setPriority(0, 60); + publishParameterUpdate(); + + runFor(module, 1200_ms, [&]() { publishSample(0, _field); }); + + EXPECT_EQ(module.selectedIndex(), 0); + EXPECT_EQ(module.priority(0), 60); + EXPECT_EQ(module.failoverCount(), 0u); + EXPECT_TRUE(magnetometerPublished()); +} + +TEST_F(VehicleMagnetometerTest, MagnetometerDisabledFromBootDoesNotDriveRun) +{ + // the only magnetometer is disabled before the module sees it: nothing ever gets selected, so + // nothing ever clears the callbacks, and one registered here would wake Run() at the sample rate + VehicleMagnetometerTestable module; + + runFor(module, 500_ms, [&]() { publishSample(0, _field); }); + + EXPECT_EQ(module.selectedIndex(), -1); + EXPECT_EQ(module.priority(0), 0); + EXPECT_FALSE(module.callbackRegistered(0)); + + setPriority(0, 75); + publishParameterUpdate(); + + runFor(module, 1200_ms, [&]() { publishSample(0, _field); }); + + EXPECT_EQ(module.selectedIndex(), 0); + EXPECT_TRUE(module.callbackRegistered(0)); +}