diff --git a/battery.c b/battery.c index 1a44745..186812e 100644 --- a/battery.c +++ b/battery.c @@ -1,13 +1,9 @@ -#ifndef __FreeBSD__ - #error Only works on FreeBSD -#endif - #include #include +#include #include -#include -const char *bat_icons[] = { +const char *icon[] = { "\uf58d", /* 0% */ "\uf579", "\uf57a", @@ -21,36 +17,89 @@ const char *bat_icons[] = { "\uf578", /* 100% */ }; -int main() { - int life, state; +typedef enum { + CHARGED = 0, + DISCHARGING = 1, + CHARGING = 2, + DISCONNECTED = 7, +} State; + +#if defined (__linux__) +void battery_state(int *nbats, int bat[], State state[]) { + FILE *fd; + int i=0; + do { + char filename[50], status[50]; + + // get current capacity + sprintf(filename, "/sys/class/power_supply/BAT%d/capacity", i); + fd = fopen(filename, "rb"); + if (fd == NULL) + break; + fscanf(fd, "%d", &bat[i]); + fclose(fd); + // battery status (charging...) + sprintf(filename, "/sys/class/power_supply/BAT%d/status", i); + fd = fopen(filename, "rb"); + fgets(status, 50, fd); + // puts(status); + fclose(fd); + if (!strcmp(status, "Not charging\n")) + state[i] = CHARGED; + else if (!strcmp(status, "Discharging\n")) + state[i] = DISCHARGING; + else if (!strcmp(status, "Charging\n")) + state[i] = CHARGING; + + // next + i++; + } while (1); + *nbats = i; +} +#elif defined (__FreeBSD__) +#include +void battery_state(int *nbats, int bat[], State state[]) { size_t len = sizeof(int); + int state = -1, life = 0; if (sysctlbyname("hw.acpi.battery.state", &state, &len, NULL, 0) || - sysctlbyname("hw.acpi.battery.life", &life, &len, NULL, 0)) { - puts("(no battery)"); - exit(EXIT_FAILURE); - } + sysctlbyname("hw.acpi.battery.life", &life, &len, NULL, 0)) + state[0] = UNKNOWN; + + *nbats = 1; + bat[0] = life; + state[0] = state; +} +#endif + +int main() { + char *color; + int life[2], nbats; + State state[2]; + + battery_state(&nbats, life, state); + for (int i=0; i < nbats; i++) { + + if (life[i] >= 50) color = "colour028"; /* green */ + else if (life[i] >= 25) color = "colour172"; /* yellow */ + else color = "colour088"; /* red */ - if (life > 100) - life = 100; - else if (life < 0) - life = 0; - - switch (state) { - case 0: /* fully charged */ - printf("\uf583 Full"); - break; - case 1: /* discharging */ - printf("%s %d%%\n", bat_icons[life / 10], life); - break; - case 2: /* charging */ - printf("\uf583 %d%%\n", life); - break; - case 7: /* disconnected */ - printf("\uf492"); - break; - default: /* unknown code */ - printf("\uf590"); + switch (state[i]) { + case CHARGED: /* fully charged */ + printf("%s %d%% ", icon[life[i]/10], life[i]); + break; + case DISCHARGING: /* discharging */ + printf("#[fg=%s]%s#[fg=default] %d%% ", color, icon[life[i]/10], life[i]); + break; + case CHARGING: /* charging */ + printf("#[fg=yellow]\uf583#[fg=default] %d%%\n ", life[i]); + break; + case DISCONNECTED: /* disconnected */ + printf("\uf492 "); + break; + default: /* unknown code */ + printf("\uf590 "); + } } return EXIT_SUCCESS; -- libgit2 0.21.2