]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
battery-util: be more careful when determining whether we are in a low battery state
authorLennart Poettering <lennart@poettering.net>
Mon, 5 Jun 2023 10:12:03 +0000 (12:12 +0200)
committerLennart Poettering <lennart@poettering.net>
Mon, 5 Jun 2023 10:20:41 +0000 (12:20 +0200)
Let's avoid assuming a low battery battery state if in doubt. That
means, handle errors reading battery state gracefully.

src/shared/battery-util.c

index b11b6dc98960cc8e38b7f5fa037a2f5d028575f1..948a5e3b9d6a4216f8a63ed1c0647a6e8b97c82b 100644 (file)
@@ -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;
 }