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

97 lines
2.3 KiB
Go
Raw Normal View History

2014-04-27 19:34:16 -07:00
package gpio
import (
"time"
"github.com/hybridgroup/gobot"
2014-04-27 19:34:16 -07:00
)
var _ gobot.Driver = (*ButtonDriver)(nil)
2014-09-27 11:34:13 -07:00
// Represents a digital Button
2014-04-27 19:34:16 -07:00
type ButtonDriver struct {
Active bool
pin string
name string
connection gobot.Connection
gobot.Eventer
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 {
b := &ButtonDriver{
name: name,
connection: a.(gobot.Adaptor),
pin: pin,
Active: false,
Eventer: gobot.NewEventer(),
2014-04-27 19:34:16 -07:00
}
2014-07-09 18:32:27 -07:00
b.AddEvent("push")
b.AddEvent("release")
b.AddEvent("error")
return b
2014-04-27 19:34:16 -07:00
}
func (b *ButtonDriver) adaptor() DigitalReader {
return b.Connection().(DigitalReader)
}
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
// "error" error - On button error
func (b *ButtonDriver) Start() (errs []error) {
2014-04-27 19:34:16 -07:00
state := 0
go func() {
for {
newValue, err := b.readState()
if err != nil {
gobot.Publish(b.Event("error"), err)
} else if newValue != state && newValue != -1 {
state = newValue
b.update(newValue)
}
//<-time.After(b.Interval())
<-time.After(100 * time.Millisecond)
2014-04-27 19:34:16 -07:00
}
}()
return
2014-04-27 19:34:16 -07:00
}
2014-09-27 11:34:13 -07:00
// Halt returns true on a successful halt of the driver
func (b *ButtonDriver) Halt() (errs []error) { return }
2014-04-27 19:34:16 -07:00
func (b *ButtonDriver) Name() string { return b.name }
func (b *ButtonDriver) Pin() string { return b.pin }
func (b *ButtonDriver) Connection() gobot.Connection { return b.connection }
func (b *ButtonDriver) String() string { return "ButtonDriver" }
func (b *ButtonDriver) ToJSON() *gobot.JSONDevice {
return &gobot.JSONDevice{
Name: b.Name(),
Driver: b.String(),
Connection: b.Connection().Name(),
//Commands: l.Commands(),
//Commands: l.Commands(),
}
}
func (b *ButtonDriver) readState() (val int, err error) {
return b.adaptor().DigitalRead(b.Pin())
2014-04-27 19:34:16 -07:00
}
func (b *ButtonDriver) update(newValue int) {
if newValue == 1 {
2014-04-27 19:34:16 -07:00
b.Active = true
gobot.Publish(b.Event("push"), newValue)
2014-04-27 19:34:16 -07:00
} else {
b.Active = false
gobot.Publish(b.Event("release"), newValue)
2014-04-27 19:34:16 -07:00
}
}