add sb-battery
This commit is contained in:
52
sb-battery.c
Normal file
52
sb-battery.c
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user