-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
112 lines (88 loc) · 1.79 KB
/
main.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
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/tothszabi/argonone/internal/fan"
"github.com/tothszabi/argonone/internal/log"
"github.com/tothszabi/argonone/internal/temperature"
)
const sleepDuration = 2 * time.Second
func main() {
os.Exit(run())
}
func run() int {
killSig := make(chan os.Signal, 1)
signal.Notify(killSig, os.Interrupt, os.Kill, syscall.SIGABRT, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
var readyChan = make(chan struct{}, 1)
var errChan = make(chan error, 1)
go controlFan(ctx, readyChan, errChan)
statusCode := 0
select {
case sig := <-killSig:
log.Info("Received signal:", sig)
cancel()
case err := <-errChan:
log.Error("Failure:", err)
cancel()
statusCode = 1
}
select {
case <-readyChan:
return statusCode
}
}
func controlFan(ctx context.Context, readyChan chan<- struct{}, errChan chan<- error) {
log.Info("Starting fan control")
var previousSpeed = -1
for {
temp, err := temperature.CurrentTemperature()
if err != nil {
errChan <- err
}
speed := calculateFanSpeed(temp)
if previousSpeed != speed {
err = setFanSpeed(speed)
if err != nil {
errChan <- err
}
previousSpeed = speed
}
select {
case <-time.After(sleepDuration):
// repeats loop
case <-ctx.Done():
stopFan()
log.Info("Fan control stopping")
readyChan <- struct{}{}
return
}
}
}
func calculateFanSpeed(temp int) int {
switch {
case temp < 55:
return 0
case temp < 60:
return 10
case temp < 65:
return 50
default:
return 100
}
}
func setFanSpeed(speed int) error {
if speed == 0 {
log.Info("Stopping fan")
} else {
log.Info("Setting fan speed to", fmt.Sprintf("%d%%", speed))
}
return fan.SetSpeed(speed)
}
func stopFan() {
setFanSpeed(0)
}