summaryrefslogtreecommitdiff
path: root/src/modules/battery.c
blob: 18a68de8747d75f5f4222785329e3086d305a0be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "battery.h"

#include <stdlib.h>
#include <string.h>
#include <tgmath.h>

#include <fcntl.h>
#include <unistd.h>

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);
}