hybridgroup.gobot/drivers/gpio/button_driver.go

101 lines
2.2 KiB
Go
Raw Normal View History

2014-04-28 10:34:16 +08:00
package gpio
import (
"time"
"gobot.io/x/gobot"
2014-04-28 10:34:16 +08:00
)
// ButtonDriver Represents a digital Button
2014-04-28 10:34:16 +08:00
type ButtonDriver struct {
Active bool
pin string
name string
halt chan bool
2014-11-29 10:44:52 +08:00
interval time.Duration
2014-11-30 03:02:10 +08:00
connection DigitalReader
gobot.Eventer
2014-04-28 10:34:16 +08:00
}
// NewButtonDriver returns a new ButtonDriver with a polling interval of
// 10 Milliseconds given a DigitalReader and pin.
//
2016-07-14 00:44:47 +08:00
// 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"),
2014-11-30 03:02:10 +08:00
connection: a,
pin: pin,
Active: false,
Eventer: gobot.NewEventer(),
2014-11-29 10:44:52 +08:00
interval: 10 * time.Millisecond,
halt: make(chan bool),
2014-11-29 10:44:52 +08:00
}
if len(v) > 0 {
b.interval = v[0]
2014-04-28 10:34:16 +08:00
}
b.AddEvent(ButtonPush)
b.AddEvent(ButtonRelease)
2014-11-30 03:02:10 +08:00
b.AddEvent(Error)
return b
2014-04-28 10:34:16 +08:00
}
// Start starts the ButtonDriver and polls the state of the button at the given interval.
2014-09-28 02:34:13 +08:00
//
// Emits the Events:
// Push int - On button push
// Release int - On button release
// Error error - On button error
func (b *ButtonDriver) Start() (err error) {
2014-04-28 10:34:16 +08:00
state := 0
go func() {
for {
2014-11-30 03:02:10 +08:00
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
}
2014-04-28 10:34:16 +08:00
}
}()
return
2014-04-28 10:34:16 +08:00
}
2014-09-28 02:34:13 +08:00
// 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 }
2014-04-28 10:34:16 +08:00
// Connection returns the ButtonDrivers Connection
2014-11-30 03:02:10 +08:00
func (b *ButtonDriver) Connection() gobot.Connection { return b.connection.(gobot.Connection) }
2014-04-28 10:34:16 +08:00
func (b *ButtonDriver) update(newValue int) {
if newValue == 1 {
2014-04-28 10:34:16 +08:00
b.Active = true
b.Publish(ButtonPush, newValue)
2014-04-28 10:34:16 +08:00
} else {
b.Active = false
b.Publish(ButtonRelease, newValue)
2014-04-28 10:34:16 +08:00
}
}