forked from brian-armstrong/gpio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
286 lines (253 loc) · 5.97 KB
/
watcher.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package gpio
import (
"container/heap"
"fmt"
"io"
"os"
"strconv"
"syscall"
"time"
)
type Pin uint
type watcherAction int
const (
watcherAdd watcherAction = iota
watcherRemove
watcherClose
)
type watcherCmd struct {
pin Pin
action watcherAction
}
type watcherNotify struct {
pin Pin
value uint
}
type fdHeap []uintptr
func (h fdHeap) Len() int { return len(h) }
// Less is actually greater (we want a max heap)
func (h fdHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h fdHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *fdHeap) Push(x interface{}) {
*h = append(*h, x.(uintptr))
}
func (h *fdHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func (h fdHeap) FdSet() *syscall.FdSet {
fdset := &syscall.FdSet{}
for _, val := range h {
fdset.Bits[val/64] |= 1 << uint(val) % 64
}
return fdset
}
const watcherCmdChanLen = 32
const notifyChanLen = 32
// Watcher provides asynchronous notifications on input changes
// The user should supply it pins to watch with AddPin and then wait for changes with Watch
type Watcher struct {
pins map[uintptr]Pin
files map[uintptr]*os.File
fds fdHeap
cmdChan chan watcherCmd
notifyChan chan watcherNotify
}
// NewWatcher creates a new Watcher instance for asynchronous inputs
func NewWatcher() *Watcher {
w := &Watcher{
pins: make(map[uintptr]Pin),
files: make(map[uintptr]*os.File),
fds: fdHeap{},
cmdChan: make(chan watcherCmd, watcherCmdChanLen),
notifyChan: make(chan watcherNotify, notifyChanLen),
}
heap.Init(&w.fds)
go w.watch()
return w
}
func (w *Watcher) notify(fdset *syscall.FdSet) {
for _, fd := range w.fds {
if (fdset.Bits[fd/64] & (1 << uint(fd) % 64)) != 0 {
file := w.files[fd]
file.Seek(0, 0)
buf := make([]byte, 1)
_, err := file.Read(buf)
if err != nil {
if err == io.EOF {
w.removeFd(fd)
continue
}
fmt.Printf("failed to read pinfile, %s", err)
os.Exit(1)
}
msg := watcherNotify{
pin: w.pins[fd],
}
c := buf[0]
switch c {
case '0':
msg.value = 0
case '1':
msg.value = 1
default:
fmt.Printf("read inconsistent value in pinfile, %c", c)
os.Exit(1)
}
select {
case w.notifyChan <- msg:
default:
}
}
}
}
func (w *Watcher) fdSelect() {
timeval := &syscall.Timeval{
Sec: 1,
Usec: 0,
}
fdset := w.fds.FdSet()
n, err := syscall.Select(int(w.fds[0] 1), nil, nil, fdset, timeval)
if err != nil {
fmt.Printf("failed to call syscall.Select, %s", err)
os.Exit(1)
}
if n != 0 {
w.notify(fdset)
}
}
func (w *Watcher) addPin(p Pin) {
f, err := os.Open(fmt.Sprintf("/sys/class/gpio/gpio%d/value", p))
if err != nil {
fmt.Printf("failed to open gpio %d value file for reading\n", p)
os.Exit(1)
}
fd := f.Fd()
w.pins[fd] = p
w.files[fd] = f
heap.Push(&w.fds, fd)
}
func (w *Watcher) removeFd(fd uintptr) {
// heap operates on an array index, so search heap for fd
for index, v := range w.fds {
if v == fd {
heap.Remove(&w.fds, index)
break
}
}
f := w.files[fd]
f.Close()
delete(w.pins, fd)
delete(w.files, fd)
}
// removePin is only a wrapper around removeFd
// it finds fd given pin and then calls removeFd
func (w *Watcher) removePin(p Pin) {
// we don't index by pin, so go looking
for fd, pin := range w.pins {
if pin == p {
// found pin
w.removeFd(fd)
return
}
}
}
func (w *Watcher) doCmd(cmd watcherCmd) (shouldContinue bool) {
shouldContinue = true
switch cmd.action {
case watcherAdd:
w.addPin(cmd.pin)
case watcherRemove:
w.removePin(cmd.pin)
case watcherClose:
shouldContinue = false
}
return shouldContinue
}
func (w *Watcher) recv() (shouldContinue bool) {
for {
select {
case cmd := <-w.cmdChan:
shouldContinue = w.doCmd(cmd)
if !shouldContinue {
return
}
default:
shouldContinue = true
return
}
}
}
func (w *Watcher) watch() {
for {
// first we do a syscall.select with timeout if we have any fds to check
if len(w.fds) != 0 {
w.fdSelect()
} else {
// so that we don't churn when the fdset is empty, sleep as if in select call
time.Sleep(1 * time.Second)
}
if w.recv() == false {
return
}
}
}
func exportGPIO(p Pin) {
export, err := os.OpenFile("/sys/class/gpio/export", os.O_WRONLY, 0600)
if err != nil {
fmt.Printf("failed to open gpio export file for writing\n")
os.Exit(1)
}
export.Write([]byte(strconv.Itoa(int(p))))
export.Close()
time.Sleep(100 * time.Millisecond)
dir, err := os.OpenFile(fmt.Sprintf("/sys/class/gpio/gpio%d/direction", p), os.O_WRONLY, 0600)
if err != nil {
fmt.Printf("failed to open gpio %d direction file for writing\n", p)
os.Exit(1)
}
defer dir.Close()
dir.Write([]byte("in"))
edge, err := os.OpenFile(fmt.Sprintf("/sys/class/gpio/gpio%d/edge", p), os.O_WRONLY, 0600)
if err != nil {
fmt.Printf("failed to open gpio %d edge file for writing\n", p)
os.Exit(1)
}
defer edge.Close()
edge.Write([]byte("both"))
}
// AddPin adds a new pin to be watched for changes
// The pin provided should be the pin known by the kernel
func (w *Watcher) AddPin(p Pin) {
exportGPIO(p)
w.cmdChan <- watcherCmd{
pin: p,
action: watcherAdd,
}
}
// RemovePin stops the watcher from watching the specified pin
func (w *Watcher) RemovePin(p Pin) {
w.cmdChan <- watcherCmd{
pin: p,
action: watcherRemove,
}
}
// Watch blocks until one change occurs on one of the watched pins
// It returns the pin which changed and its new value
// Because the Watcher is not perfectly realtime it may miss very high frequency changes
// If that happens, it's possible to see consecutive changes with the same value
// Also, if the input is connected to a mechanical switch, the user of this library must deal with debouncing
func (w *Watcher) Watch() (p Pin, v uint) {
notification := <-w.notifyChan
return notification.pin, notification.value
}
// Close stops the watcher and releases all resources
func (w *Watcher) Close() {
w.cmdChan <- watcherCmd{
pin: 0,
action: watcherClose,
}
}