From: Lennart Poettering Date: Mon, 5 Jun 2023 10:12:03 +0000 (+0200) Subject: battery-util: be more careful when determining whether we are in a low battery state X-Git-Tag: v254-rc1~285^2~1 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=c41e3605ec2f5c1d3040aa3a5fd57b9aee08c198;p=thirdparty%2Fsystemd.git battery-util: be more careful when determining whether we are in a low battery state Let's avoid assuming a low battery battery state if in doubt. That means, handle errors reading battery state gracefully. --- diff --git a/src/shared/battery-util.c b/src/shared/battery-util.c index b11b6dc9896..948a5e3b9d6 100644 --- a/src/shared/battery-util.c +++ b/src/shared/battery-util.c @@ -233,6 +233,7 @@ int battery_read_capacity_percentage(sd_device *dev) { /* If a battery whose percentage capacity is <= 5% exists, and we're not on AC power, return success */ int battery_is_discharging_and_low(void) { _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL; + bool unsure = false, found_low = false; sd_device *dev; int r; @@ -250,9 +251,29 @@ int battery_is_discharging_and_low(void) { if (r < 0) return log_debug_errno(r, "Failed to initialize battery enumerator: %m"); - FOREACH_DEVICE(e, dev) - if (battery_read_capacity_percentage(dev) > BATTERY_LOW_CAPACITY_LEVEL) + FOREACH_DEVICE(e, dev) { + int level; + + level = battery_read_capacity_percentage(dev); + if (level < 0) { + unsure = true; + continue; + } + + if (level > BATTERY_LOW_CAPACITY_LEVEL) /* Found a charged battery */ return false; - return true; + found_low = true; + } + + /* If we found a battery whose state we couldn't read, don't assume we are in low battery state */ + if (unsure) + return false; + + /* Found no charged battery, but did find low batteries */ + if (found_low) + return true; + + /* Found neither charged nor low batteries? let's return that we aren't on low battery state */ + return false; }