Commit: e6aa53853a59d174594f372fc7a435f8fc0dca53
Parent: a92255b1af58b9ee1a1f474e420711a251995858
Author: Randy Palamar
Date: Thu, 19 Dec 2024 18:54:42 -0700
linux/battery: use energy_now and energy_full to calculate capacity
capacity isn't always present but is easily calculated.
Additionally the types of all those read values need to be signed
since some devices will use negative power to indicate
discharging.
Diffstat:
2 files changed, 17 insertions(+), 15 deletions(-)
diff --git a/blocks/linux/battery.c b/blocks/linux/battery.c
@@ -15,36 +15,37 @@ batinfo(struct Block *b)
char *pre = ba->pre ? ba->pre : "";
char *suf = ba->suf ? ba->suf : "";
char path[PATH_MAX], state[12];
- int perc, s;
- unsigned long power_now, energy_now, h, m;
+ int s, perc, h, m;
+ long power_now, energy_now, energy_full;
double timeleft;
- snprintf(path, sizeof(path), "/sys/class/power_supply/%s/capacity", ba->bat);
- if (pscanf(path, "%d", &perc) != 1)
- perc = 0;
+ snprintf(path, sizeof(path), "/sys/class/power_supply/%s/energy_full", ba->bat);
+ if (pscanf(path, "%ld", &energy_full) != 1)
+ energy_full = 1;
+ snprintf(path, sizeof(path), "/sys/class/power_supply/%s/energy_now", ba->bat);
+ if (pscanf(path, "%ld", &energy_now) != 1)
+ energy_now = 0;
+
+ perc = (100 * energy_now / (double)energy_full);
s = perc < ba->thres;
snprintf(path, sizeof(path), "/sys/class/power_supply/%s/status", ba->bat);
if (pscanf(path, "%12s", &state) != 1)
snprintf(state, sizeof(state), "Unknown");
+ /* NOTE(rnp): proper devices use negative power to indicate discharging but that
+ * is not always the case. The status string can mostly be trusted */
if (!strcmp(state, "Discharging")) {
- snprintf(path, sizeof(path),
- "/sys/class/power_supply/%s/power_now", ba->bat);
- if (pscanf(path, "%lu", &power_now) != 1)
+ snprintf(path, sizeof(path), "/sys/class/power_supply/%s/power_now", ba->bat);
+ if (pscanf(path, "%ld", &power_now) != 1)
power_now = 1;
- snprintf(path, sizeof(path),
- "/sys/class/power_supply/%s/energy_now", ba->bat);
- if (pscanf(path, "%lu", &energy_now) != 1)
- energy_now = 0;
-
- timeleft = (double)energy_now / (double)power_now;
+ timeleft = (double)energy_now / (double)ABS(power_now);
h = timeleft;
m = (timeleft - (double)h) * 60;
- snprintf(buf, sizeof(buf), "%s%d%% (%lu:%02lu)%s", s ? pre : "",
+ snprintf(buf, sizeof(buf), "%s%d%% (%d:%02d)%s", s ? pre : "",
perc, h, m, s ? suf : "");
} else {
snprintf(buf, sizeof(buf), "%s%d%% (%s)%s", s ? pre : "", perc,
diff --git a/status.c b/status.c
@@ -7,6 +7,7 @@
#include <unistd.h>
#include <X11/Xlib.h>
+#define ABS(a) ((a) < 0 ? -(a) : (a))
#define LEN(a) (sizeof(a) / sizeof(*a))
#define BLOCKLEN 128
#define BLOCKPAD 4