1
1
mirror of https://github.com/systemd/systemd-stable.git synced 2025-03-06 12:58:22 +03:00

sleep: check if we're on AC power before checking battery capacity

Before this commit, battery_is_low() returns
true if there's no battery on the system.
It's now modified to check if the system is
on AC power first, and returns false early
if that's the case.

Fixes #26492

(cherry picked from commit e0b3a70fabb871bf55678e9e177445b1df2aee88)
This commit is contained in:
Mike Yuan 2023-02-20 20:12:19 +08:00 committed by Zbigniew Jędrzejewski-Szmek
parent 452cad62c8
commit 1947b9939c
3 changed files with 11 additions and 4 deletions

View File

@ -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_percentage(sd_device *dev) {
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");

View File

@ -60,7 +60,7 @@ int find_hibernate_location(HibernateLocation **ret_hibernate_location);
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);

View File

@ -274,7 +274,7 @@ static int custom_timer_suspend(const SleepConfig *sleep_config) {
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 = {};