-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpio_in.go
91 lines (79 loc) · 1.83 KB
/
gpio_in.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
package main
import (
"context"
rpio "github.com/stianeikeland/go-rpio"
"log"
"time"
)
func init() {
if err := rpio.Open(); err != nil {
log.Fatal(err)
}
}
// GpioReader
type GpioReader struct {
C chan bool
config GpioReaderCfg
lastState rpio.State
reported rpio.State
consecutiveReads int64
}
// NewGpioReader takes a configuration value and returns a GpioReader instance
func NewGpioReader(c GpioReaderCfg) *GpioReader {
if c.ReadInterval <= 0 {
c.ReadInterval = 50
}
if c.MinReadOpened <= 0 {
c.MinReadOpened = 1
}
if c.MinReadClosed <= 0 {
c.MinReadClosed = 1
}
g := &GpioReader{
C: make(chan bool, 32),
config: c,
lastState: 2,
reported: 2,
consecutiveReads: 0,
}
return g
}
func (g *GpioReader) Start(ctx context.Context) {
defer close(g.C)
pin := rpio.Pin(g.config.Pin)
pin.Input()
var openValue rpio.State = 0
if g.config.Invert {
openValue = 1
}
tick := time.NewTicker(time.Millisecond * time.Duration(g.config.ReadInterval))
log.Printf("[gpioIn:%d] Starting ticker running every %dms", g.config.Pin, g.config.ReadInterval)
for {
state := pin.Read()
switch state {
case g.lastState:
g.consecutiveReads++
default:
log.Printf("[gpioIn:%d] Got new state: %d", g.config.Pin, state)
g.lastState = state
g.consecutiveReads = 1
}
minConsecutive := g.config.MinReadClosed
if g.lastState == openValue {
minConsecutive = g.config.MinReadOpened
}
if g.reported != g.lastState && g.consecutiveReads >= minConsecutive {
log.Printf("[gpioIn:%d] Got %d consecutive reads, reporting %b", g.config.Pin, g.consecutiveReads, state == openValue)
if g.C != nil {
g.C <- state == openValue
}
g.reported = g.lastState
}
select {
case <-ctx.Done():
return
case <-tick.C:
continue
}
}
}