Repository navigation
Expand file tree
/
Copy pathmain.c
More file actions
84 lines (72 loc) · 2.21 KB
/
Copy pathmain.c
File metadata and controls
84 lines (72 loc) · 2.21 KB
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
74
75
76
77
78
79
80
81
82
83
84
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define CI(a, b) a##b
#define C(a, b) CI(a, b)
#define CL(a) C(a, __LINE__)
#define BAIL_FILE(n, f, o) \
char *n = f;\
FILE *C(n, F) = fopen(n, o);\
if (C(n, F) == NULL) {\
fprintf(stderr, "Couldn't open %s!", n);\
exit(1);\
}
#define WCBAIL_FILE(s, f) \
BAIL_FILE(CL(file), f, "w")\
fprintf(C(CL(file), F), s);\
fclose(C(CL(file), F))
#define RFBAIL_FILE(e, f) \
float e;\
BAIL_FILE(CL(e), f, "r")\
fscanf(C(CL(e), F), "%f", &e);\
fclose(C(CL(e), F))
void hibernate(void) {
WCBAIL_FILE("platform", "/sys/power/disk");
WCBAIL_FILE("disk", "/sys/power/state");
}
float battery_percent(void) {
RFBAIL_FILE(c, "/sys/class/power_supply/BAT1/charge_now");
RFBAIL_FILE(f, "/sys/class/power_supply/BAT1/charge_full");
return c / f;
}
void usage(char *name) {
fprintf(stderr, "Usage: %s [OPTIONS]...\n", name);
fputs(" -p <percent>\tThe percentage at which to hibernate (1<100)\n", stderr);
fputs(" -s <seconds>\tHow many seconds to sleep between checks\n", stderr);
fputs(" -T\t\tTest that hibernation works\n", stderr);
fputs(" -O\t\tEnable one-shot mode\n -v\t\tEnable verbose printing\n", stderr);
}
int main(int argc, char *argv[]) {
float percent = 0.05;
int opt = -1, seconds = 1;
bool once = false, test = false, verbose = false;
while ((opt = getopt(argc, argv, "p:s:vOTh")) != -1) {
switch (opt) {
case 'p': percent = atof(optarg) / 100; break;
case 's': seconds = atoi(optarg); break;
case 'v': verbose = true; break;
case 'O': once = true; break;
case 'T': test = true; break;
case 'h': default: usage(argv[0]); return 1;
}
}
if (test) hibernate();
if (percent >= 1.0 || percent <= 0.0) {
printf("Invalid percentage: %f\n", percent);
usage(argv[0]); return 2;
}
#ifndef DEBUG
if (verbose)
#endif
printf("settings = { .percent = %f, .seconds = %i .once = %i }\n", percent, seconds, once);
while(1) {
#ifndef DEBUG
if (verbose)
#endif
printf("%f\n", battery_percent());
if (percent >= battery_percent()) hibernate();
once ? exit(0) : sleep(seconds);
}
return 0;
}