hybridgroup.gobot/platforms/gpio/analog_sensor_driver.go

81 lines
2.1 KiB
Go
Raw Normal View History

2014-04-28 10:34:16 +08:00
package gpio
import (
"time"
"github.com/hybridgroup/gobot"
2014-04-28 10:34:16 +08:00
)
var _ gobot.Driver = (*AnalogSensorDriver)(nil)
2014-09-28 02:34:13 +08:00
// Represents an Analog Sensor
2014-04-28 10:34:16 +08:00
type AnalogSensorDriver struct {
name string
pin string
interval time.Duration
2014-11-30 03:02:10 +08:00
connection AnalogReader
gobot.Eventer
gobot.Commander
2014-04-28 10:34:16 +08:00
}
2014-09-28 02:34:13 +08:00
// NewAnalogSensorDriver returns a new AnalogSensorDriver given an AnalogReader, name and pin.
//
// Adds the following API Commands:
// "Read" - See AnalogSensor.Read
func NewAnalogSensorDriver(a AnalogReader, name string, pin string, v ...time.Duration) *AnalogSensorDriver {
2014-06-12 08:41:04 +08:00
d := &AnalogSensorDriver{
name: name,
2014-11-30 03:02:10 +08:00
connection: a,
pin: pin,
Eventer: gobot.NewEventer(),
Commander: gobot.NewCommander(),
interval: 10 * time.Millisecond,
2014-04-28 10:34:16 +08:00
}
if len(v) > 0 {
d.interval = v[0]
}
2014-11-30 03:02:10 +08:00
d.AddEvent(Data)
d.AddEvent(Error)
2014-07-10 09:32:27 +08:00
d.AddCommand("Read", func(params map[string]interface{}) interface{} {
val, err := d.Read()
return map[string]interface{}{"val": val, "err": err}
2014-06-12 08:41:04 +08:00
})
2014-06-12 08:41:04 +08:00
return d
2014-04-28 10:34:16 +08:00
}
2014-09-28 02:34:13 +08:00
// Starts the AnalogSensorDriver and reads the Analog Sensor at the given Driver.Interval().
// Returns true on successful start of the driver.
// Emits the Events:
// "data" int - Event is emitted on change and represents the current reading from the sensor.
func (a *AnalogSensorDriver) Start() (errs []error) {
2014-06-29 08:18:16 +08:00
value := 0
go func() {
for {
newValue, err := a.Read()
if err != nil {
2014-11-30 03:02:10 +08:00
gobot.Publish(a.Event(Error), err)
} else if newValue != value && newValue != -1 {
value = newValue
2014-11-30 03:02:10 +08:00
gobot.Publish(a.Event(Data), value)
}
<-time.After(a.interval)
2014-06-29 08:18:16 +08:00
}
}()
return
2014-06-29 08:18:16 +08:00
}
2014-09-28 02:34:13 +08:00
// Halt returns true on a successful halt of the driver
func (a *AnalogSensorDriver) Halt() (errs []error) { return }
func (a *AnalogSensorDriver) Name() string { return a.name }
func (a *AnalogSensorDriver) Pin() string { return a.pin }
2014-11-30 03:02:10 +08:00
func (a *AnalogSensorDriver) Connection() gobot.Connection { return a.connection.(gobot.Connection) }
2014-04-28 10:34:16 +08:00
2014-09-28 02:34:13 +08:00
// Read returns the current reading from the Analog Sensor
func (a *AnalogSensorDriver) Read() (val int, err error) {
2014-11-30 03:02:10 +08:00
return a.connection.AnalogRead(a.Pin())
2014-04-28 10:34:16 +08:00
}