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
66
67
68
69
70
71
72
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);
}
}
|