Commit ce4638ed71abe9aaf53d8d17e55ae34cb8c47445

Authored by Miguel Barão
0 parents
Exists in master

Initial commit

battery.py first examples in python (very slow)
battery.c uses the freebsd sysctl system calls to get the battery state
which is much faster.
Showing 3 changed files with 85 additions and 0 deletions   Show diff stats
battery 0 → 100755
No preview for this file type
battery.c 0 → 100644
  1 +++ a/battery.c
@@ -0,0 +1,46 @@ @@ -0,0 +1,46 @@
  1 +#include <stdio.h>
  2 +#include <stdlib.h>
  3 +#include <sys/types.h>
  4 +#include <sys/sysctl.h>
  5 +
  6 +const char *bat_icons[] = {
  7 + "\uf58d", /* 0% */
  8 + "\uf579",
  9 + "\uf57a",
  10 + "\uf57b",
  11 + "\uf57c",
  12 + "\uf57d", /* 50% */
  13 + "\uf57e",
  14 + "\uf57f",
  15 + "\uf580",
  16 + "\uf581",
  17 + "\uf578", /* 100% */
  18 +};
  19 +
  20 +int main() {
  21 + int life, state;
  22 + size_t len = sizeof(int);
  23 +
  24 + if (sysctlbyname("hw.acpi.battery.state", &state, &len, NULL, 0) ||
  25 + sysctlbyname("hw.acpi.battery.life", &life, &len, NULL, 0)) {
  26 + perror("No battery?");
  27 + exit(EXIT_FAILURE);
  28 + }
  29 +
  30 + switch (state) {
  31 + case 0: /* fully charged */
  32 + printf("\uf583 Full");
  33 + break;
  34 + case 1: /* discharging */
  35 + printf("%s %d%%\n", bat_icons[life / 10], life);
  36 + break;
  37 + case 2: /* charging */
  38 + printf("\uf583 %d\n", life);
  39 + break;
  40 + case 7: /* disconnected */
  41 + printf("\uf590 Disconnected");
  42 + break;
  43 + }
  44 +
  45 + return 0;
  46 +}
battery.py 0 → 100755
  1 +++ a/battery.py
@@ -0,0 +1,39 @@ @@ -0,0 +1,39 @@
  1 +#!/usr/bin/env python3
  2 +
  3 +import subprocess
  4 +
  5 +bat_icons = [
  6 + "\uf58d", # 0%
  7 + "\uf579",
  8 + "\uf57a",
  9 + "\uf57b",
  10 + "\uf57c",
  11 + "\uf57d", # 50%
  12 + "\uf57e",
  13 + "\uf57f",
  14 + "\uf580",
  15 + "\uf581",
  16 + "\uf578", # 100%
  17 +]
  18 +# bat_alert = f582
  19 +# bat_plus = f58e
  20 +# bat_minus = f58b
  21 +# bat_unknown = f590
  22 +# bat_charging = f583
  23 +
  24 +out = str(
  25 + subprocess.run(["sysctl", "hw.acpi.battery"], capture_output=True).stdout, "UTF-8"
  26 +)
  27 +bat = dict(line.split(": ") for line in out.splitlines())
  28 +
  29 +state = int(bat["hw.acpi.battery.state"])
  30 +life = int(bat["hw.acpi.battery.life"])
  31 +
  32 +if state == 0: # fully charged
  33 + print(f"\uf583 Full")
  34 +elif state == 1: # discharging
  35 + print(f"{bat_icons[life // 10]} {life}%")
  36 +elif state == 2: # charging
  37 + print(f"\uf583 {life}%")
  38 +elif state == 7: # disconnected
  39 + print("\uf590 Disconnected")