-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdpms.go
More file actions
90 lines (72 loc) · 1.79 KB
/
dpms.go
File metadata and controls
90 lines (72 loc) · 1.79 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
85
86
87
88
89
90
package main
import (
"errors"
"fmt"
"log"
"time"
"github.com/jezek/xgb"
"github.com/jezek/xgb/dpms"
)
func ListenToDPMSEvents(X *xgb.Conn, pollInterval time.Duration) (<-chan bool, error) {
if err := dpms.Init(X); err != nil {
return nil, fmt.Errorf("DPMS not available: %v", err)
}
capReply, err := dpms.Capable(X).Reply()
if err != nil || capReply == nil || !capReply.Capable {
return nil, fmt.Errorf("DPMS not supported")
}
stateChannel := make(chan bool, 1)
lastState, err := isDPMSDisplayOn(X)
if err != nil {
return nil, errors.Join(errors.New("failure fetching initial dpms state"), err)
}
// start the polling loop
go func() {
defer close(stateChannel)
// Emit the initial state
stateChannel <- lastState
ticker := time.NewTicker(pollInterval)
defer ticker.Stop()
for {
_, ok := <-ticker.C
if !ok {
return
}
currentState, err := isDPMSDisplayOn(X)
if err != nil {
log.Println("failed to get display status", err)
return
}
if currentState != lastState {
lastState = currentState
stateChannel <- currentState
}
}
}()
return stateChannel, nil
}
func isDPMSDisplayOn(X *xgb.Conn) (bool, error) {
infoReply, err := dpms.Info(X).Reply()
if err != nil {
return false, errors.Join(errors.New("failed to query DPMS state"), err)
}
if infoReply == nil {
return false, errors.Join(errors.New("failed to query DPMS state"), errors.New("reply was nil"))
}
if !infoReply.State {
return false, errors.New("DPMS state is false")
}
switch infoReply.PowerLevel {
case dpms.DPMSModeStandby:
fallthrough
case dpms.DPMSModeSuspend:
fallthrough
case dpms.DPMSModeOff:
return false, nil
default:
log.Printf("Unknown DPMS power level (%d)\n", infoReply.PowerLevel)
fallthrough
case dpms.DPMSModeOn:
return true, nil
}
}