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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
/* SPDX-License-Identifier: BSD-2-Clause */
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#define CUR_PATH "/sys/class/backlight/intel_backlight/brightness"
#define MAX_PATH "/sys/class/backlight/intel_backlight/max_brightness"
#define STEP 10
struct brightness {
int max_raw;
int raw;
int percents;
};
int readval(const char *path, int *dst)
{
FILE *f = fopen(path, "r");
int retval = 1;
if (f == NULL) {
perror(path);
goto end;
}
int raw;
if (fscanf(f, "%d", &raw) != 1) {
perror(path);
goto end;
}
*dst = raw;
retval = 0;
end:
if (f != NULL)
fclose(f);
return retval;
}
int get(struct brightness *dst)
{
int retval = 1;
if (readval(CUR_PATH, &dst->raw))
goto end;
if (readval(MAX_PATH, &dst->max_raw))
goto end;
dst->percents = (int)round((double)dst->raw*100/dst->max_raw);
retval = 0;
end:
return retval;
}
int set(struct brightness *src)
{
int retval = 1;
FILE *f = fopen(CUR_PATH, "w");
if (!f) {
perror(CUR_PATH);
goto end;
}
fprintf(f, "%d", src->raw);
retval = 0;
end:
if (f != NULL)
fclose(f);
return retval;
}
void adjust(struct brightness *b, int value)
{
b->percents += value;
if (b->percents > 100)
b->percents = 100;
else if (b->percents < 0)
b->percents = 0;
b->raw = (int)ceil((double)b->percents*b->max_raw/100);
}
void dump(struct brightness *b)
{
printf("%d (%d%%)\n", b->raw, b->percents);
}
int main(int argc, char** argv)
{
int retval = 0;
struct brightness b;
int adjust_val = STEP;
bool decr = false;
if (argc > 1 && strcmp(argv[1], "-h") == 0) {
printf("usage: %s [-h] [+/-]\n", argv[0]);
goto end;
}
if (get(&b))
goto end;
if (argc <= 1) {
dump(&b);
goto end;
}
if (strcmp(argv[1], "-") == 0)
decr = true;
else if (strcmp(argv[1], "+") != 0) {
fprintf(stderr, "%s: unknown argument\n", argv[1]);
retval = 1;
goto end;
}
if (decr)
adjust_val *= -1;
adjust(&b, adjust_val);
if (set(&b)) {
retval = 1;
goto end;
}
dump(&b);
end:
return retval;
}
|