battery.c 954 Bytes
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>

const char *bat_icons[] = {
    "\uf58d",  /* 0% */
    "\uf579",
    "\uf57a",
    "\uf57b",
    "\uf57c",
    "\uf57d",  /* 50% */
    "\uf57e",
    "\uf57f",
    "\uf580",
    "\uf581",
    "\uf578",  /* 100% */
};

int main() {
  int life, state;
  size_t len = sizeof(int);

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

  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");
  }

  return EXIT_SUCCESS;
}