battery.c 1.05 KB
#ifndef __FreeBSD__
  #error Only works on FreeBSD
#endif

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>

const char *bat_icons1[] = {
    "󰂎",  /* 0% */
    "󰁺",
    "󰁻",
    "󰁼",
    "󰁽",
    "󰁾",  /* 50% */
    "󰁿",
    "󰂀",
    "󰂁",
    "󰂂",
    "󰁹",  /* 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);
  }

  if (life > 100)
    life = 100;
  else if (life < 0)
    life = 0;

  switch (state) {
  case 0: /* fully charged */
    printf("󰂄 Full");
    break;
  case 1: /* discharging */
    printf("%s %d%%\n", bat_icons1[life / 10], life);
    break;
  case 2: /* charging */
    printf("󰂄 %d%%\n", life);
    break;
  case 7: /* disconnected */
    printf("󰂑");
    break;
  default: /* unknown code */
    printf(" unknown battery code");
  }

  return EXIT_SUCCESS;
}