From e58250d5b5d9afbe297cb2a082463d3caa417e53 Mon Sep 17 00:00:00 2001 From: Sofian Elmotiem Date: Fri, 30 Oct 2026 01:35:28 +0100 Subject: [PATCH] fix(battery): name the missing cell count when the state of charge is unknown (#29184) * fix(battery): don't report an unknown state of charge as an emergency With BATn_N_CELLS at 0 the battery library can't estimate the state of charge and publishes remaining = -1, which determineWarning() graded as WARNING_EMERGENCY. Arming was refused with "Emergency battery level" and the same path could trigger battery failsafes in flight. An unknown state of charge now maps to no warning and isn't counted as below COM_ARM_BAT_MIN. Arming is still blocked for a battery with unknown charge and no cell count, with a message pointing at the actual cause. Fixes #29154 Signed-off-by: Sofian Elmotiem <191787501+SofianElmotiem@users.noreply.github.com> * fix(battery): keep an unknown state of charge treated as an emergency Grading an unknown state of charge as no warning removed the battery failsafe for it in flight, and ignoring it for COM_ARM_BAT_MIN let a battery without a charge estimate arm. Keep both as before; the arming check only adds a message naming the missing cell count. Signed-off-by: Sofian Elmotiem <191787501+SofianElmotiem@users.noreply.github.com> * fix(battery): report unknown charge by source and BATn index Blaming the cell count for every unknown charge was wrong for external batteries, which report their own charge (Cyphal legacy always sends cell_count = 0), and the uORB instance doesn't match the BATn index. Gating coulomb counting on a non-negative estimate also let a NaN voltage, from the ESC battery averaging over zero online ESCs, through as no warning. Signed-off-by: Sofian Elmotiem <191787501+SofianElmotiem@users.noreply.github.com> * fix(battery): only report unknown charge before arming Blocking arming does nothing once we're in the air, but the check kept sending a critical status text every time an external battery reported an unknown charge. Only run it while disarmed. While at it: report an unknown time remaining instead of a negative one, make the external message neutral since a DroneCAN battery can still be estimated from BATn_N_CELLS, and tag Cyphal UDRAL batteries as external so they don't point at BAT0_N_CELLS. Signed-off-by: Sofian Elmotiem <191787501+SofianElmotiem@users.noreply.github.com> --------- Signed-off-by: Sofian Elmotiem <191787501+SofianElmotiem@users.noreply.github.com> Co-authored-by: Sofian Elmotiem <191787501+SofianElmotiem@users.noreply.github.com> --- .../cyphal/Subscribers/udral/Battery.hpp | 1 + src/lib/battery/BatteryTest.cpp | 128 ++++++++++++++++++ src/lib/battery/CMakeLists.txt | 1 + src/lib/battery/battery.cpp | 7 +- .../HealthAndArmingChecks/Common.hpp | 1 + .../batteryChecksTest.cpp | 94 ++++++++++++- .../checks/batteryCheck.cpp | 50 +++++++ .../checks/batteryCheck.hpp | 1 + src/modules/esc_battery/EscBattery.cpp | 6 + src/modules/mavlink/mavlink_receiver.cpp | 1 + 10 files changed, 285 insertions(+), 5 deletions(-) create mode 100644 src/lib/battery/BatteryTest.cpp diff --git a/src/drivers/cyphal/Subscribers/udral/Battery.hpp b/src/drivers/cyphal/Subscribers/udral/Battery.hpp index 310bc976632..f1bb653cfea 100644 --- a/src/drivers/cyphal/Subscribers/udral/Battery.hpp +++ b/src/drivers/cyphal/Subscribers/udral/Battery.hpp @@ -109,6 +109,7 @@ public: bat_status.current_a = source_ts.value.power.current.ampere; bat_status.connected = true; // Based on some threshold or an error?? + bat_status.source = battery_status_s::SOURCE_EXTERNAL; // Estimate discharged mah from Joule if (PX4_ISFINITE(_nominal_voltage)) { diff --git a/src/lib/battery/BatteryTest.cpp b/src/lib/battery/BatteryTest.cpp new file mode 100644 index 00000000000..6c504fb8be7 --- /dev/null +++ b/src/lib/battery/BatteryTest.cpp @@ -0,0 +1,128 @@ +/**************************************************************************** + * + * 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 "battery.h" + +#include + +// to run: make tests TESTFILTER=Battery + +using namespace time_literals; + +class BatteryTest : public ::testing::Test +{ +public: + void SetUp() override + { + param_control_autosave(false); + param_reset(param_find("BAT1_N_CELLS")); + param_reset(param_find("BAT1_CAPACITY")); + } + + void TearDown() override + { + param_reset(param_find("BAT1_N_CELLS")); + param_reset(param_find("BAT1_CAPACITY")); + } + + // feed a connected battery for long enough to pass the initialization delay + static battery_status_s run(Battery &battery, float voltage_v, float current_a) + { + hrt_abstime timestamp = 1_s; + + for (int i = 0; i < 8 * 50; i++) { + battery.setConnected(true); + battery.updateVoltage(voltage_v); + battery.updateCurrent(current_a); + battery.updateBatteryStatus(timestamp); + timestamp += 20_ms; + } + + return battery.getBatteryStatus(); + } +}; + +// without a cell count the state of charge is unknown, which is treated as empty +TEST_F(BatteryTest, UnknownCellCountIsAnEmergency) +{ + Battery battery(1, nullptr, 20_ms, battery_status_s::SOURCE_POWER_MODULE); + const battery_status_s status = run(battery, 12.4f, 1.f); + EXPECT_EQ(status.cell_count, 0); + EXPECT_FLOAT_EQ(status.remaining, -1.f); + EXPECT_EQ(status.warning, battery_status_s::WARNING_EMERGENCY); +} + +// a configured capacity can't make up for the unknown starting charge, so it stays reported as unknown +TEST_F(BatteryTest, UnknownCellCountWithCapacityStaysUnknown) +{ + float capacity = 5000.f; + param_set(param_find("BAT1_CAPACITY"), &capacity); + + Battery battery(1, nullptr, 20_ms, battery_status_s::SOURCE_POWER_MODULE); + const battery_status_s status = run(battery, 12.4f, 1.f); + EXPECT_FLOAT_EQ(status.remaining, -1.f); + EXPECT_EQ(status.warning, battery_status_s::WARNING_EMERGENCY); + EXPECT_FALSE(PX4_ISFINITE(status.time_remaining_s)); +} + +// a NaN voltage with a configured capacity must not hide the emergency +TEST_F(BatteryTest, NanVoltageWithCapacityIsAnEmergency) +{ + int32_t n_cells = 3; + param_set(param_find("BAT1_N_CELLS"), &n_cells); + float capacity = 5000.f; + param_set(param_find("BAT1_CAPACITY"), &capacity); + + Battery battery(1, nullptr, 20_ms, battery_status_s::SOURCE_ESCS); + const battery_status_s status = run(battery, NAN, 1.f); + EXPECT_EQ(status.warning, battery_status_s::WARNING_EMERGENCY); +} + +TEST_F(BatteryTest, KnownCellCountEstimatesCharge) +{ + int32_t n_cells = 3; + param_set(param_find("BAT1_N_CELLS"), &n_cells); + + Battery battery(1, nullptr, 20_ms, battery_status_s::SOURCE_POWER_MODULE); + const battery_status_s status = run(battery, 12.4f, 1.f); + EXPECT_EQ(status.cell_count, 3); + EXPECT_GT(status.remaining, 0.5f); + EXPECT_EQ(status.warning, battery_status_s::WARNING_NONE); + + // an empty battery still raises the emergency warning + Battery empty_battery(1, nullptr, 20_ms, battery_status_s::SOURCE_POWER_MODULE); + const battery_status_s empty_status = run(empty_battery, 9.f, 1.f); + EXPECT_EQ(empty_status.warning, battery_status_s::WARNING_EMERGENCY); +} diff --git a/src/lib/battery/CMakeLists.txt b/src/lib/battery/CMakeLists.txt index b2377e8f33c..106a6bb2478 100644 --- a/src/lib/battery/CMakeLists.txt +++ b/src/lib/battery/CMakeLists.txt @@ -37,3 +37,4 @@ target_link_libraries(battery PRIVATE failure_injection) # TODO: Add an option in px4_add_library function to add module config file set_property(GLOBAL APPEND PROPERTY PX4_MODULE_CONFIG_FILES ${CMAKE_CURRENT_SOURCE_DIR}/module.yaml) +px4_add_functional_gtest(SRC BatteryTest.cpp LINKLIBS battery) diff --git a/src/lib/battery/battery.cpp b/src/lib/battery/battery.cpp index 04e619cebde..1dc833bb869 100644 --- a/src/lib/battery/battery.cpp +++ b/src/lib/battery/battery.cpp @@ -327,7 +327,8 @@ void Battery::resetInternalResistanceEstimation(const float voltage_v, const flo void Battery::estimateStateOfCharge() { // choose which quantity we're using for final reporting - if ((_capacity_mah > 0.f) && _battery_initialized) { + // without a cell count the starting charge is unknown, so coulomb counting can't help + if ((_capacity_mah > 0.f) && _battery_initialized && (_params.n_cells > 0)) { // if battery capacity is known, fuse voltage measurement with used capacity // The lower the voltage the more adjust the estimate with it to avoid deep discharge const float weight_v = 3e-2f * (1 - _state_of_charge_volt_based); @@ -418,8 +419,8 @@ float Battery::computeRemainingTime(float current_a) } } - // Remaining time estimation only possible with capacity - if (_capacity_mah > 0.f) { + // Remaining time estimation only possible with capacity and a known state of charge + if ((_capacity_mah > 0.f) && (_state_of_charge >= 0.f)) { const float remaining_capacity_mah = _state_of_charge * _capacity_mah; const float current_ma = fmaxf(_current_average_filter_a.getState() * 1e3f, FLT_EPSILON); time_remaining_s = remaining_capacity_mah / current_ma * 3600.f; diff --git a/src/modules/commander/HealthAndArmingChecks/Common.hpp b/src/modules/commander/HealthAndArmingChecks/Common.hpp index 0d8f735367d..80a7ce28412 100644 --- a/src/modules/commander/HealthAndArmingChecks/Common.hpp +++ b/src/modules/commander/HealthAndArmingChecks/Common.hpp @@ -329,6 +329,7 @@ private: friend class HealthAndArmingChecks; friend class ExternalChecks; + friend class BatteryChecksTest; // publishes the reported events FRIEND_TEST(ReporterTest, basic_no_checks); FRIEND_TEST(ReporterTest, basic_fail_all_modes); FRIEND_TEST(ReporterTest, arming_checks_mode_category); diff --git a/src/modules/commander/HealthAndArmingChecks/batteryChecksTest.cpp b/src/modules/commander/HealthAndArmingChecks/batteryChecksTest.cpp index f202fd67212..ba70ef66874 100644 --- a/src/modules/commander/HealthAndArmingChecks/batteryChecksTest.cpp +++ b/src/modules/commander/HealthAndArmingChecks/batteryChecksTest.cpp @@ -33,12 +33,17 @@ #include +#include +#include + #include "checks/batteryCheck.hpp" #include #include #include +#include #include +#include // to run: make tests TESTFILTER=batteryChecks @@ -54,6 +59,9 @@ public: // advertised once for the whole suite so they keep instances 0 and 1 static void SetUpTestSuite() { + // ensure the topic exists, otherwise the first reported events are lost + orb_advertise(ORB_ID(event), nullptr); + for (int i = 0; i < kBatteryCount; i++) { ASSERT_TRUE(_battery_pubs[i].advertise()); ASSERT_EQ(_battery_pubs[i].get_instance(), i); @@ -68,12 +76,16 @@ public: publish(1, battery_status_s::WARNING_NONE); } - static void publish(int index, uint8_t warning, bool connected = true) + static void publish(int index, uint8_t warning, bool connected = true, float remaining = 0.5f, uint8_t cell_count = 0, + uint8_t source = battery_status_s::SOURCE_POWER_MODULE, uint8_t id = 1) { battery_status_s battery{}; battery.timestamp = hrt_absolute_time(); battery.connected = connected; - battery.remaining = 0.5f; + battery.remaining = remaining; + battery.cell_count = cell_count; + battery.source = source; + battery.id = id; battery.time_remaining_s = NAN; battery.warning = warning; _battery_pubs[index].publish(battery); @@ -91,12 +103,35 @@ public: Report reporter{_failsafe_flags, 0}; _check.checkAndReport(context, reporter); _can_arm = reporter.armingCheckResults().can_arm == NavModes::All; + + // publish the reported events and keep the battery checks' own ones + event_s event; + + while (_event_sub.update(&event)) {} + + reporter.finalize(); + reporter.report(true); + _events.clear(); + + while (_event_sub.update(&event)) { + _events.push_back(event); + } + } + + // the battery number argument follows the modes (uint32) and the health component (uint8) + bool reported(uint32_t event_id, int battery = -1) const + { + return std::any_of(_events.begin(), _events.end(), [&](const event_s & event) { + return (event.id == event_id) && ((battery < 0) || (event.arguments[5] == battery)); + }); } static uORB::PublicationMulti _battery_pubs[kBatteryCount]; failsafe_flags_s _failsafe_flags{}; bool _can_arm{false}; BatteryChecks _check; + uORB::Subscription _event_sub{ORB_ID(event)}; + std::vector _events; }; uORB::PublicationMulti BatteryChecksTest::_battery_pubs[kBatteryCount] { @@ -166,3 +201,58 @@ TEST_F(BatteryChecksTest, DisconnectedPackDoesNotHideAnotherPacksEmergency) runCheck(true); EXPECT_EQ(_failsafe_flags.battery_warning, battery_status_s::WARNING_EMERGENCY); } + +// a battery without a configured cell count has an unknown state of charge, which still counts as an emergency, +// and arming names the parameter of the BATn index rather than the topic instance +TEST_F(BatteryChecksTest, UnknownChargeWithoutCellCountNamesTheParameter) +{ + publish(0, battery_status_s::WARNING_EMERGENCY, true, -1.f, 0, battery_status_s::SOURCE_POWER_MODULE, 2); + runCheck(false); + EXPECT_EQ(_failsafe_flags.battery_warning, battery_status_s::WARNING_EMERGENCY); + EXPECT_FALSE(_can_arm); + EXPECT_TRUE(reported(events::ID("check_battery_cell_count_unknown"), 2)); + EXPECT_FALSE(reported(events::ID("check_battery_charge_unknown"))); + + publish(0, battery_status_s::WARNING_NONE, true, 0.9f, 3, battery_status_s::SOURCE_POWER_MODULE, 2); + runCheck(false); + EXPECT_TRUE(_can_arm); + EXPECT_FALSE(reported(events::ID("check_battery_cell_count_unknown"))); +} + +// an external battery without a charge blocks arming without a warning, so a single unknown value in flight +// doesn't latch a failsafe, and a cell count doesn't make the charge known +TEST_F(BatteryChecksTest, ExternalBatteryWithoutChargeBlocksArming) +{ + publish(1, battery_status_s::WARNING_NONE, true, -1.f, 1, battery_status_s::SOURCE_EXTERNAL, 0); + runCheck(false); + EXPECT_EQ(_failsafe_flags.battery_warning, battery_status_s::WARNING_NONE); + EXPECT_FALSE(_can_arm); + EXPECT_TRUE(reported(events::ID("check_battery_charge_unknown"), 2)); + EXPECT_FALSE(reported(events::ID("check_battery_cell_count_unknown"))); +} + +// an unknown state of charge still counts as below the configured arming threshold +TEST_F(BatteryChecksTest, UnknownChargeIsBelowArmThreshold) +{ + float arm_bat_min = 0.2f; + param_set(param_find("COM_ARM_BAT_MIN"), &arm_bat_min); + + publish(0, battery_status_s::WARNING_NONE, true, -1.f, 4, battery_status_s::SOURCE_EXTERNAL); + runCheck(false); + EXPECT_FALSE(_can_arm); + EXPECT_TRUE(reported(events::ID("check_battery_low"))); + + param_reset(param_find("COM_ARM_BAT_MIN")); +} + +// the unknown charge failure only matters for arming, so it isn't reported in flight +TEST_F(BatteryChecksTest, UnknownChargeIsNotReportedWhileArmed) +{ + runCheck(false); + runCheck(true); + + publish(1, battery_status_s::WARNING_NONE, true, -1.f, 1, battery_status_s::SOURCE_EXTERNAL, 0); + runCheck(true); + EXPECT_FALSE(reported(events::ID("check_battery_charge_unknown"))); + EXPECT_EQ(_failsafe_flags.battery_warning, battery_status_s::WARNING_NONE); +} diff --git a/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.cpp b/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.cpp index 175e115efcf..76e6ef652de 100644 --- a/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.cpp +++ b/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.cpp @@ -153,6 +153,11 @@ void BatteryChecks::checkAndReport(const Context &context, Report &reporter) worst_battery_remaining = battery.remaining; } + // arming failures have no effect while armed, so don't repeat the status text in flight + if (!context.isArmed() && (battery.remaining < 0.f)) { + unknownChargeCheck(reporter, battery, index); + } + if (battery.timestamp < oldest_update) { oldest_update = battery.timestamp; } @@ -305,6 +310,51 @@ void BatteryChecks::checkAndReport(const Context &context, Report &reporter) _last_armed = context.isArmed(); } +void BatteryChecks::unknownChargeCheck(Report &reporter, const battery_status_s &battery, int index) +{ + // an unknown state of charge must block arming, the warning it gets is up to the source + // the battery library estimates the charge from the cell count, and sets the id to the BATn index + const bool estimated = (battery.source == battery_status_s::SOURCE_POWER_MODULE) + || (battery.source == battery_status_s::SOURCE_ESCS); + + if (estimated) { + /* EVENT + * @description + * The state of charge can't be estimated without knowing the number of cells. + * + * + * Configure the cell count with BAT1_N_CELLS (or the respective battery's parameter). + * + */ + reporter.armingCheckFailure(NavModes::All, health_component_t::battery, + events::ID("check_battery_cell_count_unknown"), + events::Log::Error, "Battery {1}: charge unknown, set BAT{1}_N_CELLS", battery.id); + + if (reporter.mavlink_log_pub()) { + mavlink_log_critical(reporter.mavlink_log_pub(), "Preflight Fail: Battery %u charge unknown, set BAT%u_N_CELLS\t", + battery.id, battery.id); + } + + } else { + /* EVENT + * @description + * The battery doesn't report its state of charge. + * + * + * A DroneCAN battery with UAVCAN_SUB_BAT set to filter the data is estimated from its cell count: + * configure it with BAT1_N_CELLS (or the respective battery's parameter). + * + */ + reporter.armingCheckFailure(NavModes::All, health_component_t::battery, + events::ID("check_battery_charge_unknown"), + events::Log::Error, "Battery {1}: charge unknown", index + 1); + + if (reporter.mavlink_log_pub()) { + mavlink_log_critical(reporter.mavlink_log_pub(), "Preflight Fail: Battery %i charge unknown\t", index + 1); + } + } +} + void BatteryChecks::rtlEstimateCheck(const Context &context, Report &reporter, float worst_battery_time_s) { rtl_time_estimate_s rtl_time_estimate; diff --git a/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.hpp b/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.hpp index a6fbf4650da..c1ae26963e0 100644 --- a/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.hpp +++ b/src/modules/commander/HealthAndArmingChecks/checks/batteryCheck.hpp @@ -50,6 +50,7 @@ public: private: void rtlEstimateCheck(const Context &context, Report &reporter, float worst_battery_time_s); + void unknownChargeCheck(Report &reporter, const battery_status_s &battery, int index); uORB::SubscriptionMultiArray _battery_status_subs{ORB_ID::battery_status}; uORB::Subscription _rtl_time_estimate_sub{ORB_ID(rtl_time_estimate)}; diff --git a/src/modules/esc_battery/EscBattery.cpp b/src/modules/esc_battery/EscBattery.cpp index e15b9f7d833..4a0362ec9b4 100644 --- a/src/modules/esc_battery/EscBattery.cpp +++ b/src/modules/esc_battery/EscBattery.cpp @@ -91,6 +91,12 @@ EscBattery::Run() } const uint8_t online_esc_count = math::countSetBits(esc_status.esc_online_flags); + + // without an online ESC there is no voltage to average + if (online_esc_count == 0) { + return; + } + float average_voltage_v = 0.0f; float total_current_a = 0.0f; diff --git a/src/modules/mavlink/mavlink_receiver.cpp b/src/modules/mavlink/mavlink_receiver.cpp index a077eb271ce..7625f7fa1ee 100644 --- a/src/modules/mavlink/mavlink_receiver.cpp +++ b/src/modules/mavlink/mavlink_receiver.cpp @@ -2087,6 +2087,7 @@ MavlinkReceiver::handle_message_battery_status(mavlink_message_t *msg) battery_status.temperature = (battery_mavlink.temperature == INT16_MAX) ? NAN : (float)battery_mavlink.temperature / 100.0f; battery_status.connected = true; + battery_status.source = battery_status_s::SOURCE_EXTERNAL; battery_status.time_remaining_s = (battery_mavlink.time_remaining > 0) ? static_cast(battery_mavlink.time_remaining) : NAN; // Set the battery warning based on remaining charge, if available.