Commit: eb6f5c36a61227fcf7fb14381521bd913ada29b6
Parent: d6eb67da974395d992a394775143f3913625fe68
Author: opask
Date: Sun, 13 Jan 2019 00:19:08 -0700
add batinfo() for linux
Diffstat:
5 files changed, 65 insertions(+), 2 deletions(-)
diff --git a/config.def.h b/config.def.h
@@ -9,3 +9,7 @@ static const char *timefmt = "%R";
output is the output from that specific card you want the vol from */
static const char *alsacard = "default";
static const char *alsaoutput = "Speaker";
+
+/* main battery in system */
+/* found in /sys/class/power_supply/ */
+static const char *bat = "BAT0";
diff --git a/linux.c b/linux.c
@@ -1,3 +1,6 @@
+#include <limits.h>
+#include <stdio.h>
+
#include "status.h"
#if defined(__linux__)
@@ -34,4 +37,41 @@ getvol(const char *card, const char *output)
return (int)vol;
}
+char *
+batinfo(const char *bat)
+{
+ int perc;
+ unsigned long power_now, energy_now, h, m;
+ double timeleft;
+ char path[PATH_MAX], state[12];
+
+ snprintf(path, sizeof(path), "/sys/class/power_supply/%s/capacity", bat);
+ if (pscanf(path, "%d", &perc) != 1)
+ perc = 0;
+
+ snprintf(path, sizeof(path), "/sys/class/power_supply/%s/status", bat);
+ if (pscanf(path, "%12s", &state) != 1)
+ snprintf(state, sizeof(state), "Unknown");
+
+ if (!strcmp(state, "Discharging")) {
+ snprintf(path, sizeof(path),
+ "/sys/class/power_supply/%s/power_now", bat);
+ if (pscanf(path, "%lu", &power_now) != 1)
+ power_now = 1;
+
+ snprintf(path, sizeof(path),
+ "/sys/class/power_supply/%s/energy_now", bat);
+ if (pscanf(path, "%lu", &energy_now) != 1)
+ energy_now = 0;
+
+ timeleft = (double)energy_now / (double)power_now;
+ h = timeleft;
+ m = (timeleft - (double)h) * 60;
+
+ return smprintf("%d%% (%d:%02d)", perc, h, m);
+ }
+
+ return smprintf("%d%% (%s)", perc, state);
+}
+
#endif
diff --git a/openbsd.c b/openbsd.c
@@ -14,7 +14,7 @@ getvol(const char *card, const char *output)
}
char *
-batinfo(void)
+batinfo(const char *bat)
{
struct apm_power_info pi;
int fd;
diff --git a/status.c b/status.c
@@ -54,6 +54,24 @@ smprintf(const char *fmt, ...)
return ret;
}
+int
+pscanf(const char *path, const char *fmt, ...)
+{
+ FILE *fp;
+ va_list ap;
+ int ret;
+
+ if (!(fp = fopen(path, "r")))
+ return -1;
+
+ va_start(ap, fmt);
+ ret = vfscanf(fp, fmt, ap);
+ va_end(ap);
+ fclose(fp);
+
+ return (ret == EOF) ? -1 : ret;
+}
+
static void
setstatus(char *str)
{
diff --git a/status.h b/status.h
@@ -1,5 +1,6 @@
void die(const char *errstr, ...);
char *smprintf(const char *fmt, ...);
+int pscanf(const char *path, const char *fmt, ...);
int getvol(const char *card, const char *output);
-char *batinfo(void);
+char *batinfo(const char *bat);