utils

tiny programs I use on my system
Download | Log | Files | Refs | README | LICENSE

commit d3cdda678aaaee5540f8ff2e80d9d5c2d2ba44ef
parent b3d82834656596e9c6d4cd73600d7ef133731809
Author: amrfti <andrew@kloet.net>
Date:   Thu, 10 Jul 2025 11:12:10 -0400

add sb-battery

Diffstat:
MMakefile | 5++++-
MREADME.md | 2++
Asb-battery.c | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 58 insertions(+), 1 deletion(-)

diff --git a/Makefile b/Makefile @@ -2,7 +2,7 @@ CC = cc CFLAGS = -Wall -Wextra -O3 CURL_LIBS = -lcurl -SOURCES = sb-cpu.c sb-date.c sb-memory.c sb-time.c sb-weather.c +SOURCES = sb-cpu.c sb-date.c sb-memory.c sb-time.c sb-weather.c sb-battery.c EXECUTABLES = $(SOURCES:.c=) @@ -23,6 +23,9 @@ sb-memory: sb-memory.c sb-time: sb-time.c $(CC) $(CFLAGS) $< -o $@ +sb-battery: sb-battery.c + $(CC) $(CFLAGS) $< -o $@ + clean: rm -f $(EXECUTABLES) diff --git a/README.md b/README.md @@ -12,4 +12,6 @@ $ ./sb-time 10:10am $ ./sb-date Jul 10 2025 +$ ./sb-battery +Bat: +98% ``` diff --git a/sb-battery.c b/sb-battery.c @@ -0,0 +1,52 @@ +#include <dirent.h> +#include <stdio.h> +#include <string.h> + +int main() { + DIR *dir = opendir("/sys/class/power_supply"); + if (!dir) + return 1; + + struct dirent *entry; + int total = 0, count = 0, charging = 0; + + // Iterate every battery + while ((entry = readdir(dir))) { + if (strncmp(entry->d_name, "BAT", 3) != 0) + continue; + + char path[512]; + FILE *fp; + int capacity; + char status[20]; + + // Read current charge value + snprintf(path, sizeof(path), "/sys/class/power_supply/%s/capacity", + entry->d_name); + fp = fopen(path, "r"); + if (!fp) + return 1; + if (fscanf(fp, "%d", &capacity) == 1) { + total += capacity; + count++; + fclose(fp); + } + + // Check if charging + snprintf(path, sizeof(path), "/sys/class/power_supply/%s/status", + entry->d_name); + fp = fopen(path, "r"); + if (!fp) + return 1; + if (fscanf(fp, "%19s", status) == 1) { + if (strncmp(status, "Charging", 8) == 0) + charging = 1; + fclose(fp); + } + } + closedir(dir); + + if (count > 0) + printf("Bat: %s%d%%\n", charging ? "+" : "", total / count); + return 0; +}