X-Git-Url: https://git.xinqibao.xyz/slstatus.git/blobdiff_plain/a546d4b585234f66b82e048c2d7cb228b9e7fea4..e213b48122f1f8e8d837053324d9c891a67a38d2:/components/battery.c diff --git a/components/battery.c b/components/battery.c index fa525be..1178f20 100644 --- a/components/battery.c +++ b/components/battery.c @@ -1,5 +1,4 @@ /* See LICENSE file for copyright and license details. */ -#include #include #include @@ -7,13 +6,9 @@ #if defined(__linux__) #include + #include #include - #define CHARGE_NOW "/sys/class/power_supply/%s/charge_now" - #define ENERGY_NOW "/sys/class/power_supply/%s/energy_now" - #define CURRENT_NOW "/sys/class/power_supply/%s/current_now" - #define POWER_NOW "/sys/class/power_supply/%s/power_now" - static const char * pick(const char *bat, const char *f1, const char *f2, char *path, size_t length) @@ -38,8 +33,7 @@ char path[PATH_MAX]; if (esnprintf(path, sizeof(path), - "/sys/class/power_supply/%s/capacity", - bat) < 0) { + "/sys/class/power_supply/%s/capacity", bat) < 0) { return NULL; } if (pscanf(path, "%d", &perc) != 1) { @@ -63,8 +57,7 @@ char path[PATH_MAX], state[12]; if (esnprintf(path, sizeof(path), - "/sys/class/power_supply/%s/status", - bat) < 0) { + "/sys/class/power_supply/%s/status", bat) < 0) { return NULL; } if (pscanf(path, "%12s", state) != 1) { @@ -82,28 +75,34 @@ const char * battery_remaining(const char *bat) { - int charge_now, current_now, m, h; + uintmax_t charge_now, current_now, m, h; double timeleft; char path[PATH_MAX], state[12]; if (esnprintf(path, sizeof(path), - "/sys/class/power_supply/%s/status", - bat) < 0) { + "/sys/class/power_supply/%s/status", bat) < 0) { return NULL; } if (pscanf(path, "%12s", state) != 1) { return NULL; } - if (!pick(bat, CHARGE_NOW, ENERGY_NOW, path, sizeof(path)) || - pscanf(path, "%d", &charge_now) < 0) { + if (!pick(bat, "/sys/class/power_supply/%s/charge_now", + "/sys/class/power_supply/%s/energy_now", path, + sizeof(path)) || + pscanf(path, "%ju", &charge_now) < 0) { return NULL; } if (!strcmp(state, "Discharging")) { - if (!pick(bat, CURRENT_NOW, POWER_NOW, path, + if (!pick(bat, "/sys/class/power_supply/%s/current_now", + "/sys/class/power_supply/%s/power_now", path, sizeof(path)) || - pscanf(path, "%d", ¤t_now) < 0) { + pscanf(path, "%ju", ¤t_now) < 0) { + return NULL; + } + + if (current_now == 0) { return NULL; } @@ -111,7 +110,7 @@ h = timeleft; m = (timeleft - (double)h) * 60; - return bprintf("%dh %dm", h, m); + return bprintf("%juh %jum", h, m); } return "";