diff options
| author | Sam Light <sam@lightscale.co.uk> | 2025-09-10 19:37:28 +0100 |
|---|---|---|
| committer | Sam Light <sam@lightscale.co.uk> | 2025-09-10 19:37:28 +0100 |
| commit | d9b456d738e5013d48f41f5e6315ef7c22d6acf0 (patch) | |
| tree | 2e3722f5697cbf883c4b16edc87726b9e510bce1 /src/modules/battery.c | |
Initial commit
Diffstat (limited to 'src/modules/battery.c')
| -rw-r--r-- | src/modules/battery.c | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/src/modules/battery.c b/src/modules/battery.c new file mode 100644 index 0000000..6c656fe --- /dev/null +++ b/src/modules/battery.c @@ -0,0 +1,73 @@ +#include "battery.h" + +#include <stdlib.h> +#include <string.h> +#include <tgmath.h> + +#include <fcntl.h> +#include <unistd.h> + +#define UPDATE_FREQUENCY 20 + +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"); + b->last_update = 0; + + 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; + time_t now_time = time(NULL); + + if((now_time - b->last_update) >= UPDATE_FREQUENCY) { + b->last_update = now_time; + + now = battery_value(b->file_current); + + percentf = (100.0f / b->full) * now; + percent = round(percentf); + + snprintf(b->value, BATTERY_VALUE_SIZE, "%d%%", percent); + } +} |
