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>
This commit is contained in:
Sofian ElmotiemandSofian Elmotiem authored and GitHub committed 2026-10-29 18:35:28 -06:00
1 parent 026e64b241
commit e58250d5b5
10 files changed
+285 -5

No files matched your search

@@ -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)) {
+128
View File
@@ -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 <gtest/gtest.h>
#include "battery.h"
#include <px4_platform_common/param.h>
// 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);
}
+1
View File
@@ -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)
+4 -3
View File
@@ -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;
@@ -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);
@@ -33,12 +33,17 @@
#include <gtest/gtest.h>
#include <algorithm>
#include <vector>
#include "checks/batteryCheck.hpp"
#include <drivers/drv_hrt.h>
#include <px4_platform_common/param.h>
#include <uORB/PublicationMulti.hpp>
#include <uORB/Subscription.hpp>
#include <uORB/topics/battery_status.h>
#include <uORB/topics/event.h>
// 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_status_s> _battery_pubs[kBatteryCount];
failsafe_flags_s _failsafe_flags{};
bool _can_arm{false};
BatteryChecks _check;
uORB::Subscription _event_sub{ORB_ID(event)};
std::vector<event_s> _events;
};
uORB::PublicationMulti<battery_status_s> 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);
}
@@ -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.
*
* <profile name="dev">
* Configure the cell count with <param>BAT1_N_CELLS</param> (or the respective battery's parameter).
* </profile>
*/
reporter.armingCheckFailure<uint8_t>(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.
*
* <profile name="dev">
* A DroneCAN battery with <param>UAVCAN_SUB_BAT</param> set to filter the data is estimated from its cell count:
* configure it with <param>BAT1_N_CELLS</param> (or the respective battery's parameter).
* </profile>
*/
reporter.armingCheckFailure<uint8_t>(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;
@@ -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_s, battery_status_s::MAX_INSTANCES> _battery_status_subs{ORB_ID::battery_status};
uORB::Subscription _rtl_time_estimate_sub{ORB_ID(rtl_time_estimate)};
+6
View File
@@ -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;
+1
View File
@@ -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<float>(battery_mavlink.time_remaining) : NAN;
// Set the battery warning based on remaining charge, if available.