1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-27 13:48:56 +08:00
hybridgroup.gobot/drivers/gpio/button_driver.go

117 lines
2.4 KiB
Go
Raw Normal View History

2014-04-27 19:34:16 -07:00
package gpio
import (
"time"
"gobot.io/x/gobot/v2"
2014-04-27 19:34:16 -07:00
)
// ButtonDriver Represents a digital Button
2014-04-27 19:34:16 -07:00
type ButtonDriver struct {
*Driver
gobot.Eventer
pin string
active bool
defaultState int
halt chan bool
interval time.Duration
2014-04-27 19:34:16 -07:00
}
// NewButtonDriver returns a new ButtonDriver with a polling interval of
// 10 Milliseconds given a DigitalReader and pin.
//
2016-07-13 10:44:47 -06: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{
Driver: NewDriver(a.(gobot.Connection), "Button"),
Eventer: gobot.NewEventer(),
pin: pin,
active: false,
defaultState: 0,
interval: 10 * time.Millisecond,
halt: make(chan bool),
2014-11-28 18:44:52 -08:00
}
b.afterStart = b.initialize
b.beforeHalt = b.shutdown
2014-11-28 18:44:52 -08:00
if len(v) > 0 {
b.interval = v[0]
2014-04-27 19:34:16 -07:00
}
b.AddEvent(ButtonPush)
b.AddEvent(ButtonRelease)
2014-11-29 11:02:10 -08:00
b.AddEvent(Error)
return b
2014-04-27 19:34:16 -07:00
}
// Pin returns the ButtonDrivers pin
func (b *ButtonDriver) Pin() string { return b.pin }
// Active gets the current state
func (b *ButtonDriver) Active() bool {
// ensure that read and write can not interfere
b.mutex.Lock()
defer b.mutex.Unlock()
return b.active
}
// SetDefaultState for the next start.
func (b *ButtonDriver) SetDefaultState(s int) {
// ensure that read and write can not interfere
b.mutex.Lock()
defer b.mutex.Unlock()
b.defaultState = s
}
// initialize the ButtonDriver and polls the state of the button at the given interval.
2014-09-27 11:34:13 -07:00
//
// Emits the Events:
//
// Push int - On button push
// Release int - On button release
// Error error - On button error
func (b *ButtonDriver) initialize() error {
state := b.defaultState
go func() {
for {
newValue, err := b.connection.(DigitalReader).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-27 19:34:16 -07:00
}
}()
return nil
2014-04-27 19:34:16 -07:00
}
2014-09-27 11:34:13 -07:00
func (b *ButtonDriver) shutdown() error {
b.halt <- true
return nil
}
func (b *ButtonDriver) update(newValue int) {
// ensure that read and write can not interfere
b.mutex.Lock()
defer b.mutex.Unlock()
if newValue != b.defaultState {
b.active = true
b.Publish(ButtonPush, newValue)
2014-04-27 19:34:16 -07:00
} else {
b.active = false
b.Publish(ButtonRelease, newValue)
2014-04-27 19:34:16 -07:00
}
}