Skip to content

Instantly share code, notes, and snippets.

@ramblingenzyme
Last active January 2, 2017 21:50
Show Gist options
  • Save ramblingenzyme/0ea98c14e3eb5a37fc33d0294128cd5b to your computer and use it in GitHub Desktop.
Save ramblingenzyme/0ea98c14e3eb5a37fc33d0294128cd5b to your computer and use it in GitHub Desktop.
inotify battery script
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <fnmatch.h>
#include <sys/inotify.h>
#define BUF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1))
#define FILE_COUNT 3
void battery_status(char *files[FILE_COUNT]) {
int i = 0, temp_i;
double temp_f, capacity;
FILE *fp;
capacity = 0.0;
for (i=0; i < FILE_COUNT; i++) {
fp = fopen(files[i], "r");
if (fp != NULL) {
if (!fnmatch("*BAT*", files[i], FNM_NOESCAPE)) {
fscanf(fp, "%lf", &temp_f);
capacity += temp_f;
} else {
fscanf(fp, "%d", &temp_i);
}
}
fclose(fp);
}
capacity /= 2.0;
if (temp_i) {
printf("%.1lf%%+\n", capacity);
} else {
printf("%.1lf%%-\n", capacity);
}
fflush(stdout);
}
int main() {
char *read_files[FILE_COUNT] = {
"/sys/class/power_supply/AC/online",
"/sys/class/power_supply/BAT0/capacity",
"/sys/class/power_supply/BAT1/capacity"
};
char *watch_files[FILE_COUNT] = {
"/sys/class/power_supply/AC/uevent",
"/sys/class/power_supply/BAT0/uevent",
"/sys/class/power_supply/BAT1/uevent"
};
int fd, wd, i;
char buf[BUF_LEN] __attribute__ ((aligned(8)));
ssize_t num_read = 1;
fd = inotify_init();
if (fd == -1) {
perror("inotify_init");
}
for (i=0; i < FILE_COUNT; i++) {
wd = inotify_add_watch(fd, watch_files[i], IN_ACCESS);
}
if (wd == -1) {
perror("inotify_add_watch");
}
battery_status(read_files);
while (num_read > 0) {
num_read = read(fd, buf, BUF_LEN);
if (num_read == 0 || num_read == -1) {
perror("read() from inotify fd returned 0");
break;
} else {
battery_status(read_files);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment