summaryrefslogtreecommitdiff
path: root/src/modules/battery.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/modules/battery.c')
-rw-r--r--src/modules/battery.c78
1 files changed, 57 insertions, 21 deletions
diff --git a/src/modules/battery.c b/src/modules/battery.c
index 18a68de..02379c8 100644
--- a/src/modules/battery.c
+++ b/src/modules/battery.c
@@ -3,63 +3,99 @@
#include <stdlib.h>
#include <string.h>
#include <tgmath.h>
-
+#include <stdbool.h>
+#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
+#define VALUE_SIZE 16
+#define BATTERY_PATH "/sys/class/power_supply/BAT1/"
+
+struct battery {
+ int status;
+ int capacity;
+ time_t last_updated;
+ char value[VALUE_SIZE];
+};
+
static int
open_battery_file(const char * name)
{
char path[128];
- snprintf(path, 128, "/sys/class/power_supply/BAT0/%s", name);
+ snprintf(path, 128, "%s%s", BATTERY_PATH, name);
return open(path, O_RDONLY);
}
static int
battery_value(int file)
{
+ const size_t buf_size = 4;
int val = 0;
- char buf[16];
+ char buf[buf_size];
- memset(&buf, '\0', 16);
+ memset(&buf, '\0', buf_size);
lseek(file, 0, SEEK_SET);
- read(file, &buf, sizeof(char) * 16);
+ read(file, &buf, sizeof(char) * buf_size);
sscanf(buf, "%d", &val);
return val;
}
-struct battery *
-battery_new()
+static bool
+battery_status_discharging(int file)
{
- struct battery * b = malloc(sizeof(struct battery));
- int file = open_battery_file("charge_full");
+ const size_t buf_size = 16;
+ char buf[buf_size];
- b->full = battery_value(file);
- b->file_current = open_battery_file("charge_now");
+ memset(&buf, '\0', buf_size);
+ lseek(file, 0, SEEK_SET);
+ read(file, &buf, sizeof(char) * buf_size);
- close(file);
+ return strncmp(buf, "Discharging\n", buf_size) == 0;
+}
+struct battery *
+battery_new()
+{
+ struct battery * b = malloc(sizeof(struct battery));
+ b->last_updated = 0;
+ b->capacity = open_battery_file("capacity");
+ b->status = open_battery_file("status");
return b;
}
void
battery_free(struct battery * b)
{
- close(b->file_current);
+ close(b->status);
+ close(b->capacity);
free(b);
}
void battery_update(struct battery * b)
{
- int now;
- float percentf;
- int percent;
-
- now = battery_value(b->file_current);
+ int cap = battery_value(b->capacity);
+ bool discharge = battery_status_discharging(b->status);
+ snprintf(
+ b->value, VALUE_SIZE,
+ "%s% 4d%%",
+ discharge ? "\uf241" : "\uf0e7",
+ cap);
+}
- percentf = (100.0f / b->full) * now;
- percent = round(percentf);
+const char *
+battery_get_val(struct battery * b)
+{
+ return b->value;
+}
- snprintf(b->value, BATTERY_VALUE_SIZE, "%d%%", percent);
+bool
+battery_should_update(struct battery * b, time_t now, unsigned short limit)
+{
+ double time_diff = difftime(now, b->last_updated);
+ if(time_diff >= limit) {
+ b->last_updated = now;
+ return true;
+ }
+ return false;
}