diff options
author | clsr <clsr@clsr.net> | 2017-04-26 10:41:48 +0200 |
---|---|---|
committer | clsr <clsr@clsr.net> | 2017-04-26 10:41:48 +0200 |
commit | 262fd581a79f61ee99b018938c480cf318ba6bd6 (patch) | |
tree | 7d3c2250563f626f616746516560dcc6c5151880 /dwmclock.c | |
parent | e7a5b19c0ba06e12b0137a7ce5e65a15135d9977 (diff) | |
download | dwmclock-262fd581a79f61ee99b018938c480cf318ba6bd6.tar.gz dwmclock-262fd581a79f61ee99b018938c480cf318ba6bd6.zip |
Deduplicate file reading code and add battery charging indicatorv1.1.0
Diffstat (limited to 'dwmclock.c')
-rw-r--r-- | dwmclock.c | 57 |
1 files changed, 40 insertions, 17 deletions
@@ -4,6 +4,7 @@ #include <signal.h> #include <stdio.h> #include <stdlib.h> +#include <string.h> #include <time.h> #include <unistd.h> #include <X11/Xlib.h> @@ -12,29 +13,47 @@ int stop = 0; #ifdef BATTERY -int getnum(char *fn) -{ - char buf[1024]; +char *readfile(char *buf, size_t len, const char *fn) { FILE *f; - int len; + size_t n; f = fopen(fn, "r"); if (!f) { - return -1; + return NULL; } - len = fread(buf, 1, 1023, f); + n = fread(buf, 1, len-1, f); if (ferror(f)) { - return -1; + return NULL; } fclose(f); - if (len > 1022 || len < 1) { - return -1; + if (n >= len-1 || n < 1) { + return NULL; } - buf[1023] = '\0'; + buf[n] = '\0'; + + return buf; +} - return atoi(buf); +int getnum(const char *fn) { + char buf[1024]; + + if (readfile(buf, sizeof(buf), fn)) { + return atoi(buf); + } + return -1; +} + +#ifdef CHARGING +int charging(void) { + char buf[1024]; + + if (readfile(buf, sizeof(buf), STATUS)) { + return !strcmp(buf, CHARGING); + } + return 0; } -#endif +#endif /* CHARGING */ +#endif /* BATTERY */ void handler(int sig) { @@ -50,10 +69,11 @@ int main(void) char name[8 + 9]; /* (p)pp.pp% hh:mm:ss\0 */ char *perc = name; char *clock = name + 8; + char sign = '%'; #else char name[9]; /* hh:mm:ss\0 */ char *clock = name; -#endif +#endif /* BATTERY */ struct sigaction act; Display *disp; int screen; @@ -73,7 +93,7 @@ int main(void) for (i=0; !stop; ++i) { #else while (!stop) { -#endif +#endif /* BATTERY */ if (!disp) { puts("Cannot open display!"); return 1; @@ -84,6 +104,9 @@ int main(void) if (i % (BAT_REFRESH_SECONDS) == 0) { curr = getnum(ENERGY_NOW) * MUL; max = getnum(ENERGY_FULL); +#ifdef CHARGING + sign = charging() ? '+' : '%'; +#endif /* CHARGING */ if (curr < 0 || max < 1) { a = b = -1; } else { @@ -98,12 +121,12 @@ int main(void) } else if (a < 0 || a > 999999 || b < 0 || b > 99) { snprintf(perc, 8, "INVALID"); } else if (a > 999) { - snprintf(perc, 8, "%6lld%%", a); + snprintf(perc, 8, "%6lld%c", a, sign); } else { - snprintf(perc, 8, "%3lld.%02lld%%", a, b); + snprintf(perc, 8, "%3lld.%02lld%c", a, b, sign); } perc[7] = ' '; -#endif +#endif /* BATTERY */ now = time(NULL); tm = localtime(&now); |