diff options
author | Lennart Poettering <lennart@poettering.net> | 2023-06-05 12:12:03 +0200 |
---|---|---|
committer | Lennart Poettering <lennart@poettering.net> | 2023-06-05 12:20:41 +0200 |
commit | c41e3605ec2f5c1d3040aa3a5fd57b9aee08c198 (patch) | |
tree | a745fd51d1ae482589995fa4766e610624b1f6e0 /src/shared | |
parent | battery-util: move battery_is_discharging_and_low() to battery-util.[ch] (diff) | |
download | systemd-c41e3605ec2f5c1d3040aa3a5fd57b9aee08c198.tar.xz systemd-c41e3605ec2f5c1d3040aa3a5fd57b9aee08c198.zip |
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.
Diffstat (limited to 'src/shared')
-rw-r--r-- | src/shared/battery-util.c | 27 |
1 files changed, 24 insertions, 3 deletions
diff --git a/src/shared/battery-util.c b/src/shared/battery-util.c index b11b6dc989..948a5e3b9d 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; } |