add sb-battery

This commit is contained in:
2025-07-10 11:12:10 -04:00
parent 666b24d698
commit 9f3f4a83b5
3 changed files with 58 additions and 1 deletions

View File

@@ -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)

View File

@@ -12,4 +12,6 @@ $ ./sb-time
10:10am
$ ./sb-date
Jul 10 2025
$ ./sb-battery
Bat: +98%
```

52
sb-battery.c Normal file
View File

@@ -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;
}