2014-04-27 19:34:16 -07:00
|
|
|
package gpio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/hybridgroup/gobot"
|
|
|
|
)
|
|
|
|
|
2014-09-27 11:34:13 -07:00
|
|
|
// Represents a digital Button
|
2014-04-27 19:34:16 -07:00
|
|
|
type ButtonDriver struct {
|
|
|
|
gobot.Driver
|
2014-06-15 17:22:50 -07:00
|
|
|
Active bool
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
|
|
|
|
2014-09-27 11:34:13 -07:00
|
|
|
// NewButtonDriver return a new ButtonDriver given a DigitalReader, name and pin
|
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-09-27 11:34:13 -07:00
|
|
|
// Starts the ButtonDriver and reads the state of the button at the given Driver.Interval().
|
|
|
|
// Returns true on successful start of the driver.
|
|
|
|
//
|
|
|
|
// Emits the Events:
|
|
|
|
// "push" int - On button push
|
|
|
|
// "release" int - On button release
|
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
|
|
|
|
}
|
2014-09-27 11:34:13 -07:00
|
|
|
|
|
|
|
// Halt returns true on a successful halt of the driver
|
2014-04-27 19:34:16 -07:00
|
|
|
func (b *ButtonDriver) Halt() 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
|
|
|
}
|
|
|
|
}
|