2014-04-27 19:34:16 -07:00
|
|
|
package gpio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/hybridgroup/gobot"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ButtonDriver struct {
|
|
|
|
gobot.Driver
|
2014-06-15 17:22:50 -07:00
|
|
|
Active bool
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
|
|
|
|
2014-05-22 21:29:37 -07:00
|
|
|
func NewButtonDriver(a DigitalReader, name string, pin string) *ButtonDriver {
|
2014-07-03 19:14:04 -07:00
|
|
|
b := &ButtonDriver{
|
|
|
|
Driver: *gobot.NewDriver(
|
|
|
|
name,
|
|
|
|
"ButtonDriver",
|
|
|
|
a.(gobot.AdaptorInterface),
|
|
|
|
pin,
|
|
|
|
),
|
2014-06-15 17:22:50 -07:00
|
|
|
Active: false,
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
2014-07-03 19:14:04 -07:00
|
|
|
|
2014-07-09 18:32:27 -07:00
|
|
|
b.AddEvent("push")
|
|
|
|
b.AddEvent("release")
|
2014-07-03 19:14:04 -07:00
|
|
|
|
|
|
|
return b
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
|
|
|
|
2014-06-15 17:22:50 -07:00
|
|
|
func (b *ButtonDriver) adaptor() DigitalReader {
|
2014-07-09 18:32:27 -07:00
|
|
|
return b.Adaptor().(DigitalReader)
|
2014-06-15 17:22:50 -07:00
|
|
|
}
|
|
|
|
|
2014-04-27 19:34:16 -07:00
|
|
|
func (b *ButtonDriver) Start() bool {
|
|
|
|
state := 0
|
2014-07-03 19:14:04 -07:00
|
|
|
gobot.Every(b.Interval(), func() {
|
2014-06-10 15:16:11 -07:00
|
|
|
newValue := b.readState()
|
|
|
|
if newValue != state && newValue != -1 {
|
|
|
|
state = newValue
|
|
|
|
b.update(newValue)
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
2014-06-06 18:58:04 -07:00
|
|
|
})
|
2014-04-27 19:34:16 -07:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
func (b *ButtonDriver) Halt() bool { return true }
|
|
|
|
func (b *ButtonDriver) Init() bool { return true }
|
|
|
|
|
|
|
|
func (b *ButtonDriver) readState() int {
|
2014-07-03 19:14:04 -07:00
|
|
|
return b.adaptor().DigitalRead(b.Pin())
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
|
|
|
|
2014-06-10 15:16:11 -07:00
|
|
|
func (b *ButtonDriver) update(newVal int) {
|
|
|
|
if newVal == 1 {
|
2014-04-27 19:34:16 -07:00
|
|
|
b.Active = true
|
2014-07-03 19:14:04 -07:00
|
|
|
gobot.Publish(b.Event("push"), newVal)
|
2014-04-27 19:34:16 -07:00
|
|
|
} else {
|
|
|
|
b.Active = false
|
2014-07-03 19:14:04 -07:00
|
|
|
gobot.Publish(b.Event("release"), newVal)
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
|
|
|
}
|