forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
button_driver.go
102 lines (88 loc) · 2.31 KB
/
button_driver.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
package gpio
import (
"time"
"gobot.io/x/gobot"
)
// ButtonDriver Represents a digital Button
type ButtonDriver struct {
Active bool
DefaultState int
pin string
name string
halt chan bool
interval time.Duration
connection DigitalReader
gobot.Eventer
}
// NewButtonDriver returns a new ButtonDriver with a polling interval of
// 10 Milliseconds given a DigitalReader and pin.
//
// Optionally accepts:
// time.Duration: Interval at which the ButtonDriver is polled for new information
func NewButtonDriver(a DigitalReader, pin string, v ...time.Duration) *ButtonDriver {
b := &ButtonDriver{
name: gobot.DefaultName("Button"),
connection: a,
pin: pin,
Active: false,
DefaultState: 0,
Eventer: gobot.NewEventer(),
interval: 10 * time.Millisecond,
halt: make(chan bool),
}
if len(v) > 0 {
b.interval = v[0]
}
b.AddEvent(ButtonPush)
b.AddEvent(ButtonRelease)
b.AddEvent(Error)
return b
}
// Start starts the ButtonDriver and polls the state of the button at the given interval.
//
// Emits the Events:
// Push int - On button push
// Release int - On button release
// Error error - On button error
func (b *ButtonDriver) Start() (err error) {
state := b.DefaultState
go func() {
for {
newValue, err := b.connection.DigitalRead(b.Pin())
if err != nil {
b.Publish(Error, err)
} else if newValue != state && newValue != -1 {
state = newValue
b.update(newValue)
}
select {
case <-time.After(b.interval):
case <-b.halt:
return
}
}
}()
return
}
// Halt stops polling the button for new information
func (b *ButtonDriver) Halt() (err error) {
b.halt <- true
return
}
// Name returns the ButtonDrivers name
func (b *ButtonDriver) Name() string { return b.name }
// SetName sets the ButtonDrivers name
func (b *ButtonDriver) SetName(n string) { b.name = n }
// Pin returns the ButtonDrivers pin
func (b *ButtonDriver) Pin() string { return b.pin }
// Connection returns the ButtonDrivers Connection
func (b *ButtonDriver) Connection() gobot.Connection { return b.connection.(gobot.Connection) }
func (b *ButtonDriver) update(newValue int) {
if newValue != b.DefaultState {
b.Active = true
b.Publish(ButtonPush, newValue)
} else {
b.Active = false
b.Publish(ButtonRelease, newValue)
}
}