#include "battery.h" #include #include #include #include #include static int open_battery_file(const char * name) { char path[128]; snprintf(path, 128, "/sys/class/power_supply/BAT0/%s", name); return open(path, O_RDONLY); } static int battery_value(int file) { int val = 0; char buf[16]; memset(&buf, '\0', 16); lseek(file, 0, SEEK_SET); read(file, &buf, sizeof(char) * 16); sscanf(buf, "%d", &val); return val; } struct battery * battery_new() { struct battery * b = malloc(sizeof(struct battery)); int file = open_battery_file("charge_full"); b->full = battery_value(file); b->file_current = open_battery_file("charge_now"); close(file); return b; } void battery_free(struct battery * b) { close(b->file_current); free(b); } void battery_update(struct battery * b) { int now; float percentf; int percent; now = battery_value(b->file_current); percentf = (100.0f / b->full) * now; percent = round(percentf); snprintf(b->value, BATTERY_VALUE_SIZE, "%d%%", percent); }