-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrightness.go
121 lines (94 loc) · 2.09 KB
/
brightness.go
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
package main
import (
// "os"
"errors"
"fmt"
"io/ioutil"
"math"
"path"
"strconv"
"strings"
)
// Port of https://github.com/kevva/brightness/blob/master/lib/linux.js
const dir = "/sys/class/backlight"
func getBrightnessH(device string) (int, error) {
b, err := ioutil.ReadFile(path.Join(dir, device, "brightness"))
if err != nil {
return 0, err
}
n, err := strconv.Atoi(strings.TrimSpace(string(b)))
if err != nil {
return 0, err
}
return n, nil
}
func getMaxBrightnessH(device string) (int, error) {
b, err := ioutil.ReadFile(path.Join(dir, device, "max_brightness"))
if err != nil {
return 0, err
}
n, err := strconv.Atoi(strings.TrimSpace(string(b)))
if err != nil {
return 0, err
}
return n, nil
}
func setBrightnessH(device string, val int) error {
return ioutil.WriteFile(path.Join(dir, device, "brightness"), []byte(fmt.Sprint(val)), 0644)
}
func getBacklightH() (string, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return "", err
}
if len(files) == 0 {
return "", errors.New("No backlight device found")
}
return files[0].Name(), nil
}
func getBrightness() (float64, error) {
device, err := getBacklightH()
if err != nil {
return 0, err
}
max, err := getMaxBrightnessH(device)
if err != nil {
return 0, err
}
current, err := getBrightnessH(device)
if err != nil {
return 0, err
}
return float64(current) / float64(max), nil
}
func setBrightness(val float64) error {
if val < 0 {
val = 0
} else if val > 1 {
val = 1
}
device, err := getBacklightH()
if err != nil {
return err
}
max, err := getMaxBrightnessH(device)
if err != nil {
return err
}
brightness := int(math.Floor(val * float64(max)))
return setBrightnessH(device, brightness)
}
func withBrightness(f func(float64) float64) error {
b, err := getBrightness()
if err != nil {
return err
}
end := f(b)
return setBrightness(end)
}
func decBrightness(val float64) error {
return withBrightness(func(c float64) float64 { return c - val })
}
func incBrightness(val float64) error {
return withBrightness(func(c float64) float64 { return c + val })
}