diff --git a/Makefile b/Makefile index 8984336..803dc1c 100644 --- 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 index 2b0e839..0b379a2 100644 --- 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 new file mode 100644 index 0000000..37f3b6c --- /dev/null +++ b/sb-battery.c @@ -0,0 +1,52 @@ +#include +#include +#include + +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; +}