utils

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

sb-battery.c (1149B)


      1 #include <dirent.h>
      2 #include <stdio.h>
      3 #include <string.h>
      4 
      5 int main() {
      6   DIR *dir = opendir("/sys/class/power_supply");
      7   if (!dir)
      8     return 1;
      9 
     10   struct dirent *entry;
     11   int total = 0, count = 0, charging = 0;
     12 
     13   // Iterate every battery
     14   while ((entry = readdir(dir))) {
     15     if (strncmp(entry->d_name, "BAT", 3) != 0)
     16       continue;
     17 
     18     char path[512];
     19     FILE *fp;
     20     int capacity;
     21     char status[20];
     22 
     23     // Read current charge value
     24     snprintf(path, sizeof(path), "/sys/class/power_supply/%s/capacity",
     25              entry->d_name);
     26     fp = fopen(path, "r");
     27     if (!fp)
     28       return 1;
     29     if (fscanf(fp, "%d", &capacity) == 1) {
     30       total += capacity;
     31       count++;
     32       fclose(fp);
     33     }
     34 
     35     // Check if charging
     36     snprintf(path, sizeof(path), "/sys/class/power_supply/%s/status",
     37              entry->d_name);
     38     fp = fopen(path, "r");
     39     if (!fp)
     40       return 1;
     41     if (fscanf(fp, "%19s", status) == 1) {
     42       if (strncmp(status, "Charging", 8) == 0)
     43         charging = 1;
     44       fclose(fp);
     45     }
     46   }
     47   closedir(dir);
     48 
     49   if (count > 0)
     50     printf("Bat: %s%d%%\n", charging ? "+" : "", total / count);
     51   return 0;
     52 }