--- a/src/shared/sleep-config.c +++ b/src/shared/sleep-config.c @@ -42,6 +42,7 @@ #include "string-util.h" #include "strv.h" #include "time-util.h" +#include "udev-util.h" #define BATTERY_LOW_CAPACITY_LEVEL 5 #define DISCHARGE_RATE_FILEPATH "/var/lib/systemd/sleep/battery_discharge_percentage_rate_per_hour" @@ -196,8 +197,8 @@ static int read_battery_capacity_percent return battery_capacity; } -/* If battery percentage capacity is <= 5%, return success */ -int battery_is_low(void) { +/* 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; sd_device *dev; int r; @@ -206,6 +207,12 @@ int battery_is_low(void) { * or Normal in case ACPI is not working properly. In case of no battery * 0 will be returned and system will be suspended for 1st cycle then hibernated */ + r = on_ac_power(); + if (r < 0) + log_debug_errno(r, "Failed to check if the system is running on AC, assuming it is not: %m"); + if (r > 0) + return false; + r = battery_enumerator_new(&e); if (r < 0) return log_debug_errno(r, "Failed to initialize battery enumerator: %m"); --- a/src/shared/sleep-config.h +++ b/src/shared/sleep-config.h @@ -60,7 +60,7 @@ int find_hibernate_location(HibernateLoc int can_sleep(SleepOperation operation); int can_sleep_disk(char **types); int can_sleep_state(char **types); -int battery_is_low(void); +int battery_is_discharging_and_low(void); int get_total_suspend_interval(Hashmap *last_capacity, usec_t *ret); int fetch_batteries_capacity_by_name(Hashmap **ret_current_capacity); int get_capacity_by_name(Hashmap *capacities_by_name, const char *name); --- a/src/sleep/sleep.c +++ b/src/sleep/sleep.c @@ -274,7 +274,7 @@ static int custom_timer_suspend(const Sl hibernate_timestamp = usec_add(now(CLOCK_BOOTTIME), sleep_config->hibernate_delay_usec); - while (battery_is_low() == 0) { + while (battery_is_discharging_and_low() == 0) { _cleanup_hashmap_free_ Hashmap *last_capacity = NULL, *current_capacity = NULL; _cleanup_close_ int tfd = -EBADF; struct itimerspec ts = {};