Skip to content

Instantly share code, notes, and snippets.

@clsr
Created August 26, 2014 18:42
Show Gist options
  • Save clsr/50eb01133870c43b7bf0 to your computer and use it in GitHub Desktop.
Save clsr/50eb01133870c43b7bf0 to your computer and use it in GitHub Desktop.
Show a clock and battery percentage in X root tile (for dwm)
#define _GNU_SOURCE
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <X11/Xlib.h>
#define ENERGY_FULL "/sys/class/power_supply/BAT0/energy_full"
#define ENERGY_NOW "/sys/class/power_supply/BAT0/energy_now"
#define BAT_REFRESH_SECONDS 60
int stop = 0;
#ifdef BATTERY
int getnum(char *fn)
{
char buf[1024];
FILE *f;
int len;
f = fopen(fn, "r");
len = fread(buf, 1, 1023, f);
if (ferror(f)) {
return -1;
}
fclose(f);
if (len > 1022 || len < 1) {
return -1;
}
buf[1023] = '\0';
return atoi(buf);
}
#endif
void handler(int sig)
{
stop = sig;
}
int main(void)
{
struct tm *tm;
time_t now;
#ifdef BATTERY
int curr, max, a, b, i;
char name[8 + 9]; /* (p)pp.pp% hh:mm:ss\0 */
char *perc = name;
char *clock = name + 8;
#else
char name[9]; /* hh:mm:ss\0 */
char *clock = name;
#endif
struct sigaction act;
Display *disp;
int screen;
Window root;
act.sa_handler = handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGHUP, &act, NULL);
sigaction(SIGINT, &act, NULL);
sigaction(SIGQUIT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
#ifdef BATTERY
for (i=0; !stop; ++i) {
#else
while (!stop) {
#endif
disp = XOpenDisplay(NULL);
if (!disp) {
puts("Cannot open display!");
return 1;
}
screen = DefaultScreen(disp);
root = RootWindow(disp, screen);
#ifdef BATTERY
if (i % (BAT_REFRESH_SECONDS) == 0) {
curr = getnum(ENERGY_NOW) / 1000;
max = getnum(ENERGY_FULL) / 1000;
if (curr < 0 || max < 1) {
a = b = -1;
} else {
a = (curr * 10000) / max;
b = a % 100;
a /= 100;
}
}
if (a < 0 || b < 0) {
snprintf(perc, 9, "NO BAT ");
} else if (a < 0 || a > 999999 || b < 0 || b > 99) {
snprintf(perc, 8, "INVALID", a, b);
} else if (a > 999) {
snprintf(perc, 8, "%6d%%", a);
} else if (a > 99) {
snprintf(perc, 8, "%3d.%02d%%", a, b);
} else {
snprintf(perc, 8, " %2d.%02d%%", a, b);
}
perc[7] = ' ';
#endif
now = time(NULL);
tm = localtime(&now);
strftime(clock, 9, "%H:%M:%S", tm);
XStoreName(disp, root, name);
XCloseDisplay(disp);
sleep(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment